diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bin Bulaye Baarati full movie in hindi hd 1080p download torrent Where to find the best links and sources for this film.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bin Bulaye Baarati full movie in hindi hd 1080p download torrent Where to find the best links and sources for this film.md deleted file mode 100644 index 8d6387601401c38a23b5c6a7b4591ca802960974..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bin Bulaye Baarati full movie in hindi hd 1080p download torrent Where to find the best links and sources for this film.md +++ /dev/null @@ -1,138 +0,0 @@ - -

Bin Bulaye Baraati: A Comedy of Errors

-

Bin Bulaye Baraati is a 2011 Hindi comedy film directed by Chandrakant Singh and starring Aftab Shivdasani, Priyanka Kothari, Rajpal Yadav, Om Puri, Shakti Kapoor and many more. The film is a hilarious story of a group of misfits who get involved in a series of mishaps while trying to escape from a gangster and the police.

-

The film was released on June 17, 2011 and received mixed reviews from critics and audiences. However, it became a cult hit among comedy lovers who enjoyed its slapstick humor, witty dialogues and funny situations. The film also features some catchy songs and dance numbers that add to its entertainment value.

-

Bin Bulaye Baarati full movie in hindi hd 1080p download torrent


Download File ✒ ✒ ✒ https://byltly.com/2uKxgx



-

If you are looking for a fun-filled movie that will make you laugh out loud, then Bin Bulaye Baraati is a perfect choice for you. In this article, we will tell you how you can download Bin Bulaye Baraati full movie in HD 1080p, watch it online or enjoy it with your friends and family.

-

How to Download Bin Bulaye Baraati Full Movie in HD 1080p

-

One of the best ways to enjoy Bin Bulaye Baraati is to download it in HD 1080p quality. This way, you can watch the movie in high definition and appreciate its visuals and sound effects. You can also watch the movie offline at your convenience and without any interruptions.

-

There are many sites that offer Bin Bulaye Baraati full movie download in HD 1080p. However, not all of them are reliable or safe. Some of them may contain viruses, malware or spyware that can harm your device or compromise your privacy. Some of them may also have low-quality or incomplete downloads that can ruin your viewing experience.

-

Therefore, you need to be careful and choose a trusted site that provides Bin Bulaye Baraati full movie download in HD 1080p. Here are some of the best sites that we recommend:

- -

To download Bin Bulaye Baraati full movie using a torrent client, you need to have a torrent software installed on your device such as BitTorrent, uTorrent or Vuze. You also need to find a torrent file or magnet link that contains Bin Bulaye Baraati full movie in HD 1080p. You can find such files or links on various torrent sites such as The Pirate Bay, Kickass Torrents or RARBG. However, be aware that downloading movies from torrent sites may be illegal or risky in some countries or regions. Therefore, use a VPN service to protect your identity and data while downloading movies from torrent sites.

-

To download Bin Bulaye Baraati full movie using a torrent client, follow these steps:

-
    -
  1. Go to any torrent site that has Bin Bulaye Baraati full movie in HD 1080p such as The Pirate Bay, Kickass Torrents or RARBG.
  2. -
  3. Search for Bin Bulaye Baraati in the search bar.
  4. -
  5. Select the torrent file or magnet link that has Bin Bulaye Baraati full movie in HD 1080p.
  6. -
  7. Open the torrent file or magnet link with your torrent software.
  8. -
  9. Select your desired location for saving the file and start downloading.
  10. -
-

How to Watch Bin Bulaye Baraati Full Movie Online

-

If you don't want to download Bin Bulaye Baraati full movie in HD 1080p, you can also watch it online on various streaming platforms. This way, you can save your storage space and bandwidth and watch the movie anytime and anywhere with an internet connection. You can also enjoy other features such as subtitles, captions, ratings, reviews and more.

-

There are many platforms that offer Bin Bulaye Baraati full movie online streaming. However, not all of them are legal or safe. Some of them may contain ads, pop-ups or malware that can disrupt your viewing experience or harm your device or data. Some of them may also have low-quality or incomplete streams that can spoil your enjoyment.

-

Bin Bulaye Baarati hindi movie hd torrent download
-Download Bin Bulaye Baarati full movie in 1080p hindi
-Bin Bulaye Baarati hd hindi movie torrent link
-How to download Bin Bulaye Baarati movie in hindi hd
-Bin Bulaye Baarati full movie 1080p hindi torrent magnet
-Watch Bin Bulaye Baarati hindi movie online hd
-Bin Bulaye Baarati hindi movie download 1080p free
-Bin Bulaye Baarati full movie torrent download in hd hindi
-Bin Bulaye Baarati hd movie hindi torrent file
-Bin Bulaye Baarati movie download hindi 1080p quality
-Bin Bulaye Baarati hindi movie 1080p torrent download site
-Bin Bulaye Baarati full movie in hd hindi download link
-Bin Bulaye Baarati movie torrent download hd hindi version
-Bin Bulaye Baarati hindi movie hd 1080p free download
-Bin Bulaye Baarati full movie in hindi hd torrent online
-Bin Bulaye Baarati movie download torrent in hindi hd 1080p
-Bin Bulaye Baarati hd hindi movie free torrent download
-Bin Bulaye Baarati full movie 1080p hindi torrent online watch
-Bin Bulaye Baarati movie hd hindi torrent download free
-Bin Bulaye Baarati full movie in hindi 1080p download link
-Bin Bulaye Baarati hindi movie torrent download 1080p hd quality
-Bin Bulaye Baarati full movie in hd hindi torrent magnet link
-Bin Bulaye Baarati movie download in hindi hd 1080p free
-Bin Bulaye Baarati full movie torrent download in hindi hd quality
-Bin Bulaye Baarati hd movie in hindi torrent download link
-Bin Bulaye Baarati full movie in hindi 1080p torrent download free
-Bin Bulaye Baarati movie hd 1080p hindi torrent file download
-Bin Bulaye Baarati full movie in hd hindi free download torrent
-Bin Bulaye Baarati movie download 1080p hd hindi torrent magnet
-Bin Bulaye Baarati full movie in hindi hd online watch torrent
-Bin Bulaye Baarati movie torrent download in hd 1080p hindi quality
-Bin Bulaye Baarati full movie in hindi 1080p free download link
-Bin Bulaye Baarati hd movie torrent download in hindi free
-Bin Bulaye Baarati full movie online watch in hd 1080p hindi
-Bin Bulaye Baarati movie free download in hd 1080p hindi torrent link
-Bin Bulaye Baarati full movie in hindi torrent download site 1080p quality
-Bin Bulaye Baarati hd 1080p movie in hindi free torrent file
-Bin Bulaye Baarati full movie watch online in hd 1080p hindi torrent link
-Bin Bulaye Baarati movie in hd 1080p hindi torrent magnet download free
-Bin Bulaye Baarati full movie in hindi free download site 1080p quality
-Bin Bulaye Baarati hd 1080p movie torrent file download in hindi free
-Bin Bulaye Baarati full movie online watch free in hd 1080p hindi quality
-Bin Bulaye Baarati movie in hd 1080p hindi free download link torrent magnet

-

Therefore, you need to be careful and choose a legal and safe platform that provides Bin Bulaye Baraati full movie online streaming. Here are some of the best platforms that we recommend:

- -

How to Enjoy Bin Bulaye Baraati Full Movie with Friends and Family

-

If you want to make your movie-watching experience more fun and memorable, you can enjoy Bin Bulaye Baraati full movie with your friends and family. Here are some tips on how to do that:

- -

Conclusion

-

In conclusion, Bin Bulaye Baraati is a hilarious comedy film that will make you laugh out loud with its slapstick humor, witty dialogues and funny situations. The film also features some catchy songs and dance numbers that add to its entertainment value. If you are looking for a fun-filled movie that will make you happy, then Bin Bulaye Baraati is a perfect choice for you.

-

In this article, we have told you how you can download Bin Bulaye Baraati full movie in HD 1080p, watch it online or enjoy it with your friends and family. We have also provided you with some of the best sites and platforms that offer Bin Bulaye Baraati full movie download or streaming in HD quality. We hope you found this article helpful and informative.

-

If you liked this article, please share it with your friends and family who are also interested in watching Bin Bulaye Baraati full movie. Also, don't forget to leave your feedback or suggestions in the comments section below. We would love to hear from you.

-

Thank you for reading this article. Have a great day!

-

Frequently Asked Questions (FAQs)

-
    -
  1. What is the genre of Bin Bulaye Baraati?
  2. -

    Bin Bulaye Baraati is a comedy film that belongs to the subgenre of comedy of errors.

    -
  3. Who are the main actors in Bin Bulaye Baraati?
  4. -

    The main actors in Bin Bulaye Baraati are Aftab Shivdasani, Priyanka Kothari, Rajpal Yadav, Om Puri, Shakti Kapoor and many more.

    -
  5. Who is the director of Bin Bulaye Baraati?
  6. -

    The director of Bin Bulaye Baraati is Chandrakant Singh.

    -
  7. When was Bin Bulaye Baraati released?
  8. -

    Bin Bulaye Baraati was released on June 17, 2011.

    -
  9. How long is Bin Bulaye Baraati?
  10. -

    Bin Bulaye Baraati is 2 hours and 18 minutes long.

    -
-

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download and Install Autodesk 123D Design 64-Bit in Minutes.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download and Install Autodesk 123D Design 64-Bit in Minutes.md deleted file mode 100644 index 55015b7f13367a26d1103af7390e4c4b80d9f3ad..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download and Install Autodesk 123D Design 64-Bit in Minutes.md +++ /dev/null @@ -1,45 +0,0 @@ - -

How to Download and Install Autodesk 123D Design 64-Bit for Windows

-

Autodesk 123D Design is a free and powerful 3D modeling software that lets you create and edit 3D designs with ease. You can use it to design anything from simple shapes to complex objects, and prepare them for 3D printing or fabrication. Autodesk 123D Design is also compatible with other Autodesk products, such as ReCap, Fusion 360, and Tinkercad.

-

123d download 64 bit


Download File ★★★ https://byltly.com/2uKwRR



-

If you want to download and install Autodesk 123D Design 64-bit for Windows, you will need to follow these steps:

-
    -
  1. Go to https://archive.org/details/123-d-design-win64-installer and click on the "DOWNLOAD OPTIONS" button on the right side of the page.
  2. -
  3. Select the "ZIP" option and wait for the download to finish. The file size is about 371 MB.
  4. -
  5. Once the download is done, right-click on the .zip file and extract it using a program like 7-Zip or WinRAR.
  6. -
  7. Double-click on the extracted folder and run the "Setup.exe" file as an administrator.
  8. -
  9. Follow the instructions on the screen to complete the installation process. You will need to accept the license agreement, choose a destination folder, and select the components you want to install.
  10. -
  11. Once the installation is finished, you can launch Autodesk 123D Design from your desktop or start menu.
  12. -
-

Congratulations! You have successfully downloaded and installed Autodesk 123D Design 64-bit for Windows. You can now start creating your own 3D models and projects with this amazing software.

- -

What are the Features of Autodesk 123D Design?

-

Autodesk 123D Design is not just a simple 3D modeling software. It has many features that make it stand out from other software in the same category. Here are some of them:

- -

What are the Requirements of Autodesk 123D Design?

-

If you want to run Autodesk 123D Design on your Windows PC, you will need to meet these minimum requirements:

- - - - - - - -
OSWindows 7 64-bit / Windows 8 64-bit / Windows 10 64-bit
ProcessorDual core processor
Memory4 GB RAM
GraphicsDedicated graphics card with DirectX 10 support
Storage1 GB available space
Internet connectionRequired for installation and online features
-

If you want to run Autodesk 123D Design on higher settings, you will need to meet these recommended requirements:

-

- - - - - - - -
OSWindows 7 64-bit / Windows 8 64-bit / Windows 10 64-bit
ProcessorQuad core processor
Memory8 GB RAM
GraphicsDedicated graphics card with DirectX 11 support
Storage2 GB available space
Internet connectionRequired for installation and online features

ddb901b051
-
-
\ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/HD Online Player (xmlbar video downloader vip crack) The Ultimate Solution for Online Video Lovers.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/HD Online Player (xmlbar video downloader vip crack) The Ultimate Solution for Online Video Lovers.md deleted file mode 100644 index fff8b6f2b98312e5d17d30f62c71e0050ca513dc..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/HD Online Player (xmlbar video downloader vip crack) The Ultimate Solution for Online Video Lovers.md +++ /dev/null @@ -1,133 +0,0 @@ -
-

HD Online Player (xmlbar video downloader vip crack)

-

Do you want to watch and download videos from various websites in high definition? Do you want to enjoy unlimited downloads without any restrictions or ads? If yes, then you need HD Online Player (xmlbar video downloader vip crack). This is a powerful combination of a video player and a video downloader that can help you access and save any online video you want. In this article, we will explain what HD Online Player, xmlbar video downloader, and vip crack are, and how to use them to download videos with ease.

-

HD Online Player (xmlbar video downloader vip crack)


Download Ziphttps://byltly.com/2uKxAw



-

What is HD Online Player?

-

HD Online Player is a free software that allows you to watch online videos in high quality. It supports various formats, such as MP4, MKV, AVI, FLV, WMV, etc. It also supports subtitles, playlists, and multiple languages. You can use HD Online Player to watch videos from YouTube, Vimeo, Dailymotion, Facebook, and other popular websites. You can also use it to play local videos on your computer.

-

Features of HD Online Player

- -

How to use HD Online Player

-
    -
  1. Download and install HD Online Player from its official website or from a trusted source.
  2. -
  3. Launch HD Online Player and click on the "Online" tab to access the built-in browser.
  4. -
  5. Type in the website address or the keyword of the video you want to watch in the search bar and press enter.
  6. -
  7. Select the video from the search results and click on it to start playing.
  8. -
  9. You can adjust the volume, brightness, playback speed, aspect ratio, and other settings by using the buttons on the bottom or by right-clicking on the screen.
  10. -
  11. You can also add subtitles, change languages, create playlists, and switch between full-screen and windowed mode by using the buttons on the top or by right-clicking on the screen.
  12. -
-

What is xmlbar video downloader?

-

xmlbar video downloader is a free software that allows you to download online videos from various websites. It supports more than 1000 websites, such as YouTube, Vimeo, Dailymotion, Facebook, Instagram, TikTok, etc. It also supports various formats, such as MP4, FLV, 3GP, WEBM, etc. You can use xmlbar video downloader to download videos in different resolutions, from 144p to 4K.

-

Features of xmlbar video downloader

- -

How to use xmlbar video downloader

-
    -
  1. Download and install xmlbar video downloader from its official website or from a trusted source.
  2. -
  3. Launch xmlbar video downloader and click on the "Add URL" button on the top left corner.
  4. -
  5. Paste the URL of the video you want to download into the pop-up window and click "OK".
  6. -
  7. Select the output format and quality from the drop-down menu and click "Download".
  8. -
  9. You can also drag-and-drop videos from your browser or other sources into the app window to start downloading.
  10. -
  11. You can view the download progress, pause or resume downloads, delete downloads, and open downloaded files by using the buttons on the right side of each item.
  12. -
-

What is vip crack?

-

vip crack is a special code that can unlock all the features and functions of HD Online Player and xmlbar video downloader. With vip crack, you can enjoy unlimited downloads without any restrictions or ads. You can also access more websites, formats, resolutions, and options. vip crack is not available for free. You have to pay a certain amount of money to get it. However, there are some ways to get vip crack for free or at a lower price.

-

HD Online Player (xmlbar video downloader vip crack) free download
-HD Online Player (xmlbar video downloader vip crack) for Windows 10
-HD Online Player (xmlbar video downloader vip crack) review
-HD Online Player (xmlbar video downloader vip crack) alternative
-HD Online Player (xmlbar video downloader vip crack) tutorial
-How to use HD Online Player (xmlbar video downloader vip crack)
-How to install HD Online Player (xmlbar video downloader vip crack)
-How to get HD Online Player (xmlbar video downloader vip crack) for free
-How to crack HD Online Player (xmlbar video downloader vip crack)
-How to download videos with HD Online Player (xmlbar video downloader vip crack)
-Best settings for HD Online Player (xmlbar video downloader vip crack)
-Benefits of HD Online Player (xmlbar video downloader vip crack)
-Features of HD Online Player (xmlbar video downloader vip crack)
-Comparison of HD Online Player (xmlbar video downloader vip crack) and other video downloaders
-Pros and cons of HD Online Player (xmlbar video downloader vip crack)
-Tips and tricks for HD Online Player (xmlbar video downloader vip crack)
-Troubleshooting HD Online Player (xmlbar video downloader vip crack)
-FAQs about HD Online Player (xmlbar video downloader vip crack)
-Testimonials of HD Online Player (xmlbar video downloader vip crack) users
-Customer support for HD Online Player (xmlbar video downloader vip crack)
-HD Online Player (xmlbar video downloader vip crack) vs Media Lounge APK
-HD Online Player (xmlbar video downloader vip crack) for Mac
-HD Online Player (xmlbar video downloader vip crack) for Android
-HD Online Player (xmlbar video downloader vip crack) for iOS
-HD Online Player (xmlbar video downloader vip crack) for Linux
-HD Online Player (xmlbar video downloader vip crack) for Chromebook
-HD Online Player (xmlbar video downloader vip crack) for Firestick
-HD Online Player (xmlbar video downloader vip crack) for Roku
-HD Online Player (xmlbar video downloader vip crack) for Smart TV
-HD Online Player (xmlbar video downloader vip crack) for Xbox One
-HD Online Player (xmlbar video downloader vip crack) for PS4
-HD Online Player (xmlbar video downloader vip crack) for PC
-HD Online Player (xmlbar video downloader vip crack) for laptop
-HD Online Player (xmlbar video downloader vip crack) for tablet
-HD Online Player (xmlbar video downloader vip crack) for phone
-Download YouTube videos with HD Online Player (xmlbar video downloader vip crack)
-Download Netflix videos with HD Online Player (xmlbar video downloader vip crack)
-Download Hulu videos with HD Online Player (xmlbar video downloader vip crack)
-Download Amazon Prime videos with HD Online Player (xmlbar video downloader vip crack)
-Download Disney+ videos with HD Online Player (xmlbar video downloader vip crack)
-Download HBO Max videos with HD Online Player (xmlbar video downloader vip crack)
-Download Vimeo videos with HD Online Player (xmlbar video downloader vip crack)
-Download Dailymotion videos with HD Online Player (xmlbar video downloader vip crack)
-Download TikTok videos with HD Online Player (xmlbar video downloader vip crack)
-Download Instagram videos with HD Online Player (xmlbar video downloader vip crack)

-

Benefits of vip crack

- -

How to get vip crack

- -

How to download videos with HD Online Player (xmlbar video downloader vip crack)

-

If you have HD Online Player (xmlbar video downloader vip crack), you can download videos with ease. Here are the steps you need to follow:

-

Step 1: Install HD Online Player and xmlbar video downloader

-

You need to install both HD Online Player and xmlbar video downloader on your computer. You can download them from their official websites or from trusted sources. Make sure you have enough space on your hard drive for installation and downloading videos.

-

Step 2: Open HD Online Player and find the video you want to download

-

You need to open HD Online Player and click on the "Online" tab. You will see a built-in browser where you can search and browse online videos. You need to find the video you want to download from any website. You can use keywords or website addresses in the search bar. You can also use filters or categories to narrow down your search results. Once you find the video you want to download, click on it to start playing it.

-

Step 3: Copy the video URL and paste it into xmlbar video downloader

-

You need to copy the URL of the video you want to download from HD Online Player. You can do this by right-clicking on the screen and selecting "Copy URL". Alternatively "Add URL" button on the top left corner of xmlbar video downloader and pasting it into the pop-up window. Alternatively, you can drag-and-drop the URL from HD Online Player into xmlbar video downloader.

-

Step 4: Choose the output format and quality and click download

-

You need to choose the output format and quality of the video you want to download from xmlbar video downloader. You can do this by selecting from the drop-down menu below the URL. You can choose from various formats, such as MP4, FLV, 3GP, WEBM, etc. You can also choose from various resolutions, such as 144p, 240p, 360p, 480p, 720p, 1080p, 2K, 4K, etc. You can also customize the output settings by clicking on the "Settings" button. Once you have chosen the output format and quality, click on the "Download" button to start downloading the video.

-

You can view the download progress, pause or resume downloads, delete downloads, and open downloaded files by using the buttons on the right side of each item in xmlbar video downloader. You can also preview downloaded videos within xmlbar video downloader by clicking on the "Play" button.

-

Conclusion

-

HD Online Player (xmlbar video downloader vip crack) is a powerful combination of a video player and a video downloader that can help you watch and download online videos in high definition. It has many features and functions that make it easy and convenient to use. It also has a vip crack that can unlock all the features and functions without any restrictions or ads. You can get vip crack by buying it, participating in promotions or giveaways, or using hacks or cheats. You can download videos with HD Online Player (xmlbar video downloader vip crack) by following four simple steps: install HD Online Player and xmlbar video downloader, open HD Online Player and find the video you want to download, copy the video URL and paste it into xmlbar video downloader, and choose the output format and quality and click download.

-

We hope this article has helped you understand what HD Online Player (xmlbar video downloader vip crack) is and how to use it to download videos. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

-

FAQs

- -

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/A Great Big World When The Morning Comes Download Zip.md b/spaces/1gistliPinn/ChatGPT4/Examples/A Great Big World When The Morning Comes Download Zip.md deleted file mode 100644 index 53dfb8e74954e56168dab23d9eef630f4441a099..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/A Great Big World When The Morning Comes Download Zip.md +++ /dev/null @@ -1,6 +0,0 @@ - -

265. consecrated life is often misunderstood, and much confusion reigns about what it really is. many people do not see how profoundly the example of consecrated life can benefit the world, especially when it comes to living faithfully in the world. no one lives out of the world as they do in the church. no one lives in the church without being perfectly incorporated in the world, and yet this integration is not a merely formal and superficial one. in consecrated life, the world and the church are knit together. in consecrated life, the world is a home, a place to work, a sanctuary of prayer, a home for the reception of god. as a result, consecrated persons are also responsible to the world. the world is a home, and the church is a home, and the whole christian community lives in the church as if it were a home. this is the way in which the church understands, and indeed must understand, its mission: to be a home in the world.

-

30. the presence of the saints in the church, and the saints in heaven, is not an impediment to the growth of christian life, but rather a great help to it. the saints are not a burden, but an example which we can follow. they show us the path of god in the world, and we can follow in their steps if we desire to do so. their example encourages us to overcome our difficulties, to continue in prayer, and to work for the good of all. the saints are a great source of joy, as we can see if we open ourselves to their friendship. but their closeness is always accompanied by intercession. we can ask them to pray for us in order that they may assist us in our struggles.

-

a great big world when the morning comes download zip


DOWNLOADhttps://imgfil.com/2uy0kh



899543212b
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/ConvertXtoDVD V5.3.0.9 Installer -nelly- Serial Key.md b/spaces/1gistliPinn/ChatGPT4/Examples/ConvertXtoDVD V5.3.0.9 Installer -nelly- Serial Key.md deleted file mode 100644 index af6b85ff30108ea9492aa7aefb02ead2d2bca6cd..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/ConvertXtoDVD V5.3.0.9 Installer -nelly- Serial Key.md +++ /dev/null @@ -1,7 +0,0 @@ -
-

Lastly, you have the ability to convert directly to DVD or specify the best type of format for DVD. You can also select which audio track to add to the DVDs. In addition, the software can also combine media files. It has an automatic video stabilization option and a silent movie mode. Using this option will enable you to record in silence even if the sound is playing. Additionally, this program allows you to record while the previous clip is playing. VSO ConvertXtoDVD Download Free 1.1.9.2 is a flexible batch converter which runs on almost all popular media players. Additionally, it can be used as a standalone software. It has a powerful file format converter that converts among all media formats. Windows Media Player (WMV), Windows Media Format (WAV), Apple QuickTime (MOV), RealMedia (AAC/MP3), FLV and more video formats will be supported. Additionally, a powerful video editor is provided.

-

ConvertXtoDVD V5.3.0.9 Installer -nelly- Serial Key


Download File ⚹⚹⚹ https://imgfil.com/2uxYBZ



-

VSO ConvertXtoDVD Serial Key is a very useful software that can perform a batch conversion of many files at once and save time. Additionally, it allows you to convert media files or burn them to create DVD. Additionally, you can select between video or audio conversion. The software comes with many options and settings that will help you decide on the type of hard drive space required for the software and the system requirements.

-

VSO ConvertXtoDVD Serial Key is a very useful software that can perform a batch conversion of many files at once and save time. Additionally, it allows you to convert media files or burn them to create DVD. Additionally, you can select between video or audio conversion.

899543212b
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Download Auto Macro Recorder With Crack.md b/spaces/1gistliPinn/ChatGPT4/Examples/Download Auto Macro Recorder With Crack.md deleted file mode 100644 index 616e886ccc68eadfa567bc1588cbb37781d76409..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Download Auto Macro Recorder With Crack.md +++ /dev/null @@ -1,8 +0,0 @@ - -

Take your recording games to another level with Auto Macro Recorder. It will auto record mouse and keyboard actions automatically. You can record on-screen, pause the recording, stop the recording, replay the recording, and many more! You can record mouse clicks and keystrokes to easily automate some task.

-

Mouse Recorder Premium is a professional macro recorder to automate repetitive tasks and can be used for software test automation or as a mouse auto clicker. It records your mouse clicks and keystrokes for infinite playback. Edgy mouse movements can be streamlined and timing can be optimized, e.g. for smooth screencast video tutorials. Macro recordings are recorded like a tape recorder or created step-by-step with the powerful macro editor.

-

Download Auto Macro Recorder With Crack


Download ✪✪✪ https://imgfil.com/2uxY3J



-

While it is possible to use software to make macro, not all keyboard and mouse are compatible with these software, and since these software are not developed by the hardware companies themselves, they will not be covered by hardware companies' support team, this is where programmable keyboard and mouse come in. With built-in programmablility, the software of these keyboard and mouse will be supported by the manufacturers, and some of these keyboard and mouse even come with added features in hardware levels (for example, macro keys).

-

From the name itself, we can easily say that this program is made to do repetitive actions just like what a mouse and keyboard recorder does. With Do It Again app, you can record any macros from your keyboard and mouse, and then play it again whenever you want to. The process is direct, all you need is to create new tasks and all your mouse and keyboard actions will be captured simultaneously. Just hit the Scroll Lock to stop the recording process.

899543212b
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Download Pes 2010 Torent Tpb 23.md b/spaces/1gistliPinn/ChatGPT4/Examples/Download Pes 2010 Torent Tpb 23.md deleted file mode 100644 index 1d2135d3f6684787a7c923db6b0cc3517112005f..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Download Pes 2010 Torent Tpb 23.md +++ /dev/null @@ -1,6 +0,0 @@ -

download pes 2010 torent tpb 23


Download File ->>> https://imgfil.com/2uy1QN



- -Fifa 2012, Download liga 1 fifa 2012 torent tpb, fifa 2010 320240 landscape game free. Game fifa ... Choi fifa 07 online crack Mar 23, 2015. 1fdad05405
-
-
-

diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/app.py b/spaces/1pelhydcardo/ChatGPT-prompt-generator/app.py deleted file mode 100644 index 5da2e5088053267553b6f5af9760a0a7d58c2a1f..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/app.py +++ /dev/null @@ -1,18 +0,0 @@ -from transformers import AutoTokenizer, AutoModelForSeq2SeqLM -import gradio as gr - -tokenizer = AutoTokenizer.from_pretrained("merve/chatgpt-prompts-bart-long") -model = AutoModelForSeq2SeqLM.from_pretrained("merve/chatgpt-prompts-bart-long", from_tf=True) - -def generate(prompt): - - batch = tokenizer(prompt, return_tensors="pt") - generated_ids = model.generate(batch["input_ids"], max_new_tokens=150) - output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) - return output[0] - -input_component = gr.Textbox(label = "Input a persona, e.g. photographer", value = "photographer") -output_component = gr.Textbox(label = "Prompt") -examples = [["photographer"], ["developer"]] -description = "This app generates ChatGPT prompts, it's based on a BART model trained on [this dataset](https://huggingface.co/datasets/fka/awesome-chatgpt-prompts). 📓 Simply enter a persona that you want the prompt to be generated based on. 🧙🏻🧑🏻‍🚀🧑🏻‍🎨🧑🏻‍🔬🧑🏻‍💻🧑🏼‍🏫🧑🏽‍🌾" -gr.Interface(generate, inputs = input_component, outputs=output_component, examples=examples, title = "👨🏻‍🎤 ChatGPT Prompt Generator 👨🏻‍🎤", description=description).launch() diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Gas Station Simulator Mod Apk and Experience the Real Life of a Gas Station Owner.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Gas Station Simulator Mod Apk and Experience the Real Life of a Gas Station Owner.md deleted file mode 100644 index 5bb8afd7de98abfd23f74f1074e9eee572674077..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Gas Station Simulator Mod Apk and Experience the Real Life of a Gas Station Owner.md +++ /dev/null @@ -1,125 +0,0 @@ - -

Download Gas Station Simulator Mod Apk 2022

-

Do you dream of owning and running your own gas station business? Do you want to experience the thrill and challenge of managing a busy service station? If yes, then you should try Gas Station Simulator, a fun and realistic simulation game that lets you become a gas station tycoon. And if you want to enjoy more features and benefits, you should download Gas Station Simulator Mod Apk 2022, a modified version of the game that gives you unlimited money, unlocked items, and more. In this article, we will tell you everything you need to know about this amazing game and how to download it on your Android device.

-

download gas station simulator mod apk 2022


Download Zip ••• https://urlin.us/2uSWgx



-

What is Gas Station Simulator?

-

Gas Station Simulator is a simulation game developed by METODEGAMES, a popular game studio that specializes in creating realistic and immersive simulation games. In this game, you will start with a small and rundown gas station that you have to renovate and expand into a profitable business. You will have to take care of various aspects of your gas station, such as refueling cars, repairing vehicles, washing windows, selling snacks, hiring staff, upgrading facilities, and more

The game features realistic graphics, sound effects, and physics that make you feel like you are actually running a gas station. You will also encounter different types of customers, such as truck drivers, bikers, families, and more, each with their own preferences and personalities. You will have to satisfy their needs and earn their trust and loyalty. The game also has a day and night cycle, weather effects, and random events that add more variety and challenge to your gameplay.

-

Why download Gas Station Simulator Mod Apk 2022?

-

Gas Station Simulator is a free-to-play game that you can download from the Google Play Store. However, the game also has some in-app purchases and ads that may limit your enjoyment and progress. For example, you will need to spend real money to buy more coins, gems, and items that can help you upgrade your gas station faster. You will also have to watch ads to get some rewards or bonuses. If you want to avoid these hassles and have more fun and freedom in playing the game, you should download Gas Station Simulator Mod Apk 2022, a modified version of the game that gives you many advantages over the original version.

-

Benefits of Gas Station Simulator Mod Apk 2022

-

Some of the benefits of downloading Gas Station Simulator Mod Apk 2022 are:

- -

Drawbacks of Gas Station Simulator Mod Apk 2022

-

Some of the drawbacks of downloading Gas Station Simulator Mod Apk 2022 are:

-

How to download Gas Station Simulator Mod Apk 2022?

-

If you are convinced that downloading Gas Station Simulator Mod Apk 2022 is worth it, you may be wondering how to do it. Well, don't worry, because we have prepared a simple and easy tutorial for you. Just follow these steps and you will be able to enjoy the modded version of the game in no time.

-

download gas station simulator mod apk 2022 unlimited money
-download gas station simulator mod apk 2022 latest version
-download gas station simulator mod apk 2022 for android
-download gas station simulator mod apk 2022 free
-download gas station simulator mod apk 2022 hack
-download gas station simulator mod apk 2022 offline
-download gas station simulator mod apk 2022 no ads
-download gas station simulator mod apk 2022 full unlocked
-download gas station simulator mod apk 2022 premium
-download gas station simulator mod apk 2022 pro
-download gas station simulator mod apk 2022 mega mod
-download gas station simulator mod apk 2022 update
-download gas station simulator mod apk 2022 new features
-download gas station simulator mod apk 2022 cheats
-download gas station simulator mod apk 2022 gameplay
-download gas station simulator mod apk 2022 review
-download gas station simulator mod apk 2022 tips and tricks
-download gas station simulator mod apk 2022 best settings
-download gas station simulator mod apk 2022 guide
-download gas station simulator mod apk 2022 tutorial
-download gas station simulator mod apk 2022 how to play
-download gas station simulator mod apk 2022 how to install
-download gas station simulator mod apk 2022 how to download
-download gas station simulator mod apk 2022 how to get unlimited money
-download gas station simulator mod apk 2022 how to unlock everything
-download gas station simulator mod apk 2022 how to hack
-download gas station simulator mod apk 2022 how to run offline
-download gas station simulator mod apk 2022 how to remove ads
-download gas station simulator mod apk 2022 how to upgrade
-download gas station simulator mod apk 2022 how to customize
-download gas station simulator mod apk 2022 how to manage your business
-download gas station simulator mod apk 2022 how to attract customers
-download gas station simulator mod apk 2022 how to earn more money
-download gas station simulator mod apk 2022 how to expand your business
-download gas station simulator mod apk 2022 how to compete with other players
-download gas station simulator mod apk 2022 how to enjoy the game
-download gas station simulator mod apk 2022 benefits and drawbacks
-download gas station simulator mod apk 2022 pros and cons
-download gas station simulator mod apk 2022 advantages and disadvantages
-download gas station simulator mod apk 2022 comparison and contrast
-download gas station simulator mod apk 2022 alternatives and substitutes
-download gas station simulator mod apk 2022 similar and related games
-download gas station simulator mod apk 2022 recommendations and suggestions
-download gas station simulator mod apk 2022 feedback and ratings
-download gas station simulator mod apk 2022 comments and reviews
-download gas station simulator mod apk 2022 questions and answers
-download gas station simulator mod apk 2022 problems and solutions
-download gas station simulator mod apk 2022 issues and fixes

-

Requirements for downloading Gas Station Simulator Mod Apk 2022

-

Before you start downloading the modded version of the game, you need to make sure that you have the following requirements:

- -

Steps for downloading Gas Station Simulator Mod Apk 2022

-

Once you have the requirements ready, you can proceed with the following steps:

-
    -
  1. Click on this link Gas Station Simulator Mod Apk 2022 to download the modded version of the game. The file size is about 90 MB and it is in zip format.
  2. -
  3. Wait for the download to finish and then locate the zip file on your device using your file manager app.
  4. -
  5. Extract the zip file and you will see two files: one is the apk file and the other is the obb file.
  6. -
  7. Tap on the apk file and install it on your device. Do not open it yet.
  8. -
  9. Copy the obb file and paste it into this folder: Android/obb/com.metodegames.gasstationsimulator. If you don't have this folder, create it manually.
  10. -
  11. Now you can open the game and enjoy playing Gas Station Simulator Mod Apk 2022 with unlimited money, gems, and items.
  12. -
-

Tips and tricks for playing Gas Station Simulator Mod Apk 2022

-

Now that you have downloaded and installed Gas Station Simulator Mod Apk 2022, you may want to know some tips and tricks that can help you play the game better. Here are some of them:

-

How to upgrade your gas station?

-

One of the main goals of the game is to upgrade your gas station and make it more attractive and efficient. You can do this by using your money and gems to buy new items and facilities, such as pumps, tanks, car washes, shops, restrooms, parking lots, and more. You can also customize your gas station with different colors, decorations, signs, and logos. Upgrading your gas station will increase your income and reputation, as well as unlock new features and challenges.

-

How to attract more customers?

-

Another important aspect of the game is to attract more customers and keep them happy. You can do this by providing them with fast and quality service, such as refueling their cars, repairing their vehicles, washing their windows, selling them snacks, and more. You can also offer them discounts, coupons, loyalty cards, and freebies to make them come back again. You can also advertise your gas station on social media, radio, TV, or billboards to reach more potential customers. Attracting more customers will increase your revenue and rating, as well as unlock new types of customers and vehicles.

-

How to manage your finances?

-

The last but not least aspect of the game is to manage your finances and balance your income and expenses. You can do this by keeping track of your daily earnings and spending, as well as your taxes and loans. You can also invest your money in stocks, bonds, or cryptocurrencies to earn more profits or dividends. You can also save your money in a bank account or a safe to protect it from theft or loss. Managing your finances will help you grow your business and avoid bankruptcy or debt.

-

Conclusion

-

In conclusion, Gas Station Simulator is a fun and realistic simulation game that lets you become a gas station tycoon. You can download Gas Station Simulator Mod Apk 2022 to enjoy more features and benefits than the original version of the game. However, you should also be aware of the drawbacks and risks of downloading the modded version. You should also follow our tips and tricks to play the game better and achieve your goals faster. We hope that this article has been helpful and informative for you. If you have any questions or feedback, please feel free to contact us through the comment section below. Thank you for reading and happy gaming!

-

FAQs

-

Here are some frequently asked questions and answers about Gas Station Simulator Mod Apk 2022:

-

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Enjoy Love Convention Mod APK with Unlimited Money and Gems.md b/spaces/1phancelerku/anime-remove-background/Enjoy Love Convention Mod APK with Unlimited Money and Gems.md deleted file mode 100644 index e9f65acdd531c506b817f83268777aadfad852ba..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Enjoy Love Convention Mod APK with Unlimited Money and Gems.md +++ /dev/null @@ -1,98 +0,0 @@ -
-

Love Convention Mod APK: A Free Adventure Game for Android Lovers

-

If you are looking for a fun and exciting adventure game for your Android device, you might want to check out Love Convention Mod APK. This is a free software that makes part of the category 'Adventure' and lets you experience a romantic and thrilling story with different characters and choices. In this article, we will tell you everything you need to know about Love Convention, how to download and install the mod apk version, why you should play it, and some useful tips and tricks to enjoy it more.

-

What is Love Convention?

-

A brief introduction to the game and its features

-

Love Convention is a game developed by RAITgames, a studio that specializes in creating interactive stories with high-quality graphics and sound effects. The game was published on Softonic on October 4th, 2022 and has received positive reviews from users. The game is set in a fictional convention where you can meet different characters, such as celebrities, cosplayers, fans, and more. You can choose your own avatar, name, gender, and preferences, and interact with the characters in various ways. You can also customize your outfits, accessories, and hairstyles to suit your style. The game has multiple endings depending on your choices and actions, so you can replay it as many times as you want.

-

love convention mod apk


Downloadhttps://jinyurl.com/2uNKnT



-

How to download and install the mod apk version

-

The mod apk version of Love Convention is a modified version that gives you access to some extra features that are not available in the original one. For example, you can get unlimited money, gems, tickets, and energy, which you can use to buy items, unlock scenes, and progress faster in the game. You can also remove ads and enjoy a smoother gameplay. To download and install the mod apk version of Love Convention, you need to follow these steps:

-
    -
  1. Go to this link and download the apk file of Love Convention Mod APK.
  2. -
  3. Go to your device settings and enable the installation of apps from unknown sources.
  4. -
  5. Locate the downloaded apk file in your file manager and tap on it to install it.
  6. -
  7. Launch the game and enjoy!
  8. -
-

Why should you play Love Convention Mod APK?

-

The benefits of playing the mod apk version over the original one

-

As we mentioned before, playing the mod apk version of Love Convention gives you some advantages over playing the original one. Here are some of them:

- -

The challenges and rewards of the game

-

Playing Love Convention is not only fun but also challenging. You will face different situations and dilemmas that will test your skills, judgment, and emotions. You will have to make decisions that will affect your relationships with the characters and the outcome of the story. You will also have to deal with some conflicts, secrets, mysteries, and surprises that will keep you on your toes. However, playing Love Convention is also rewarding. You will get to experience a captivating and immersive story that will make you feel like you are part of it. You will also get to meet and romance different characters that have their own personalities, backgrounds, and goals. You will also get to enjoy stunning graphics, animations, and sound effects that will enhance your gaming experience. Playing Love Convention is a great way to escape from reality and have some fun.

-

The best tips and tricks to enjoy the game

-

If you want to make the most out of playing Love Convention, here are some tips and tricks that you can use:

- -

Conclusion

-

Love Convention Mod APK is a free adventure game for Android lovers that lets you experience a romantic and thrilling story with different characters and choices. You can download and install the mod apk version of Love Convention to get access to some extra features that are not available in the original one, such as unlimited money, gems, tickets, and energy, as well as removing ads and enjoying a smoother gameplay. You can also enjoy the benefits, challenges, and rewards of playing Love Convention, as well as some useful tips and tricks to enjoy it more. If you are looking for a fun and exciting adventure game for your Android device, you should definitely give Love Convention Mod APK a try!

-

FAQs

-

What are the requirements to play Love Convention Mod APK?

-

To play Love Convention Mod APK, you need to have an Android device that runs on Android 4.4 or higher, as well as a stable internet connection. You also need to have enough storage space on your device to download and install the apk file of Love Convention Mod APK.

-

Is Love Convention Mod APK safe and legal?

-

Yes, Love Convention Mod APK is safe and legal to use. The apk file of Love Convention Mod APK is scanned for viruses and malware before being uploaded on our website. However, we recommend that you download and install the apk file from our website only, as we cannot guarantee the safety and legality of other sources.

-

How can I update Love Convention Mod APK?

-

To update Love Convention Mod APK, you need to visit our website regularly and check for any new versions of the apk file. If there is a new version available, you can download and install it following the same steps as before. However, you might need to uninstall the previous version of Love Convention Mod APK before installing the new one.

-

love convention mod apk download
-love convention mod apk free
-love convention mod apk latest version
-love convention mod apk unlimited money
-love convention mod apk android
-love convention mod apk obb
-love convention mod apk offline
-love convention mod apk 2023
-love convention mod apk softonic
-love convention mod apk apkcombo
-love convention mod apk adventure game
-love convention mod apk raitgames
-love convention mod apk english
-love convention mod apk german
-love convention mod apk russian
-love convention mod apk portuguese
-love convention mod apk romance
-love convention mod apk simulation
-love convention mod apk choices
-love convention mod apk stories
-love convention mod apk characters
-love convention mod apk graphics
-love convention mod apk gameplay
-love convention mod apk review
-love convention mod apk rating
-love convention mod apk update
-love convention mod apk bug fix
-love convention mod apk features
-love convention mod apk cheats
-love convention mod apk hack
-love convention mod apk tips
-love convention mod apk guide
-love convention mod apk walkthrough
-love convention mod apk trailer
-love convention mod apk video
-love convention mod apk screenshot
-love convention mod apk install
-love convention mod apk safe
-love convention mod apk virus free
-love convention mod apk legal
-love convention mod apk compatible devices
-love convention mod apk system requirements
-love convention mod apk size
-love convention mod apk file type
-love convention mod apk online support
-love convention mod apk feedback
-love convention mod apk forum
-love convention mod apk community

-

Can I play Love Convention Mod APK offline?

-

No, you cannot play Love Convention Mod APK offline. You need to have a stable internet connection to play Love Convention Mod APK, as the game requires online verification and data synchronization.

-

How can I contact the developers of Love Convention?

-

If you have any questions, feedback, or suggestions regarding Love Convention or Love Convention Mod APK, you can contact the developers of Love Convention by sending them an email at raitgames@gmail.com or by visiting their official website at https://www.raitgames.com/.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/9752isme/ChatGPT4/README.md b/spaces/9752isme/ChatGPT4/README.md deleted file mode 100644 index 7938de14e5355209aaae713f289ca469181bbb17..0000000000000000000000000000000000000000 --- a/spaces/9752isme/ChatGPT4/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Chat-with-GPT4 -emoji: 🚀 -colorFrom: red -colorTo: indigo -sdk: gradio -sdk_version: 3.21.0 -app_file: app.py -pinned: false -license: mit -duplicated_from: ysharma/ChatGPT4 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/ADOPLE/Adopleai-DocumentQA/README.md b/spaces/ADOPLE/Adopleai-DocumentQA/README.md deleted file mode 100644 index f710a7105127d27d8180235f66453473f4393102..0000000000000000000000000000000000000000 --- a/spaces/ADOPLE/Adopleai-DocumentQA/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: DocumentQA -emoji: 🏃 -colorFrom: red -colorTo: red -sdk: gradio -sdk_version: 3.35.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/ADobrovsky/Plant_Disease_Classification_Project/app.py b/spaces/ADobrovsky/Plant_Disease_Classification_Project/app.py deleted file mode 100644 index af1826c0658b7e8f2021abc7c281f81df0aac8cb..0000000000000000000000000000000000000000 --- a/spaces/ADobrovsky/Plant_Disease_Classification_Project/app.py +++ /dev/null @@ -1,48 +0,0 @@ -import gradio as gr -import torch -import torch.nn -from torch import Tensor -import torch.nn.functional -import torchvision -from torchvision import transforms - -MODEL_NAME = 'ResNeXt-101-64x4d' -DEVICE = "cuda" if torch.cuda.is_available() else "cpu" -MEAN = [0.485, 0.456, 0.406] -STD = [0.229, 0.224, 0.225] - -from torchvision.models import resnext101_64x4d -model = resnext101_64x4d() -model.fc = torch.nn.Linear(model.fc.in_features, 88) - -if (torch.cuda.is_available()): - model.load_state_dict(torch.load(MODEL_NAME+'-model-1.pt')) -else: - model.load_state_dict(torch.load(MODEL_NAME+'-model-1.pt', map_location=torch.device('cpu'))) - -model = model.to(DEVICE) - -labels = ['Apple__black_rot', 'Apple__healthy', 'Apple__rust', 'Apple__scab', 'Cassava__bacterial_blight', 'Cassava__brown_streak_disease', 'Cassava__green_mottle', 'Cassava__healthy', 'Cassava__mosaic_disease', 'Cherry__healthy', 'Cherry__powdery_mildew', 'Chili__healthy', 'Chili__leaf curl', 'Chili__leaf spot', 'Chili__whitefly', 'Chili__yellowish', 'Coffee__cercospora_leaf_spot', 'Coffee__healthy', 'Coffee__red_spider_mite', 'Coffee__rust', 'Corn__common_rust', 'Corn__gray_leaf_spot', 'Corn__healthy', 'Corn__northern_leaf_blight', 'Cucumber__diseased', 'Cucumber__healthy', 'Gauva__diseased', 'Gauva__healthy', 'Grape__black_measles', 'Grape__black_rot', 'Grape__healthy', 'Grape__leaf_blight_(isariopsis_leaf_spot)', 'Jamun__diseased', 'Jamun__healthy', 'Lemon__diseased', 'Lemon__healthy', 'Mango__diseased', 'Mango__healthy', 'Peach__bacterial_spot', 'Peach__healthy', 'Pepper_bell__bacterial_spot', 'Pepper_bell__healthy', 'Pomegranate__diseased', 'Pomegranate__healthy', 'Potato__early_blight', 'Potato__healthy', 'Potato__late_blight', 'Rice__brown_spot', 'Rice__healthy', 'Rice__hispa', 'Rice__leaf_blast', 'Rice__neck_blast', 'Soybean__bacterial_blight', 'Soybean__caterpillar', 'Soybean__diabrotica_speciosa', 'Soybean__downy_mildew', 'Soybean__healthy', 'Soybean__mosaic_virus', 'Soybean__powdery_mildew', 'Soybean__rust', 'Soybean__southern_blight', 'Strawberry___leaf_scorch', 'Strawberry__healthy', 'Sugarcane__bacterial_blight', 'Sugarcane__healthy', 'Sugarcane__red_rot', 'Sugarcane__red_stripe', 'Sugarcane__rust', 'Tea__algal_leaf', 'Tea__anthracnose', 'Tea__bird_eye_spot', 'Tea__brown_blight', 'Tea__healthy', 'Tea__red_leaf_spot', 'Tomato__bacterial_spot', 'Tomato__early_blight', 'Tomato__healthy', 'Tomato__late_blight', 'Tomato__leaf_mold', 'Tomato__mosaic_virus', 'Tomato__septoria_leaf_spot', 'Tomato__spider_mites_(two_spotted_spider_mite)', 'Tomato__target_spot', 'Tomato__yellow_leaf_curl_virus', 'Wheat__brown_rust', 'Wheat__healthy', 'Wheat__septoria', 'Wheat__yellow_rust'] - -predictTransform = transforms.Compose([ - transforms.ToTensor(), - transforms.Normalize(mean=MEAN, std=STD) -]) - -def predict(img): - img = predictTransform(img).unsqueeze(0).to(DEVICE) - with torch.no_grad(): - model.eval() - prediction = torch.nn.functional.softmax(model(img)[0], dim=0) - confidences = {labels[i]: float(prediction[i]) for i in range(len(labels))} - return confidences - -title = "Plant Disease Classifier" -description = "Please upload a photo containing a plant leaf." -iface = gr.Interface(predict, - inputs=gr.Image(shape=(224, 224)), - outputs=gr.Label(num_top_classes=7), - live=True, - title=title, - description=description, - interpretation='default').launch() \ No newline at end of file diff --git a/spaces/AIConsultant/MusicGen/audiocraft/grids/diffusion/4_bands_base_32khz.py b/spaces/AIConsultant/MusicGen/audiocraft/grids/diffusion/4_bands_base_32khz.py deleted file mode 100644 index f7e67bcc89dd0c8e50d770e600b55f179fe19588..0000000000000000000000000000000000000000 --- a/spaces/AIConsultant/MusicGen/audiocraft/grids/diffusion/4_bands_base_32khz.py +++ /dev/null @@ -1,27 +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. - -""" -Training of the 4 diffusion models described in -"From Discrete Tokens to High-Fidelity Audio Using Multi-Band Diffusion" -(paper link). -""" - -from ._explorers import DiffusionExplorer - - -@DiffusionExplorer -def explorer(launcher): - launcher.slurm_(gpus=4, partition='learnfair') - - launcher.bind_({'solver': 'diffusion/default', - 'dset': 'internal/music_10k_32khz'}) - - with launcher.job_array(): - launcher({'filter.use': True, 'filter.idx_band': 0, "processor.use": False, 'processor.power_std': 0.4}) - launcher({'filter.use': True, 'filter.idx_band': 1, "processor.use": False, 'processor.power_std': 0.4}) - launcher({'filter.use': True, 'filter.idx_band': 2, "processor.use": True, 'processor.power_std': 0.4}) - launcher({'filter.use': True, 'filter.idx_band': 3, "processor.use": True, 'processor.power_std': 0.75}) diff --git a/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/sampler.py b/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/sampler.py deleted file mode 100644 index e4784d068f808a40a56c8e748d83175f7f4e6233..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/sampler.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Samplers, conforming to the glTF 2.0 standards as specified in -https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-sampler - -Author: Matthew Matl -""" -from .constants import GLTF - - -class Sampler(object): - """Texture sampler properties for filtering and wrapping modes. - - Parameters - ---------- - name : str, optional - The user-defined name of this object. - magFilter : int, optional - Magnification filter. Valid values: - - :attr:`.GLTF.NEAREST` - - :attr:`.GLTF.LINEAR` - minFilter : int, optional - Minification filter. Valid values: - - :attr:`.GLTF.NEAREST` - - :attr:`.GLTF.LINEAR` - - :attr:`.GLTF.NEAREST_MIPMAP_NEAREST` - - :attr:`.GLTF.LINEAR_MIPMAP_NEAREST` - - :attr:`.GLTF.NEAREST_MIPMAP_LINEAR` - - :attr:`.GLTF.LINEAR_MIPMAP_LINEAR` - wrapS : int, optional - S (U) wrapping mode. Valid values: - - :attr:`.GLTF.CLAMP_TO_EDGE` - - :attr:`.GLTF.MIRRORED_REPEAT` - - :attr:`.GLTF.REPEAT` - wrapT : int, optional - T (V) wrapping mode. Valid values: - - :attr:`.GLTF.CLAMP_TO_EDGE` - - :attr:`.GLTF.MIRRORED_REPEAT` - - :attr:`.GLTF.REPEAT` - """ - - def __init__(self, - name=None, - magFilter=None, - minFilter=None, - wrapS=GLTF.REPEAT, - wrapT=GLTF.REPEAT): - self.name = name - self.magFilter = magFilter - self.minFilter = minFilter - self.wrapS = wrapS - self.wrapT = wrapT - - @property - def name(self): - """str : The user-defined name of this object. - """ - return self._name - - @name.setter - def name(self, value): - if value is not None: - value = str(value) - self._name = value - - @property - def magFilter(self): - """int : Magnification filter type. - """ - return self._magFilter - - @magFilter.setter - def magFilter(self, value): - self._magFilter = value - - @property - def minFilter(self): - """int : Minification filter type. - """ - return self._minFilter - - @minFilter.setter - def minFilter(self, value): - self._minFilter = value - - @property - def wrapS(self): - """int : S (U) wrapping mode. - """ - return self._wrapS - - @wrapS.setter - def wrapS(self, value): - self._wrapS = value - - @property - def wrapT(self): - """int : T (V) wrapping mode. - """ - return self._wrapT - - @wrapT.setter - def wrapT(self, value): - self._wrapT = value diff --git a/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/encoders/CLAP/CLAPWrapper.py b/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/encoders/CLAP/CLAPWrapper.py deleted file mode 100644 index b26af847dcfdd314d10aa2c795362deac1e1fac7..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/encoders/CLAP/CLAPWrapper.py +++ /dev/null @@ -1,257 +0,0 @@ -import random -import torchaudio -from torch._six import string_classes -import collections -import re -import torch.nn.functional as F -import numpy as np -from transformers import AutoTokenizer -from ldm.modules.encoders.CLAP.utils import read_config_as_args -from ldm.modules.encoders.CLAP.clap import CLAP -import math -import torchaudio.transforms as T -import os -import torch -from importlib_resources import files - - -class CLAPWrapper(): - """ - A class for interfacing CLAP model. - """ - - def __init__(self, model_fp, device): - self.np_str_obj_array_pattern = re.compile(r'[SaUO]') - self.file_path = os.path.realpath(__file__) - self.default_collate_err_msg_format = ( - "default_collate: batch must contain tensors, numpy arrays, numbers, " - "dicts or lists; found {}") - self.config_as_str = files('ldm').joinpath('modules/encoders/CLAP/config.yml').read_text() - self.model_fp = model_fp - self.device = device - self.clap, self.tokenizer, self.args = self.load_clap() - - def load_clap(self): - r"""Load CLAP model with args from config file""" - - args = read_config_as_args(self.config_as_str, is_config_str=True) - - if 'bert' in args.text_model: - self.token_keys = ['input_ids', 'token_type_ids', 'attention_mask'] - else: - self.token_keys = ['input_ids', 'attention_mask'] - - clap = CLAP( - audioenc_name=args.audioenc_name, - sample_rate=args.sampling_rate, - window_size=args.window_size, - hop_size=args.hop_size, - mel_bins=args.mel_bins, - fmin=args.fmin, - fmax=args.fmax, - classes_num=args.num_classes, - out_emb=args.out_emb, - text_model=args.text_model, - transformer_embed_dim=args.transformer_embed_dim, - d_proj=args.d_proj - ) - - # Load pretrained weights for model - model_state_dict = torch.load(self.model_fp, map_location=torch.device('cpu'))['model'] - clap.load_state_dict(model_state_dict) - - clap.eval() # set clap in eval mode - tokenizer = AutoTokenizer.from_pretrained(args.text_model) - - clap = clap.to(self.device) - tokenizer = tokenizer.to(self.device) - - return clap, tokenizer, args - - def default_collate(self, batch): - r"""Puts each data field into a tensor with outer dimension batch size""" - elem = batch[0] - elem_type = type(elem) - if isinstance(elem, torch.Tensor): - out = None - if torch.utils.data.get_worker_info() is not None: - # If we're in a background process, concatenate directly into a - # shared memory tensor to avoid an extra copy - numel = sum([x.numel() for x in batch]) - storage = elem.storage()._new_shared(numel) - out = elem.new(storage) - return torch.stack(batch, 0, out=out) - elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \ - and elem_type.__name__ != 'string_': - if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap': - # array of string classes and object - if self.np_str_obj_array_pattern.search(elem.dtype.str) is not None: - raise TypeError( - self.default_collate_err_msg_format.format(elem.dtype)) - - return self.default_collate([torch.as_tensor(b) for b in batch]) - elif elem.shape == (): # scalars - return torch.as_tensor(batch) - elif isinstance(elem, float): - return torch.tensor(batch, dtype=torch.float64) - elif isinstance(elem, int): - return torch.tensor(batch) - elif isinstance(elem, string_classes): - return batch - elif isinstance(elem, collections.abc.Mapping): - return {key: self.default_collate([d[key] for d in batch]) for key in elem} - elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple - return elem_type(*(self.default_collate(samples) for samples in zip(*batch))) - elif isinstance(elem, collections.abc.Sequence): - # check to make sure that the elements in batch have consistent size - it = iter(batch) - elem_size = len(next(it)) - if not all(len(elem) == elem_size for elem in it): - raise RuntimeError( - 'each element in list of batch should be of equal size') - transposed = zip(*batch) - return [self.default_collate(samples) for samples in transposed] - - raise TypeError(self.default_collate_err_msg_format.format(elem_type)) - - def load_audio_into_tensor(self, audio_path, audio_duration, resample=False): - r"""Loads audio file and returns raw audio.""" - # Randomly sample a segment of audio_duration from the clip or pad to match duration - audio_time_series, sample_rate = torchaudio.load(audio_path) - resample_rate = self.args.sampling_rate - if resample: - resampler = T.Resample(sample_rate, resample_rate) - audio_time_series = resampler(audio_time_series) - audio_time_series = audio_time_series.reshape(-1) - - # audio_time_series is shorter than predefined audio duration, - # so audio_time_series is extended - if audio_duration*sample_rate >= audio_time_series.shape[0]: - repeat_factor = int(np.ceil((audio_duration*sample_rate) / - audio_time_series.shape[0])) - # Repeat audio_time_series by repeat_factor to match audio_duration - audio_time_series = audio_time_series.repeat(repeat_factor) - # remove excess part of audio_time_series - audio_time_series = audio_time_series[0:audio_duration*sample_rate] - else: - # audio_time_series is longer than predefined audio duration, - # so audio_time_series is trimmed - start_index = random.randrange( - audio_time_series.shape[0] - audio_duration*sample_rate) - audio_time_series = audio_time_series[start_index:start_index + - audio_duration*sample_rate] - return torch.FloatTensor(audio_time_series) - - def preprocess_audio(self, audio_files, resample): - r"""Load list of audio files and return raw audio""" - audio_tensors = [] - for audio_file in audio_files: - audio_tensor = self.load_audio_into_tensor( - audio_file, self.args.duration, resample) - audio_tensor = audio_tensor.reshape(1, -1).to(self.device) - audio_tensors.append(audio_tensor) - return self.default_collate(audio_tensors) - - def preprocess_text(self, text_queries, text_len=100): - r"""Load list of class labels and return tokenized text""" - device = next(self.clap.parameters()).device - tokenized_texts = [] - for ttext in text_queries: - tok = self.tokenizer.encode_plus( - text=ttext, add_special_tokens=True, max_length=text_len, pad_to_max_length=True, return_tensors="pt") - for key in self.token_keys: - tok[key] = tok[key].reshape(-1).to(device) - tokenized_texts.append(tok) - return self.default_collate(tokenized_texts) - - def get_text_embeddings(self, class_labels): - r"""Load list of class labels and return text embeddings""" - preprocessed_text = self.preprocess_text(class_labels) - text_embeddings = self._get_text_embeddings(preprocessed_text) - text_embeddings = text_embeddings/torch.norm(text_embeddings, dim=-1, keepdim=True) - return text_embeddings - - def get_audio_embeddings(self, audio_files, resample): - r"""Load list of audio files and return a audio embeddings""" - preprocessed_audio = self.preprocess_audio(audio_files, resample) - audio_embeddings = self._get_audio_embeddings(preprocessed_audio) - audio_embeddings = audio_embeddings/torch.norm(audio_embeddings, dim=-1, keepdim=True) - return audio_embeddings - - def _get_text_embeddings(self, preprocessed_text): - r"""Load preprocessed text and return text embeddings""" - with torch.no_grad(): - text_embeddings = self.clap.caption_encoder(preprocessed_text) - text_embeddings = text_embeddings/torch.norm(text_embeddings, dim=-1, keepdim=True) - return text_embeddings - - def _get_audio_embeddings(self, preprocessed_audio): - r"""Load preprocessed audio and return a audio embeddings""" - with torch.no_grad(): - preprocessed_audio = preprocessed_audio.reshape( - preprocessed_audio.shape[0], preprocessed_audio.shape[2]) - #Append [0] the audio emebdding, [1] has output class probabilities - audio_embeddings = self.clap.audio_encoder(preprocessed_audio)[0] - audio_embeddings = audio_embeddings/torch.norm(audio_embeddings, dim=-1, keepdim=True) - return audio_embeddings - - def compute_similarity(self, audio_embeddings, text_embeddings): - r"""Compute similarity between text and audio embeddings""" - logit_scale = self.clap.logit_scale.exp() - similarity = logit_scale*text_embeddings @ audio_embeddings.T - return similarity.T - - def _generic_batch_inference(self, func, *args): - r"""Process audio and/or text per batch""" - input_tmp = args[0] - batch_size = args[-1] - # args[0] has audio_files, args[1] has class_labels - inputs = [args[0], args[1]] if len(args) == 3 else [args[0]] - args0_len = len(args[0]) - # compute text_embeddings once for all the audio_files batches - if len(inputs) == 2: - text_embeddings = self.get_text_embeddings(args[1]) - inputs = [args[0], args[1], text_embeddings] - dataset_idx = 0 - for _ in range(math.ceil(args0_len/batch_size)): - next_batch_idx = dataset_idx + batch_size - # batch size is bigger than available audio/text items - if next_batch_idx >= args0_len: - inputs[0] = input_tmp[dataset_idx:] - return func(*tuple(inputs)) - else: - inputs[0] = input_tmp[dataset_idx:next_batch_idx] - yield func(*tuple(inputs)) - dataset_idx = next_batch_idx - - def get_audio_embeddings_per_batch(self, audio_files, batch_size): - r"""Load preprocessed audio and return a audio embeddings per batch""" - return self._generic_batch_inference(self.get_audio_embeddings, audio_files, batch_size) - - def get_text_embeddings_per_batch(self, class_labels, batch_size): - r"""Load preprocessed text and return text embeddings per batch""" - return self._generic_batch_inference(self.get_text_embeddings, class_labels, batch_size) - - def classify_audio_files_per_batch(self, audio_files, class_labels, batch_size): - r"""Compute classification probabilities for each audio recording in a batch and each class label""" - return self._generic_batch_inference(self.classify_audio_files, audio_files, class_labels, batch_size) - -if __name__ == '__main__': - - # Load and initialize CLAP - weights_path = "/home1/huangrongjie/Project/Diffusion/LatentDiffusion/CLAP/CLAP_weights_2022.pth" - clap_model = CLAPWrapper(weights_path, use_cuda=False) - - y = ["A woman talks nearby as water pours", "Multiple clanging and clanking sounds"] - x = ['/home2/huangjiawei/data/audiocaps/train/Yr1nicOVtvkQ.wav', '/home2/huangjiawei/data/audiocaps/train/YUDGBjjwyaqE.wav'] - - # Computing text embeddings - text_embeddings = clap_model.get_text_embeddings(y) - - import ipdb - ipdb.set_trace() - - # Computing audio embeddings - audio_embeddings = clap_model.get_audio_embeddings(x, resample=True) - similarity = clap_model.compute_similarity(audio_embeddings, text_embeddings) - diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov7/yolov7_tiny_syncbn_fast_8x16b-300e_coco.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov7/yolov7_tiny_syncbn_fast_8x16b-300e_coco.py deleted file mode 100644 index b9e9f10e2926a840d2af7a9e27b0e2047710343d..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov7/yolov7_tiny_syncbn_fast_8x16b-300e_coco.py +++ /dev/null @@ -1,98 +0,0 @@ -_base_ = './yolov7_l_syncbn_fast_8x16b-300e_coco.py' - -# ========================modified parameters======================== - -# -----model related----- -# Data augmentation -max_translate_ratio = 0.1 # YOLOv5RandomAffine -scaling_ratio_range = (0.5, 1.6) # YOLOv5RandomAffine -mixup_prob = 0.05 # YOLOv5MixUp -randchoice_mosaic_prob = [0.8, 0.2] -mixup_alpha = 8.0 # YOLOv5MixUp -mixup_beta = 8.0 # YOLOv5MixUp - -# -----train val related----- -loss_cls_weight = 0.5 -loss_obj_weight = 1.0 - -lr_factor = 0.01 # Learning rate scaling factor -# ===============================Unmodified in most cases==================== -num_classes = _base_.num_classes -num_det_layers = _base_.num_det_layers -img_scale = _base_.img_scale -pre_transform = _base_.pre_transform -model = dict( - backbone=dict( - arch='Tiny', act_cfg=dict(type='LeakyReLU', negative_slope=0.1)), - neck=dict( - is_tiny_version=True, - in_channels=[128, 256, 512], - out_channels=[64, 128, 256], - block_cfg=dict( - _delete_=True, type='TinyDownSampleBlock', middle_ratio=0.25), - act_cfg=dict(type='LeakyReLU', negative_slope=0.1), - use_repconv_outs=False), - bbox_head=dict( - head_module=dict(in_channels=[128, 256, 512]), - loss_cls=dict(loss_weight=loss_cls_weight * - (num_classes / 80 * 3 / num_det_layers)), - loss_obj=dict(loss_weight=loss_obj_weight * - ((img_scale[0] / 640)**2 * 3 / num_det_layers)))) - -mosiac4_pipeline = [ - dict( - type='Mosaic', - img_scale=img_scale, - pad_val=114.0, - pre_transform=pre_transform), - dict( - type='YOLOv5RandomAffine', - max_rotate_degree=0.0, - max_shear_degree=0.0, - max_translate_ratio=max_translate_ratio, # change - scaling_ratio_range=scaling_ratio_range, # change - # img_scale is (width, height) - border=(-img_scale[0] // 2, -img_scale[1] // 2), - border_val=(114, 114, 114)), -] - -mosiac9_pipeline = [ - dict( - type='Mosaic9', - img_scale=img_scale, - pad_val=114.0, - pre_transform=pre_transform), - dict( - type='YOLOv5RandomAffine', - max_rotate_degree=0.0, - max_shear_degree=0.0, - max_translate_ratio=max_translate_ratio, # change - scaling_ratio_range=scaling_ratio_range, # change - border=(-img_scale[0] // 2, -img_scale[1] // 2), - border_val=(114, 114, 114)), -] - -randchoice_mosaic_pipeline = dict( - type='RandomChoice', - transforms=[mosiac4_pipeline, mosiac9_pipeline], - prob=randchoice_mosaic_prob) - -train_pipeline = [ - *pre_transform, - randchoice_mosaic_pipeline, - dict( - type='YOLOv5MixUp', - alpha=mixup_alpha, - beta=mixup_beta, - prob=mixup_prob, # change - pre_transform=[*pre_transform, randchoice_mosaic_pipeline]), - dict(type='YOLOv5HSVRandomAug'), - dict(type='mmdet.RandomFlip', prob=0.5), - dict( - type='mmdet.PackDetInputs', - meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'flip', - 'flip_direction')) -] - -train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) -default_hooks = dict(param_scheduler=dict(lr_factor=lr_factor)) diff --git a/spaces/Ababababababbababa/Ashaar/langs.py b/spaces/Ababababababbababa/Ashaar/langs.py deleted file mode 100644 index ce66ea7bb4884344c705c066657646185ff3ebc0..0000000000000000000000000000000000000000 --- a/spaces/Ababababababbababa/Ashaar/langs.py +++ /dev/null @@ -1,59 +0,0 @@ -IMG = """

-logo for Ashaar -

- -""" -TITLE_ar="""

أَشْعــَـار: تحليل وإنشاء الشعر العربي

""" -DESCRIPTION_ar = IMG - -DESCRIPTION_ar +="""

-هذا البرنامج يتيح للمستخدم تحليل وإنشاء الشعر العربي. -لإنشاء الشعر العربي تم تدريب نموج يقوم بإستخدام البحر والقافية والعاطفة لإنشاء أكمال للقصيدة بناء على هذه الشروط. -بالإضافة إلى نموذج إنشاء الشعر يحتوي البرنامج على نماذج لتصنيف الحقبة الزمنية والعاطفة والبحر و كذلك تشكيل الشعر . -يقوم البرنامج بإستخدام هذه النماذج لإيجاد الخلل في القصيدة من خلال إضافة ألوان معينة تدل على اماكن الخلل. -لإستخدام البرنامج قم في البداية بكتابة قصيدة تحتوي على عدد زوجي من الأبيات و من ثم قم بالضغط على تحليل ، وبعد إنتهاء التحليل بالإمكان إنشاء إكمال للقصيدة. -عند الضغط على زر التحليل يتم إنشاء جدول التحليل الذي يشرح العديد من الأشياء : -

-""" -DESCRIPTION_ar+= """
- -
-""" -DESCRIPTION_ar+= """

-قمنا بتوفير الشفرة البرمجية كلها على - GitHub. -

-""" - -TITLE_en="""

Ashaar: Arabic Poetry Analysis and Generation

""" -DESCRIPTION_en = IMG - -DESCRIPTION_en +=""" -The demo provides a way to generate analysis for poetry and also complete the poetry. -The generative model is a character-based conditional GPT-2 model. The pipeline contains many models for -classification, diacritization and conditional generation. Check our GitHub for more techincal details -about this work. In the demo we have two basic pipelines. Analyze which predicts the meter, era, theme, diacritized text, qafiyah and, arudi style. -The other module, Generate which takes the input text, meter, theme and qafiyah to generate the full poem. -""" - -btn_trg_text_ar = "إنشاء" -btn_inp_text_ar = "تحليل" - -btn_inp_text_en = "Generate" -btn_trg_text_en = "Analyze" - -textbox_inp_text_ar = "القصيدة المدخلة" -textbox_trg_text_ar = "القصيدة المنشئة" - -textbox_trg_text_en = "Input Poem" -textbox_inp_text_en = "Generated Poem" - - - diff --git a/spaces/Abdllh/poetry2023/app.py b/spaces/Abdllh/poetry2023/app.py deleted file mode 100644 index 5b6654d5a405778ddbc9ca5fa5d041aff535f3b5..0000000000000000000000000000000000000000 --- a/spaces/Abdllh/poetry2023/app.py +++ /dev/null @@ -1,53 +0,0 @@ -import gc -import gradio as gr -from transformers import pipeline, set_seed - -pipe = pipeline('text-generation', framework='pt', model='akhooli/ap2023', tokenizer='akhooli/ap2023') -#gc.collect() -samples = [['أنت' - ,1.0, 50, 1.0, 1.0, 114],['هل غادر' - ,1.0, 50, 1.0, 1.0, 114 ],['ألا ليت' - ,1.0, 50, 1.0, 1.0, 114 ],['يا قدس' - ,1.0, 50, 1.0, 1.0, 114],['عيد بأية حال' - ,1.0, 50, 1.0, 1.0, 114],['لكل شيء إذا ما' - ,1.0, 50, 1.0, 1.0, 114 ],['.' - ,1.0, 50, 1.0, 1.0, 114]] - -notes = """ -- Enter a short prompt or select (click) one of the examples and click SEND -- Adjust parameters (temperture, top k, top p and penalty) through the slider (keep close to default values). -- For the same seed (randomness), the same output is regenerated if other parameters are fixed -- Clear and enter new prompt or select another example and SEND to regenerate -- The '.' means start a new line from no prompt (your prompt need not be long) -- Be patient: this runs on CPU (free tier) -- Feedback (Twitter): @akhooli (https://twitter.com/akhooli/status/1611025232201977859) -- Note/Disclaimer: may generate unaccepted or inappropriate content. Use at your own risk. -""" -def sayPoetry(prompt, temp=1.0, topk = 50, topp = 1.0, penalty=1.0, seed=114): - if not int(seed) >= 0: seed=114 - set_seed(seed) - gen = pipe(prompt, max_length=96, do_sample=True, temperature=temp, top_k=topk, top_p=topp, repetition_penalty=penalty, - min_length = 64, no_repeat_ngram_size = 3, return_full_text=True, - num_beams=5, num_return_sequences=1)[0]["generated_text"] - poetry ="" - for line in gen.split('.')[:-1]: - poetry += line #+ "\n" - return poetry -poetry = gr.Interface(fn=sayPoetry, - inputs=[ - gr.Textbox(label="Enter short prompt or select from examples:"), - gr.Slider(0.70, 1.2, step=0.01,value=1.0, label='control temperature'), - gr.Slider(25, 100, step=1,value=50, label='control top k'), - gr.Slider(0.80, 1.0, step=0.01,value=1.0, label='control top p'), - gr.Slider(0.90, 1.50, step=0.01,value=1.0, label='control penalty'), - gr.Number(value=139750, precision=0, label='Seed'), - ], - outputs=[gr.Textbox(label="Generated Poetry:")], - - allow_flagging='never', - title='Arabic Poetry Generation Demo (updated Jan. 2023)', - description = "A simple demo of AI generated poetry based on 1M poems fine-tuned using AraGPT2 (be patient, runs on cpu)", - examples=samples, - cache_examples=False, - article = notes) -poetry.launch() # show_error = True, debug=True \ No newline at end of file diff --git a/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/hooks/hook-librosa.py b/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/hooks/hook-librosa.py deleted file mode 100644 index 7bc3a51fd59885d030a68b9bde89c432dadaab2d..0000000000000000000000000000000000000000 --- a/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/hooks/hook-librosa.py +++ /dev/null @@ -1,3 +0,0 @@ -from PyInstaller.utils.hooks import copy_metadata - -datas = copy_metadata('librosa') diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/gridalign-plugin.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/gridalign-plugin.js deleted file mode 100644 index 74cdb7adbe56090743b137541360cb8425d66586..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/gridalign-plugin.js +++ /dev/null @@ -1,26 +0,0 @@ -import { - HexagonGridAlign, - QuadGridAlign -} from './gridalign.js'; - -class GridAlignPlugin extends Phaser.Plugins.BasePlugin { - - constructor(pluginManager) { - super(pluginManager); - } - - start() { - var eventEmitter = this.game.events; - eventEmitter.on('destroy', this.destroy, this); - } - - hexagon(items, options) { - return HexagonGridAlign(items, options); - } - - quad(items, options) { - return QuadGridAlign(items, options); - } -} - -export default GridAlignPlugin; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/Bejeweled.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/Bejeweled.d.ts deleted file mode 100644 index d8f4e99c7143d53801fae58cb6a1636dfbbed535..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/Bejeweled.d.ts +++ /dev/null @@ -1,192 +0,0 @@ -import ComponentBase from '../../plugins/utils/componentbase/ComponentBase'; -import Board from '../../plugins/board/board/Board'; -import Match from '../../plugins/board/match/Match'; -import MoveTo from '../../plugins/board/moveto/MoveTo'; -import { TileXYType } from '../../plugins/board/types/Position'; - -export default Bejeweled; - -declare namespace Bejeweled { - - type ChessSymbol = number | string; - - type GenerateSymbolCallbackType = ( - board: Board, - tileX: number, tileY: number, - excluded: undefined | ChessSymbol[] - ) => ChessSymbol; - - type CreateChessCallbackType = ( - board: Board - ) => Phaser.GameObjects.GameObject; - - type SwapActionType = ( - chess1: Phaser.GameObjects.GameObject, - chess2: Phaser.GameObjects.GameObject, - board: Board, - bejeweled: Bejeweled, - ) => void; - - type EliminatingActionType = ( - chessArray: Phaser.GameObjects.GameObject[], - board: Board, - bejeweled: Bejeweled, - ) => void; - - type FallingActionType = ( - board: Board, - bejeweled: Bejeweled, - ) => void; - - interface IConfig { - rexBoard?: string, - - board: Board.IConfig, - match?: Match.IConfig, - - chess: { - symbols: ChessSymbol[] | GenerateSymbolCallbackType, - - create: CreateChessCallbackType, - - scope?: object, - - moveTo?: MoveTo.IConfig, - - tileZ?: number | string, - }, - - swapAction?: SwapActionType, - - undoSwapAction?: SwapActionType, - - eliminatingAction?: EliminatingActionType, - - fallingAction?: FallingActionType, - - input?: boolean, - - mask?: boolean, - - debug?: boolean, - - } - - namespace Events { - type Select1CallbackType = (board: Board, bejeweled: Bejeweled) => void; - - type Select2CallbackType = (board: Board, bejeweled: Bejeweled) => void; - - type SwapCallbackType = ( - selectedChess1: Phaser.GameObjects.GameObject, - selectedChess2: Phaser.GameObjects.GameObject, - board: Board, bejeweled: Bejeweled - ) => void; - - type MatchStartCallbackType = (board: Board, bejeweled: Bejeweled) => void; - - type MatchCallbackType = ( - lines: Phaser.Structs.Set[], - board: Board, bejeweled: Bejeweled - ) => void; - - type EliminateCallbackType = ( - chessArray: Phaser.GameObjects.GameObject[], - board: Board, bejeweled: Bejeweled - ) => void; - - type FallCallbackType = (board: Board, bejeweled: Bejeweled) => void; - - type FillCallbackType = (board: Board, bejeweled: Bejeweled) => void; - - type MatchEndCallbackType = (board: Board, bejeweled: Bejeweled) => void; - - type UndoSwapCallbackType = ( - selectedChess1: Phaser.GameObjects.GameObject, - selectedChess2: Phaser.GameObjects.GameObject, - board: Board, bejeweled: Bejeweled - ) => void; - - type SetDataCallback = ( - bejeweled: Bejeweled, - key: string, value: any - ) => void; - - type ChangeetAnyDataCallback = ( - bejeweled: Bejeweled, - key: string, value: any, previousValue: any - ) => void; - - type ChangeetDataCallback = ( - bejeweled: Bejeweled, - value: any, previousValue: any - ) => void; - } -} - -declare class Bejeweled extends ComponentBase { - constructor( - scene: Phaser.Scene, - config?: Bejeweled.IConfig - ); - - start(): this; - - setInputEnable(enable?: boolean): this; - - worldXYToChess( - worldX: number, - worldY: number - ): Phaser.GameObjects.GameObject; - - tileXYToChess( - tileX: number, - tileY: number - ): Phaser.GameObjects.GameObject; - - getNeighborChessAtAngle( - chess: Phaser.GameObjects.GameObject | TileXYType, - angle: number - ): Phaser.GameObjects.GameObject; - - getNeighborChessAtDirection( - chess: Phaser.GameObjects.GameObject | TileXYType, - direction: number - ): Phaser.GameObjects.GameObject; - - selectChess1( - chess: Phaser.GameObjects.GameObject - ): this; - getSelectedChess1(): Phaser.GameObjects.GameObject; - - selectChess2( - chess: Phaser.GameObjects.GameObject - ): this; - getSelectedChess2(): Phaser.GameObjects.GameObject; - - getChessMoveTo( - chess: Phaser.GameObjects.GameObject - ): MoveTo | undefined; - - getChessTileZ(): number | string; - - getBoard(): Board; - getMatch(): Match; - - // Custom eliminateChess, falling action - waitEvent( - eventEmitter: Phaser.Events.EventEmitter, - eventName?: string - ): this; - isWaitingEvent(): boolean; - - // Data manager - setDataEnabled(): this; - setData(key: string, value: any): this; - incData(key: string, value: number): this; - toggleData(key: string): this; - getData(key: string): any; - data: Phaser.Data.DataManager; - - -} \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/grid/Grid.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/grid/Grid.js deleted file mode 100644 index 9690f11462dab772746954220f1b8cb1e2e45c54..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/grid/Grid.js +++ /dev/null @@ -1,60 +0,0 @@ -import Base from '../base/Base.js'; -import { Circle } from '../utils/Geoms.js'; -import Yoyo from '../utils/Yoyo.js'; - - -const Linear = Phaser.Math.Linear; -const RowNum = 3; -const ColNum = 3; - -class Grid extends Base { - constructor(scene, config) { - super(scene, config); - this.type = 'rexSpinnerGrid'; - } - - buildShapes() { - var cnt = RowNum * ColNum; - for (var i = 0; i < cnt; i++) { - var dot = new Circle(); - this.addShape(dot); - - dot.setData('offset', Math.random()); - } - } - - updateShapes() { - var centerX = this.centerX; - var centerY = this.centerY; - var radius = this.radius; - var isSizeChanged = this.isSizeChanged; - - var leftBound = centerX - radius; - var topBound = centerY - radius; - var cellWidth = (radius * 2) / ColNum; - var cellHeight = (radius * 2) / RowNum; - var maxDotRadius = (Math.min(cellWidth, cellHeight) / 2) * 0.8; - - - var shapes = this.getShapes(); - for (var i = 0, cnt = shapes.length; i < cnt; i++) { - var colIdx = (i % ColNum); - var rowIdx = Math.floor(i / RowNum); - var x = leftBound + cellWidth * (colIdx + 0.5); - var y = topBound + cellHeight * (rowIdx + 0.5); - - var dot = shapes[i]; - var t = (this.value + dot.getData('offset')) % 1; - t = Yoyo(t); - dot.fillStyle(this.color, Linear(0.25, 1, t)); - - if (isSizeChanged) { - dot - .setRadius(maxDotRadius) - .setCenterPosition(x, y) - } - } - } -} - -export default Grid; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/maker/index.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/maker/index.d.ts deleted file mode 100644 index 1b3ba0e597040a53bf0a9664635cd5efee6f5585..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/maker/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import Maker from './Maker'; -import Make from './Make'; -import YAMLMake from './YAMLMake'; -import Builders from './builders/Builders'; - - -export { - Maker, - Make, - YAMLMake, - Builders, -} \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/ninepatch/NinePatch.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/ninepatch/NinePatch.d.ts deleted file mode 100644 index b992996667ae521f9cec6b70679744c0258d7c3e..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/ninepatch/NinePatch.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import NinePatch from '../../../plugins/ninepatch'; -export default NinePatch; \ No newline at end of file diff --git a/spaces/AiMimicry/sovits-models/modules/__init__.py b/spaces/AiMimicry/sovits-models/modules/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Amon1/ChatGPTForAcadamic/project_self_analysis.md b/spaces/Amon1/ChatGPTForAcadamic/project_self_analysis.md deleted file mode 100644 index b1f530276c2c05ca0e5af894c4dc19cdad3dc446..0000000000000000000000000000000000000000 --- a/spaces/Amon1/ChatGPTForAcadamic/project_self_analysis.md +++ /dev/null @@ -1,175 +0,0 @@ -# chatgpt-academic项目自译解报告 -(Author补充:以下分析均由本项目调用ChatGPT一键生成,如果有不准确的地方,全怪GPT😄) - -## [0/18] 程序摘要: functional_crazy.py - -这是一个功能扩展的程序,文件名为 `functional_crazy.py`。代码的主要功能是通过提供一系列函数插件,增强程序的功能,让用户可以通过界面中的按钮,快速调用对应的函数插件实现相应的操作。代码中使用了 `HotReload` 函数插件,可以在不重启程序的情况下更新函数插件的代码,让其生效。同时,通过 `UserVisibleLevel` 变量的设置,可以控制哪些插件会在UI界面显示出来。函数插件列表包括了以下功能:解析项目本身、解析一个Python项目、解析一个C++项目头文件、解析一个C++项目、读取文章并生成摘要、批量生成函数注释、全项目切换成英文、批量总结PDF文档、批量总结PDF文档pdfminer、批量总结Word文档、高阶功能模板函数、以及其他未经充分测试的函数插件。 - -## [1/18] 程序摘要: main.py - -该程序是一个基于Gradio构建的对话生成模型的Web界面示例,包含了以下主要功能: - -1.加载模型并对用户输入进行响应; -2.通过调用外部函数库来获取用户的输入,并在模型生成的过程中进行处理; -3.支持用户上传本地文件,供外部函数库调用; -4.支持停止当前的生成过程; -5.保存用户的历史记录,并将其记录在本地日志文件中,以供后续分析和使用。 - -该程序需要依赖于一些外部库和软件包,如Gradio、torch等。用户需要确保这些依赖项已经安装,并且在运行该程序前对config_private.py配置文件进行相应的修改。 - -## [2/18] 程序摘要: functional.py - -该文件定义了一个名为“functional”的函数,函数的作用是返回一个包含多个字典(键值对)的字典,每个键值对表示一种功能。该字典的键值由功能名称和对应的数据组成。其中的每个字典都包含4个键值对,分别为“Prefix”、“Suffix”、“Color”和“PreProcess”,分别表示前缀、后缀、按钮颜色和预处理函数。如果某些键值对没有给出,那么程序中默认相应的值,如按钮颜色默认为“secondary”等。每个功能描述了不同的学术润色/翻译/其他服务,如“英语学术润色”、“中文学术润色”、“查找语法错误”等。函数还引用了一个名为“clear_line_break”的函数,用于预处理修改前的文本。 - -## [3/18] 程序摘要: show_math.py - -该程序文件名为show_math.py,主要用途是将Markdown和LaTeX混合格式转换成带有MathML的HTML格式。该程序通过递归地处理LaTeX和Markdown混合段落逐一转换成HTML/MathML标记出来,并在LaTeX公式创建中进行错误处理。在程序文件中定义了3个变量,分别是incomplete,convError和convert,其中convert函数是用来执行转换的主要函数。程序使用正则表达式进行LaTeX格式和Markdown段落的分割,从而实现转换。如果在Latex转换过程中发生错误,程序将输出相应的错误信息。 - -## [4/18] 程序摘要: predict.py - -本程序文件的文件名为"./predict.py",主要包含三个函数: - -1. predict:正常对话时使用,具备完备的交互功能,不可多线程; -2. predict_no_ui:高级实验性功能模块调用,不会实时显示在界面上,参数简单,可以多线程并行,方便实现复杂的功能逻辑; -3. predict_no_ui_long_connection:在实验过程中发现调用predict_no_ui处理长文档时,和openai的连接容易断掉,这个函数用stream的方式解决这个问题,同样支持多线程。 - -其中,predict函数用于基础的对话功能,发送至chatGPT,流式获取输出,根据点击的哪个按钮,进行对话预处理等额外操作;predict_no_ui函数用于payload比较大的情况,或者用于实现多线、带嵌套的复杂功能;predict_no_ui_long_connection实现调用predict_no_ui处理长文档时,避免连接断掉的情况,支持多线程。 - -## [5/18] 程序摘要: check_proxy.py - -该程序文件名为check_proxy.py,主要功能是检查代理服务器的可用性并返回代理服务器的地理位置信息或错误提示。具体实现方式如下: - -首先使用requests模块向指定网站(https://ipapi.co/json/)发送GET请求,请求结果以JSON格式返回。如果代理服务器参数(proxies)是有效的且没有指明'https'代理,则用默认字典值'无'替代。 - -然后,程序会解析返回的JSON数据,并根据数据中是否包含国家名字字段来判断代理服务器的地理位置。如果有国家名字字段,则将其打印出来并返回代理服务器的相关信息。如果没有国家名字字段,但有错误信息字段,则返回其他错误提示信息。 - -在程序执行前,程序会先设置环境变量no_proxy,并使用toolbox模块中的get_conf函数从配置文件中读取代理参数。 - -最后,检测程序会输出检查结果并返回对应的结果字符串。 - -## [6/18] 程序摘要: config_private.py - -本程序文件名为`config_private.py`,其功能为配置私有信息以便在主程序中使用。主要功能包括: - -- 配置OpenAI API的密钥和API URL -- 配置是否使用代理,如果使用代理配置代理地址和端口 -- 配置发送请求的超时时间和失败重试次数的限制 -- 配置并行使用线程数和用户名密码 -- 提供检查功能以确保API密钥已经正确设置 - -其中,需要特别注意的是:最后一个检查功能要求在运行之前必须将API密钥正确设置,否则程序会直接退出。 - -## [7/18] 程序摘要: config.py - -该程序文件是一个配置文件,用于配置OpenAI的API参数和优化体验的相关参数,具体包括以下几个步骤: - -1.设置OpenAI的API密钥。 - -2.选择是否使用代理,如果使用则需要设置代理地址和端口等参数。 - -3.设置请求OpenAI后的超时时间、网页的端口、重试次数、选择的OpenAI模型、API的网址等。 - -4.设置并行使用的线程数和用户名密码。 - -该程序文件的作用为在使用OpenAI API时进行相关参数的配置,以保证请求的正确性和速度,并且优化使用体验。 - -## [8/18] 程序摘要: theme.py - -该程序是一个自定义Gradio主题的Python模块。主题文件名为"./theme.py"。程序引入了Gradio模块,并定义了一个名为"adjust_theme()"的函数。该函数根据输入值调整Gradio的默认主题,返回一个包含所需自定义属性的主题对象。主题属性包括颜色、字体、过渡、阴影、按钮边框和渐变等。主题颜色列表包括石板色、灰色、锌色、中性色、石头色、红色、橙色、琥珀色、黄色、酸橙色、绿色、祖母绿、青蓝色、青色、天蓝色、蓝色、靛蓝色、紫罗兰色、紫色、洋红色、粉红色和玫瑰色。如果Gradio版本较旧,则不能自定义字体和颜色。 - -## [9/18] 程序摘要: toolbox.py - -该程序文件包含了一系列函数,用于实现聊天程序所需的各种功能,如预测对话、将对话记录写入文件、将普通文本转换为Markdown格式文本、装饰器函数CatchException和HotReload等。其中一些函数用到了第三方库,如Python-Markdown、mdtex2html、zipfile、tarfile、rarfile和py7zr。除此之外,还有一些辅助函数,如get_conf、clear_line_break和extract_archive等。主要功能包括: - -1. 导入markdown、mdtex2html、threading、functools等模块。 -2. 定义函数predict_no_ui_but_counting_down,用于生成对话。 -3. 定义函数write_results_to_file,用于将对话记录生成Markdown文件。 -4. 定义函数regular_txt_to_markdown,将普通文本转换为Markdown格式的文本。 -5. 定义装饰器函数CatchException,用于捕获函数执行异常并返回生成器。 -6. 定义函数report_execption,用于向chatbot中添加错误信息。 -7. 定义函数text_divide_paragraph,用于将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。 -8. 定义函数markdown_convertion,用于将Markdown格式的文本转换为HTML格式。 -9. 定义函数format_io,用于将输入和输出解析为HTML格式。 -10. 定义函数find_free_port,用于返回当前系统中可用的未使用端口。 -11. 定义函数extract_archive,用于解压归档文件。 -12. 定义函数find_recent_files,用于查找最近创建的文件。 -13. 定义函数on_file_uploaded,用于处理上传文件的操作。 -14. 定义函数on_report_generated,用于处理生成报告文件的操作。 - - -## [10/18] 程序摘要: crazy_functions/生成函数注释.py - -该程序文件是一个Python脚本,文件名为“生成函数注释.py”,位于“./crazy_functions/”目录下。该程序实现了一个批量生成函数注释的功能,可以对指定文件夹下的所有Python和C++源代码文件中的所有函数进行注释,使用Markdown表格输出注释结果。 - -该程序引用了predict.py和toolbox.py两个模块,其中predict.py实现了一个基于GPT模型的文本生成功能,用于生成函数注释,而toolbox.py实现了一些工具函数,包括异常处理函数、文本写入函数等。另外,该程序还定义了两个函数,一个是“生成函数注释”函数,用于处理单个文件的注释生成;另一个是“批量生成函数注释”函数,用于批量处理多个文件的注释生成。 - -## [11/18] 程序摘要: crazy_functions/读文章写摘要.py - -这个程序文件是一个名为“读文章写摘要”的函数。该函数的输入包括文章的文本内容、top_p(生成文本时选择最可能的词语的概率阈值)、temperature(控制生成文本的随机性的因子)、对话历史等参数,以及一个聊天机器人和一个系统提示的文本。该函数的主要工作是解析一组.tex文件,然后生成一段学术性语言的中文和英文摘要。在解析过程中,该函数使用一个名为“toolbox”的模块中的辅助函数和一个名为“predict”的模块中的函数来执行GPT-2模型的推理工作,然后将结果返回给聊天机器人。另外,该程序还包括一个名为“fast_debug”的bool型变量,用于调试和测试。 - -## [12/18] 程序摘要: crazy_functions/代码重写为全英文_多线程.py - -该程序文件实现了一个多线程操作,用于将指定目录下的所有 Python 文件中的中文转化为英文,并将转化后的文件存入另一个目录中。具体实现过程如下: - -1. 集合目标文件路径并清空历史记录。 -2. 循环目标文件,对每个文件启动一个线程进行任务操作。 -3. 各个线程同时开始执行任务函数,并在任务完成后将转化后的文件写入指定目录,最终生成一份任务执行报告。 - -## [13/18] 程序摘要: crazy_functions/高级功能函数模板.py - -该程序文件名为高级功能函数模板.py,它包含了一个名为“高阶功能模板函数”的函数,这个函数可以作为开发新功能函数的模板。该函数引用了predict.py和toolbox.py文件中的函数。在该函数内部,它首先清空了历史记录,然后对于今天和今天以后的四天,它问用户历史中哪些事件发生在这些日期,并列举两条事件并发送相关的图片。在向用户询问问题时,使用了GPT进行响应。由于请求GPT需要一定的时间,所以函数会在重新显示状态之前等待一段时间。在每次与用户的互动中,使用yield关键字生成器函数来输出聊天机器人的当前状态,包括聊天消息、历史记录和状态('正常')。最后,程序调用write_results_to_file函数将聊天的结果写入文件,以供后续的评估和分析。 - -## [14/18] 程序摘要: crazy_functions/总结word文档.py - -该程序文件名为总结word文档.py,主要功能是批量总结Word文档。具体实现过程是解析docx格式和doc格式文件,生成文件内容,然后使用自然语言处理工具对文章内容做中英文概述,最后给出建议。该程序需要依赖python-docx和pywin32,如果没有安装,会给出安装建议。 - -## [15/18] 程序摘要: crazy_functions/批量总结PDF文档pdfminer.py - -该程序文件名为pdfminer.py,位于./crazy_functions/目录下。程序实现了批量读取PDF文件,并使用pdfminer解析PDF文件内容。此外,程序还根据解析得到的文本内容,调用机器学习模型生成对每篇文章的概述,最终生成全文摘要。程序中还对模块依赖进行了导入检查,若缺少依赖,则会提供安装建议。 - -## [16/18] 程序摘要: crazy_functions/解析项目源代码.py - -这个程序文件中包含了几个函数,分别是: - -1. `解析源代码(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)`:通过输入文件路径列表对程序文件进行逐文件分析,根据分析结果做出整体功能和构架的概括,并生成包括每个文件功能的markdown表格。 -2. `解析项目本身(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)`:对当前文件夹下的所有Python文件及其子文件夹进行逐文件分析,并生成markdown表格。 -3. `解析一个Python项目(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)`:对指定路径下的所有Python文件及其子文件夹进行逐文件分析,并生成markdown表格。 -4. `解析一个C项目的头文件(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)`:对指定路径下的所有头文件进行逐文件分析,并生成markdown表格。 -5. `解析一个C项目(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)`:对指定路径下的所有.h、.cpp、.c文件及其子文件夹进行逐文件分析,并生成markdown表格。 - -程序中还包含了一些辅助函数和变量,如CatchException装饰器函数,report_execption函数、write_results_to_file函数等。在执行过程中还会调用其他模块中的函数,如toolbox模块的函数和predict模块的函数。 - -## [17/18] 程序摘要: crazy_functions/批量总结PDF文档.py - -这个程序文件是一个名为“批量总结PDF文档”的函数插件。它导入了predict和toolbox模块,并定义了一些函数,包括is_paragraph_break,normalize_text和clean_text。这些函数是对输入文本进行预处理和清洗的功能函数。主要的功能函数是解析PDF,它打开每个PDF文件并将其内容存储在file_content变量中,然后传递给聊天机器人,以产生一句话的概括。在解析PDF文件之后,该函数连接了所有文件的摘要,以产生一段学术语言和英文摘要。最后,函数批量处理目标文件夹中的所有PDF文件,并输出结果。 - -## 根据以上你自己的分析,对程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能。 - -该程序是一个聊天机器人,使用了OpenAI的GPT语言模型以及一些特殊的辅助功能去处理各种学术写作和科研润色任务。整个程序由一些函数组成,每个函数都代表了不同的学术润色/翻译/其他服务。 - -下面是程序中每个文件的功能列表: - -| 文件名 | 功能 | -|--------|--------| -| functional_crazy.py | 实现高级功能函数模板和其他一些辅助功能函数 | -| main.py | 程序的主要入口,负责程序的启动和UI的展示 | -| functional.py | 定义各种功能按钮的颜色和响应函数 | -| show_math.py | 解析LaTeX文本,将其转换为Markdown格式 | -| predict.py | 基础的对话功能,用于与chatGPT进行交互 | -| check_proxy.py | 检查代理设置的正确性 | -| config_private.py | 配置程序的API密钥和其他私有信息 | -| config.py | 配置OpenAI的API参数和程序的其他属性 | -| theme.py | 设置程序主题样式 | -| toolbox.py | 存放一些辅助函数供程序使用 | -| crazy_functions/生成函数注释.py | 生成Python文件中所有函数的注释 | -| crazy_functions/读文章写摘要.py | 解析文章文本,生成中英文摘要 | -| crazy_functions/代码重写为全英文_多线程.py | 将中文代码内容转化为英文 | -| crazy_functions/高级功能函数模板.py | 实现高级功能函数模板 | -| crazy_functions/总结word文档.py | 解析Word文件,生成文章内容的概要 | -| crazy_functions/批量总结PDF文档pdfminer.py | 解析PDF文件,生成文章内容的概要(使用pdfminer库) | -| crazy_functions/批量总结PDF文档.py | 解析PDF文件,生成文章内容的概要(使用PyMuPDF库) | -| crazy_functions/解析项目源代码.py | 解析C/C++源代码,生成markdown表格 | -| crazy_functions/批量总结PDF文档.py | 对PDF文件进行批量摘要生成 | - -总的来说,该程序提供了一系列的学术润色和翻译的工具,支持对各种类型的文件进行分析和处理。同时也提供了对话式用户界面,便于用户使用和交互。 - diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/dreambooth/train_dreambooth_lora.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/dreambooth/train_dreambooth_lora.py deleted file mode 100644 index 49b454f4636af8d358cf7a54c08b9314e44347e9..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/dreambooth/train_dreambooth_lora.py +++ /dev/null @@ -1,1418 +0,0 @@ -#!/usr/bin/env python -# coding=utf-8 -# Copyright 2023 The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and - -import argparse -import gc -import hashlib -import itertools -import logging -import math -import os -import shutil -import warnings -from pathlib import Path -from typing import Dict - -import numpy as np -import torch -import torch.nn.functional as F -import torch.utils.checkpoint -import transformers -from accelerate import Accelerator -from accelerate.logging import get_logger -from accelerate.utils import ProjectConfiguration, set_seed -from huggingface_hub import create_repo, upload_folder -from packaging import version -from PIL import Image -from PIL.ImageOps import exif_transpose -from torch.utils.data import Dataset -from torchvision import transforms -from tqdm.auto import tqdm -from transformers import AutoTokenizer, PretrainedConfig - -import diffusers -from diffusers import ( - AutoencoderKL, - DDPMScheduler, - DiffusionPipeline, - DPMSolverMultistepScheduler, - StableDiffusionPipeline, - UNet2DConditionModel, -) -from diffusers.loaders import ( - LoraLoaderMixin, - text_encoder_lora_state_dict, -) -from diffusers.models.attention_processor import ( - AttnAddedKVProcessor, - AttnAddedKVProcessor2_0, - LoRAAttnAddedKVProcessor, - LoRAAttnProcessor, - LoRAAttnProcessor2_0, - SlicedAttnAddedKVProcessor, -) -from diffusers.optimization import get_scheduler -from diffusers.utils import check_min_version, is_wandb_available -from diffusers.utils.import_utils import is_xformers_available - - -# Will error if the minimal version of diffusers is not installed. Remove at your own risks. -check_min_version("0.19.0") - -logger = get_logger(__name__) - - -def save_model_card( - repo_id: str, - images=None, - base_model=str, - train_text_encoder=False, - prompt=str, - repo_folder=None, - pipeline: DiffusionPipeline = None, -): - img_str = "" - for i, image in enumerate(images): - image.save(os.path.join(repo_folder, f"image_{i}.png")) - img_str += f"![img_{i}](./image_{i}.png)\n" - - yaml = f""" ---- -license: creativeml-openrail-m -base_model: {base_model} -instance_prompt: {prompt} -tags: -- {'stable-diffusion' if isinstance(pipeline, StableDiffusionPipeline) else 'if'} -- {'stable-diffusion-diffusers' if isinstance(pipeline, StableDiffusionPipeline) else 'if-diffusers'} -- text-to-image -- diffusers -- lora -inference: true ---- - """ - model_card = f""" -# LoRA DreamBooth - {repo_id} - -These are LoRA adaption weights for {base_model}. The weights were trained on {prompt} using [DreamBooth](https://dreambooth.github.io/). You can find some example images in the following. \n -{img_str} - -LoRA for the text encoder was enabled: {train_text_encoder}. -""" - with open(os.path.join(repo_folder, "README.md"), "w") as f: - f.write(yaml + model_card) - - -def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str): - text_encoder_config = PretrainedConfig.from_pretrained( - pretrained_model_name_or_path, - subfolder="text_encoder", - revision=revision, - ) - model_class = text_encoder_config.architectures[0] - - if model_class == "CLIPTextModel": - from transformers import CLIPTextModel - - return CLIPTextModel - elif model_class == "RobertaSeriesModelWithTransformation": - from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation - - return RobertaSeriesModelWithTransformation - elif model_class == "T5EncoderModel": - from transformers import T5EncoderModel - - return T5EncoderModel - else: - raise ValueError(f"{model_class} is not supported.") - - -def parse_args(input_args=None): - 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( - "--revision", - type=str, - default=None, - required=False, - help="Revision of pretrained 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, - required=True, - help="The prompt with identifier specifying the instance", - ) - parser.add_argument( - "--class_prompt", - type=str, - default=None, - help="The prompt to specify images in the same class as provided instance images.", - ) - parser.add_argument( - "--validation_prompt", - type=str, - default=None, - help="A prompt that is used during validation to verify that the model is learning.", - ) - parser.add_argument( - "--num_validation_images", - type=int, - default=4, - help="Number of images that should be generated during validation with `validation_prompt`.", - ) - parser.add_argument( - "--validation_epochs", - type=int, - default=50, - help=( - "Run dreambooth validation every X epochs. Dreambooth validation consists of running the prompt" - " `args.validation_prompt` multiple times: `args.num_validation_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 there are not enough images already present in" - " class_data_dir, additional images will be sampled with class_prompt." - ), - ) - parser.add_argument( - "--output_dir", - type=str, - default="lora-dreambooth-model", - 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", - default=False, - action="store_true", - help=( - "Whether to center crop the input images to the resolution. If not set, the images will be randomly" - " cropped. The images will be resized to the resolution first before cropping." - ), - ) - parser.add_argument( - "--train_text_encoder", - action="store_true", - help="Whether to train the text encoder. If set, the text encoder should be float32 precision.", - ) - 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( - "--checkpointing_steps", - type=int, - default=500, - help=( - "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final" - " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming" - " training using `--resume_from_checkpoint`." - ), - ) - parser.add_argument( - "--checkpoints_total_limit", - type=int, - default=None, - help=("Max number of checkpoints to store."), - ) - parser.add_argument( - "--resume_from_checkpoint", - type=str, - default=None, - help=( - "Whether training should be resumed from a previous checkpoint. Use a path saved by" - ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.' - ), - ) - 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-4, - 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( - "--lr_num_cycles", - type=int, - default=1, - help="Number of hard resets of the lr in cosine_with_restarts scheduler.", - ) - parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.") - parser.add_argument( - "--dataloader_num_workers", - type=int, - default=0, - help=( - "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process." - ), - ) - 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( - "--allow_tf32", - action="store_true", - help=( - "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see" - " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices" - ), - ) - parser.add_argument( - "--report_to", - type=str, - default="tensorboard", - help=( - 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`' - ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.' - ), - ) - parser.add_argument( - "--mixed_precision", - type=str, - default=None, - 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. Default to the value of accelerate config of the current system or the" - " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config." - ), - ) - parser.add_argument( - "--prior_generation_precision", - type=str, - default=None, - choices=["no", "fp32", "fp16", "bf16"], - help=( - "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" - " 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32." - ), - ) - parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") - parser.add_argument( - "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers." - ) - parser.add_argument( - "--pre_compute_text_embeddings", - action="store_true", - help="Whether or not to pre-compute text embeddings. If text embeddings are pre-computed, the text encoder will not be kept in memory during training and will leave more GPU memory available for training the rest of the model. This is not compatible with `--train_text_encoder`.", - ) - parser.add_argument( - "--tokenizer_max_length", - type=int, - default=None, - required=False, - help="The maximum length of the tokenizer. If not set, will default to the tokenizer's max length.", - ) - parser.add_argument( - "--text_encoder_use_attention_mask", - action="store_true", - required=False, - help="Whether to use attention mask for the text encoder", - ) - parser.add_argument( - "--validation_images", - required=False, - default=None, - nargs="+", - help="Optional set of images to use for validation. Used when the target pipeline takes an initial image as input such as when training image variation or superresolution.", - ) - parser.add_argument( - "--class_labels_conditioning", - required=False, - default=None, - help="The optional `class_label` conditioning to pass to the unet, available values are `timesteps`.", - ) - parser.add_argument( - "--rank", - type=int, - default=4, - help=("The dimension of the LoRA update matrices."), - ) - - if input_args is not None: - args = parser.parse_args(input_args) - else: - 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.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.") - else: - # logger is not available yet - if args.class_data_dir is not None: - warnings.warn("You need not use --class_data_dir without --with_prior_preservation.") - if args.class_prompt is not None: - warnings.warn("You need not use --class_prompt without --with_prior_preservation.") - - if args.train_text_encoder and args.pre_compute_text_embeddings: - raise ValueError("`--train_text_encoder` cannot be used with `--pre_compute_text_embeddings`") - - 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, - class_data_root=None, - class_prompt=None, - class_num=None, - size=512, - center_crop=False, - encoder_hidden_states=None, - instance_prompt_encoder_hidden_states=None, - tokenizer_max_length=None, - ): - self.size = size - self.center_crop = center_crop - self.tokenizer = tokenizer - self.encoder_hidden_states = encoder_hidden_states - self.instance_prompt_encoder_hidden_states = instance_prompt_encoder_hidden_states - self.tokenizer_max_length = tokenizer_max_length - - 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 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()) - if class_num is not None: - self.num_class_images = min(len(self.class_images_path), class_num) - else: - 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 = {} - instance_image = Image.open(self.instance_images_path[index % self.num_instance_images]) - instance_image = exif_transpose(instance_image) - - if not instance_image.mode == "RGB": - instance_image = instance_image.convert("RGB") - example["instance_images"] = self.image_transforms(instance_image) - - if self.encoder_hidden_states is not None: - example["instance_prompt_ids"] = self.encoder_hidden_states - else: - text_inputs = tokenize_prompt( - self.tokenizer, self.instance_prompt, tokenizer_max_length=self.tokenizer_max_length - ) - example["instance_prompt_ids"] = text_inputs.input_ids - example["instance_attention_mask"] = text_inputs.attention_mask - - if self.class_data_root: - class_image = Image.open(self.class_images_path[index % self.num_class_images]) - class_image = exif_transpose(class_image) - - if not class_image.mode == "RGB": - class_image = class_image.convert("RGB") - example["class_images"] = self.image_transforms(class_image) - - if self.instance_prompt_encoder_hidden_states is not None: - example["class_prompt_ids"] = self.instance_prompt_encoder_hidden_states - else: - class_text_inputs = tokenize_prompt( - self.tokenizer, self.class_prompt, tokenizer_max_length=self.tokenizer_max_length - ) - example["class_prompt_ids"] = class_text_inputs.input_ids - example["class_attention_mask"] = class_text_inputs.attention_mask - - return example - - -def collate_fn(examples, with_prior_preservation=False): - has_attention_mask = "instance_attention_mask" in examples[0] - - input_ids = [example["instance_prompt_ids"] for example in examples] - pixel_values = [example["instance_images"] for example in examples] - - if has_attention_mask: - attention_mask = [example["instance_attention_mask"] for example in examples] - - # Concat class and instance examples for prior preservation. - # We do this to avoid doing two forward passes. - if with_prior_preservation: - input_ids += [example["class_prompt_ids"] for example in examples] - pixel_values += [example["class_images"] for example in examples] - if has_attention_mask: - attention_mask += [example["class_attention_mask"] for example in examples] - - pixel_values = torch.stack(pixel_values) - pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float() - - input_ids = torch.cat(input_ids, dim=0) - - batch = { - "input_ids": input_ids, - "pixel_values": pixel_values, - } - - if has_attention_mask: - batch["attention_mask"] = attention_mask - - return batch - - -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 - - -def tokenize_prompt(tokenizer, prompt, tokenizer_max_length=None): - if tokenizer_max_length is not None: - max_length = tokenizer_max_length - else: - max_length = tokenizer.model_max_length - - text_inputs = tokenizer( - prompt, - truncation=True, - padding="max_length", - max_length=max_length, - return_tensors="pt", - ) - - return text_inputs - - -def encode_prompt(text_encoder, input_ids, attention_mask, text_encoder_use_attention_mask=None): - text_input_ids = input_ids.to(text_encoder.device) - - if text_encoder_use_attention_mask: - attention_mask = attention_mask.to(text_encoder.device) - else: - attention_mask = None - - prompt_embeds = text_encoder( - text_input_ids, - attention_mask=attention_mask, - ) - prompt_embeds = prompt_embeds[0] - - return prompt_embeds - - -def unet_attn_processors_state_dict(unet) -> Dict[str, torch.tensor]: - r""" - Returns: - a state dict containing just the attention processor parameters. - """ - attn_processors = unet.attn_processors - - attn_processors_state_dict = {} - - for attn_processor_key, attn_processor in attn_processors.items(): - for parameter_key, parameter in attn_processor.state_dict().items(): - attn_processors_state_dict[f"{attn_processor_key}.{parameter_key}"] = parameter - - return attn_processors_state_dict - - -def main(args): - logging_dir = Path(args.output_dir, args.logging_dir) - - accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir) - - accelerator = Accelerator( - gradient_accumulation_steps=args.gradient_accumulation_steps, - mixed_precision=args.mixed_precision, - log_with=args.report_to, - project_config=accelerator_project_config, - ) - - if args.report_to == "wandb": - if not is_wandb_available(): - raise ImportError("Make sure to install wandb if you want to use it for logging during training.") - import wandb - - # 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 (sayakpaul): 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." - ) - - # Make one log on every process with the configuration for debugging. - logging.basicConfig( - format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", - datefmt="%m/%d/%Y %H:%M:%S", - level=logging.INFO, - ) - logger.info(accelerator.state, main_process_only=False) - if accelerator.is_local_main_process: - transformers.utils.logging.set_verbosity_warning() - diffusers.utils.logging.set_verbosity_info() - else: - transformers.utils.logging.set_verbosity_error() - diffusers.utils.logging.set_verbosity_error() - - # If passed along, set the training seed now. - if args.seed is not None: - set_seed(args.seed) - - # Generate class images if prior preservation is enabled. - 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 - if args.prior_generation_precision == "fp32": - torch_dtype = torch.float32 - elif args.prior_generation_precision == "fp16": - torch_dtype = torch.float16 - elif args.prior_generation_precision == "bf16": - torch_dtype = torch.bfloat16 - pipeline = DiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - torch_dtype=torch_dtype, - safety_checker=None, - revision=args.revision, - ) - 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 - ): - images = pipeline(example["prompt"]).images - - for i, image in enumerate(images): - hash_image = hashlib.sha1(image.tobytes()).hexdigest() - image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg" - image.save(image_filename) - - del pipeline - if torch.cuda.is_available(): - torch.cuda.empty_cache() - - # Handle the repository creation - if accelerator.is_main_process: - if args.output_dir is not None: - os.makedirs(args.output_dir, exist_ok=True) - - if args.push_to_hub: - repo_id = create_repo( - repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token - ).repo_id - - # Load the tokenizer - if args.tokenizer_name: - tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False) - elif args.pretrained_model_name_or_path: - tokenizer = AutoTokenizer.from_pretrained( - args.pretrained_model_name_or_path, - subfolder="tokenizer", - revision=args.revision, - use_fast=False, - ) - - # import correct text encoder class - text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision) - - # Load scheduler and models - noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler") - text_encoder = text_encoder_cls.from_pretrained( - args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision - ) - try: - vae = AutoencoderKL.from_pretrained( - args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision - ) - except OSError: - # IF does not have a VAE so let's just set it to None - # We don't have to error out here - vae = None - - unet = UNet2DConditionModel.from_pretrained( - args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision - ) - - # We only train the additional adapter LoRA layers - if vae is not None: - vae.requires_grad_(False) - text_encoder.requires_grad_(False) - unet.requires_grad_(False) - - # For mixed precision training we cast all non-trainable weigths (vae, non-lora text_encoder and non-lora unet) to half-precision - # as these weights are only used for inference, keeping weights in full precision is not required. - weight_dtype = torch.float32 - if accelerator.mixed_precision == "fp16": - weight_dtype = torch.float16 - elif accelerator.mixed_precision == "bf16": - weight_dtype = torch.bfloat16 - - # Move unet, vae and text_encoder to device and cast to weight_dtype - unet.to(accelerator.device, dtype=weight_dtype) - if vae is not None: - vae.to(accelerator.device, dtype=weight_dtype) - text_encoder.to(accelerator.device, dtype=weight_dtype) - - if args.enable_xformers_memory_efficient_attention: - if is_xformers_available(): - import xformers - - xformers_version = version.parse(xformers.__version__) - if xformers_version == version.parse("0.0.16"): - logger.warn( - "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details." - ) - unet.enable_xformers_memory_efficient_attention() - else: - raise ValueError("xformers is not available. Make sure it is installed correctly") - - # now we will add new LoRA weights to the attention layers - # It's important to realize here how many attention weights will be added and of which sizes - # The sizes of the attention layers consist only of two different variables: - # 1) - the "hidden_size", which is increased according to `unet.config.block_out_channels`. - # 2) - the "cross attention size", which is set to `unet.config.cross_attention_dim`. - - # Let's first see how many attention processors we will have to set. - # For Stable Diffusion, it should be equal to: - # - down blocks (2x attention layers) * (2x transformer layers) * (3x down blocks) = 12 - # - mid blocks (2x attention layers) * (1x transformer layers) * (1x mid blocks) = 2 - # - up blocks (2x attention layers) * (3x transformer layers) * (3x down blocks) = 18 - # => 32 layers - - # Set correct lora layers - unet_lora_attn_procs = {} - unet_lora_parameters = [] - for name, attn_processor in unet.attn_processors.items(): - cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim - if name.startswith("mid_block"): - hidden_size = unet.config.block_out_channels[-1] - elif name.startswith("up_blocks"): - block_id = int(name[len("up_blocks.")]) - hidden_size = list(reversed(unet.config.block_out_channels))[block_id] - elif name.startswith("down_blocks"): - block_id = int(name[len("down_blocks.")]) - hidden_size = unet.config.block_out_channels[block_id] - - if isinstance(attn_processor, (AttnAddedKVProcessor, SlicedAttnAddedKVProcessor, AttnAddedKVProcessor2_0)): - lora_attn_processor_class = LoRAAttnAddedKVProcessor - else: - lora_attn_processor_class = ( - LoRAAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else LoRAAttnProcessor - ) - - module = lora_attn_processor_class( - hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=args.rank - ) - unet_lora_attn_procs[name] = module - unet_lora_parameters.extend(module.parameters()) - - unet.set_attn_processor(unet_lora_attn_procs) - - # The text encoder comes from 🤗 transformers, so we cannot directly modify it. - # So, instead, we monkey-patch the forward calls of its attention-blocks. - if args.train_text_encoder: - # ensure that dtype is float32, even if rest of the model that isn't trained is loaded in fp16 - text_lora_parameters = LoraLoaderMixin._modify_text_encoder(text_encoder, dtype=torch.float32, rank=args.rank) - - # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format - def save_model_hook(models, weights, output_dir): - # there are only two options here. Either are just the unet attn processor layers - # or there are the unet and text encoder atten layers - unet_lora_layers_to_save = None - text_encoder_lora_layers_to_save = None - - for model in models: - if isinstance(model, type(accelerator.unwrap_model(unet))): - unet_lora_layers_to_save = unet_attn_processors_state_dict(model) - elif isinstance(model, type(accelerator.unwrap_model(text_encoder))): - text_encoder_lora_layers_to_save = text_encoder_lora_state_dict(model) - else: - raise ValueError(f"unexpected save model: {model.__class__}") - - # make sure to pop weight so that corresponding model is not saved again - weights.pop() - - LoraLoaderMixin.save_lora_weights( - output_dir, - unet_lora_layers=unet_lora_layers_to_save, - text_encoder_lora_layers=text_encoder_lora_layers_to_save, - ) - - def load_model_hook(models, input_dir): - unet_ = None - text_encoder_ = None - - while len(models) > 0: - model = models.pop() - - if isinstance(model, type(accelerator.unwrap_model(unet))): - unet_ = model - elif isinstance(model, type(accelerator.unwrap_model(text_encoder))): - text_encoder_ = model - else: - raise ValueError(f"unexpected save model: {model.__class__}") - - lora_state_dict, network_alphas = LoraLoaderMixin.lora_state_dict(input_dir) - LoraLoaderMixin.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=unet_) - LoraLoaderMixin.load_lora_into_text_encoder( - lora_state_dict, network_alphas=network_alphas, text_encoder=text_encoder_ - ) - - accelerator.register_save_state_pre_hook(save_model_hook) - accelerator.register_load_state_pre_hook(load_model_hook) - - # Enable TF32 for faster training on Ampere GPUs, - # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices - if args.allow_tf32: - torch.backends.cuda.matmul.allow_tf32 = True - - 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 - - # Optimizer creation - params_to_optimize = ( - itertools.chain(unet_lora_parameters, text_lora_parameters) - if args.train_text_encoder - else unet_lora_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, - ) - - if args.pre_compute_text_embeddings: - - def compute_text_embeddings(prompt): - with torch.no_grad(): - text_inputs = tokenize_prompt(tokenizer, prompt, tokenizer_max_length=args.tokenizer_max_length) - prompt_embeds = encode_prompt( - text_encoder, - text_inputs.input_ids, - text_inputs.attention_mask, - text_encoder_use_attention_mask=args.text_encoder_use_attention_mask, - ) - - return prompt_embeds - - pre_computed_encoder_hidden_states = compute_text_embeddings(args.instance_prompt) - validation_prompt_negative_prompt_embeds = compute_text_embeddings("") - - if args.validation_prompt is not None: - validation_prompt_encoder_hidden_states = compute_text_embeddings(args.validation_prompt) - else: - validation_prompt_encoder_hidden_states = None - - if args.instance_prompt is not None: - pre_computed_instance_prompt_encoder_hidden_states = compute_text_embeddings(args.instance_prompt) - else: - pre_computed_instance_prompt_encoder_hidden_states = None - - text_encoder = None - tokenizer = None - - gc.collect() - torch.cuda.empty_cache() - else: - pre_computed_encoder_hidden_states = None - validation_prompt_encoder_hidden_states = None - validation_prompt_negative_prompt_embeds = None - pre_computed_instance_prompt_encoder_hidden_states = None - - # Dataset and DataLoaders creation: - 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, - class_num=args.num_class_images, - tokenizer=tokenizer, - size=args.resolution, - center_crop=args.center_crop, - encoder_hidden_states=pre_computed_encoder_hidden_states, - instance_prompt_encoder_hidden_states=pre_computed_instance_prompt_encoder_hidden_states, - tokenizer_max_length=args.tokenizer_max_length, - ) - - train_dataloader = torch.utils.data.DataLoader( - train_dataset, - batch_size=args.train_batch_size, - shuffle=True, - collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation), - num_workers=args.dataloader_num_workers, - ) - - # 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 * accelerator.num_processes, - num_training_steps=args.max_train_steps * accelerator.num_processes, - num_cycles=args.lr_num_cycles, - power=args.lr_power, - ) - - # Prepare everything with our `accelerator`. - 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 - ) - - # 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: - tracker_config = vars(args) - tracker_config.pop("validation_images") - accelerator.init_trackers("dreambooth-lora", config=tracker_config) - - # 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}") - global_step = 0 - first_epoch = 0 - - # Potentially load in the weights and states from a previous save - if args.resume_from_checkpoint: - if args.resume_from_checkpoint != "latest": - path = os.path.basename(args.resume_from_checkpoint) - else: - # Get the mos recent checkpoint - dirs = os.listdir(args.output_dir) - dirs = [d for d in dirs if d.startswith("checkpoint")] - dirs = sorted(dirs, key=lambda x: int(x.split("-")[1])) - path = dirs[-1] if len(dirs) > 0 else None - - if path is None: - accelerator.print( - f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run." - ) - args.resume_from_checkpoint = None - else: - accelerator.print(f"Resuming from checkpoint {path}") - accelerator.load_state(os.path.join(args.output_dir, path)) - global_step = int(path.split("-")[1]) - - resume_global_step = global_step * args.gradient_accumulation_steps - first_epoch = global_step // num_update_steps_per_epoch - resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps) - - # Only show the progress bar once on each machine. - progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process) - progress_bar.set_description("Steps") - - for epoch in range(first_epoch, args.num_train_epochs): - unet.train() - if args.train_text_encoder: - text_encoder.train() - for step, batch in enumerate(train_dataloader): - # Skip steps until we reach the resumed step - if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step: - if step % args.gradient_accumulation_steps == 0: - progress_bar.update(1) - continue - - with accelerator.accumulate(unet): - pixel_values = batch["pixel_values"].to(dtype=weight_dtype) - - if vae is not None: - # Convert images to latent space - model_input = vae.encode(pixel_values).latent_dist.sample() - model_input = model_input * vae.config.scaling_factor - else: - model_input = pixel_values - - # Sample noise that we'll add to the latents - noise = torch.randn_like(model_input) - bsz, channels, height, width = model_input.shape - # Sample a random timestep for each image - timesteps = torch.randint( - 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=model_input.device - ) - timesteps = timesteps.long() - - # Add noise to the model input according to the noise magnitude at each timestep - # (this is the forward diffusion process) - noisy_model_input = noise_scheduler.add_noise(model_input, noise, timesteps) - - # Get the text embedding for conditioning - if args.pre_compute_text_embeddings: - encoder_hidden_states = batch["input_ids"] - else: - encoder_hidden_states = encode_prompt( - text_encoder, - batch["input_ids"], - batch["attention_mask"], - text_encoder_use_attention_mask=args.text_encoder_use_attention_mask, - ) - - if accelerator.unwrap_model(unet).config.in_channels == channels * 2: - noisy_model_input = torch.cat([noisy_model_input, noisy_model_input], dim=1) - - if args.class_labels_conditioning == "timesteps": - class_labels = timesteps - else: - class_labels = None - - # Predict the noise residual - model_pred = unet( - noisy_model_input, timesteps, encoder_hidden_states, class_labels=class_labels - ).sample - - # if model predicts variance, throw away the prediction. we will only train on the - # simplified training objective. This means that all schedulers using the fine tuned - # model must be configured to use one of the fixed variance variance types. - if model_pred.shape[1] == 6: - model_pred, _ = torch.chunk(model_pred, 2, dim=1) - - # 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(model_input, 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="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_lora_parameters, text_lora_parameters) - if args.train_text_encoder - else unet_lora_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 - - if accelerator.is_main_process: - if global_step % args.checkpointing_steps == 0: - # _before_ saving state, check if this save would set us over the `checkpoints_total_limit` - if args.checkpoints_total_limit is not None: - checkpoints = os.listdir(args.output_dir) - checkpoints = [d for d in checkpoints if d.startswith("checkpoint")] - checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1])) - - # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints - if len(checkpoints) >= args.checkpoints_total_limit: - num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1 - removing_checkpoints = checkpoints[0:num_to_remove] - - logger.info( - f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints" - ) - logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}") - - for removing_checkpoint in removing_checkpoints: - removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint) - shutil.rmtree(removing_checkpoint) - - save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}") - accelerator.save_state(save_path) - logger.info(f"Saved state to {save_path}") - - logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]} - progress_bar.set_postfix(**logs) - accelerator.log(logs, step=global_step) - - if global_step >= args.max_train_steps: - break - - if accelerator.is_main_process: - if args.validation_prompt is not None and epoch % args.validation_epochs == 0: - logger.info( - f"Running validation... \n Generating {args.num_validation_images} images with prompt:" - f" {args.validation_prompt}." - ) - # create pipeline - pipeline = DiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - unet=accelerator.unwrap_model(unet), - text_encoder=None if args.pre_compute_text_embeddings else accelerator.unwrap_model(text_encoder), - revision=args.revision, - torch_dtype=weight_dtype, - ) - - # We train on the simplified learning objective. If we were previously predicting a variance, we need the scheduler to ignore it - scheduler_args = {} - - if "variance_type" in pipeline.scheduler.config: - variance_type = pipeline.scheduler.config.variance_type - - if variance_type in ["learned", "learned_range"]: - variance_type = "fixed_small" - - scheduler_args["variance_type"] = variance_type - - pipeline.scheduler = DPMSolverMultistepScheduler.from_config( - pipeline.scheduler.config, **scheduler_args - ) - - pipeline = pipeline.to(accelerator.device) - pipeline.set_progress_bar_config(disable=True) - - # run inference - generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None - if args.pre_compute_text_embeddings: - pipeline_args = { - "prompt_embeds": validation_prompt_encoder_hidden_states, - "negative_prompt_embeds": validation_prompt_negative_prompt_embeds, - } - else: - pipeline_args = {"prompt": args.validation_prompt} - - if args.validation_images is None: - images = [] - for _ in range(args.num_validation_images): - with torch.cuda.amp.autocast(): - image = pipeline(**pipeline_args, generator=generator).images[0] - images.append(image) - else: - images = [] - for image in args.validation_images: - image = Image.open(image) - with torch.cuda.amp.autocast(): - image = pipeline(**pipeline_args, image=image, generator=generator).images[0] - images.append(image) - - for tracker in accelerator.trackers: - if tracker.name == "tensorboard": - np_images = np.stack([np.asarray(img) for img in images]) - tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC") - if tracker.name == "wandb": - tracker.log( - { - "validation": [ - wandb.Image(image, caption=f"{i}: {args.validation_prompt}") - for i, image in enumerate(images) - ] - } - ) - - del pipeline - torch.cuda.empty_cache() - - # Save the lora layers - accelerator.wait_for_everyone() - if accelerator.is_main_process: - unet = accelerator.unwrap_model(unet) - unet = unet.to(torch.float32) - unet_lora_layers = unet_attn_processors_state_dict(unet) - - if text_encoder is not None and args.train_text_encoder: - text_encoder = accelerator.unwrap_model(text_encoder) - text_encoder = text_encoder.to(torch.float32) - text_encoder_lora_layers = text_encoder_lora_state_dict(text_encoder) - else: - text_encoder_lora_layers = None - - LoraLoaderMixin.save_lora_weights( - save_directory=args.output_dir, - unet_lora_layers=unet_lora_layers, - text_encoder_lora_layers=text_encoder_lora_layers, - ) - - # Final inference - # Load previous pipeline - pipeline = DiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, revision=args.revision, torch_dtype=weight_dtype - ) - - # We train on the simplified learning objective. If we were previously predicting a variance, we need the scheduler to ignore it - scheduler_args = {} - - if "variance_type" in pipeline.scheduler.config: - variance_type = pipeline.scheduler.config.variance_type - - if variance_type in ["learned", "learned_range"]: - variance_type = "fixed_small" - - scheduler_args["variance_type"] = variance_type - - pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, **scheduler_args) - - pipeline = pipeline.to(accelerator.device) - - # load attention processors - pipeline.load_lora_weights(args.output_dir, weight_name="pytorch_lora_weights.bin") - - # run inference - images = [] - if args.validation_prompt and args.num_validation_images > 0: - generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None - images = [ - pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0] - for _ in range(args.num_validation_images) - ] - - for tracker in accelerator.trackers: - if tracker.name == "tensorboard": - np_images = np.stack([np.asarray(img) for img in images]) - tracker.writer.add_images("test", np_images, epoch, dataformats="NHWC") - if tracker.name == "wandb": - tracker.log( - { - "test": [ - wandb.Image(image, caption=f"{i}: {args.validation_prompt}") - for i, image in enumerate(images) - ] - } - ) - - if args.push_to_hub: - save_model_card( - repo_id, - images=images, - base_model=args.pretrained_model_name_or_path, - train_text_encoder=args.train_text_encoder, - prompt=args.instance_prompt, - repo_folder=args.output_dir, - pipeline=pipeline, - ) - upload_folder( - repo_id=repo_id, - folder_path=args.output_dir, - commit_message="End of training", - ignore_patterns=["step_*", "epoch_*"], - ) - - accelerator.end_training() - - -if __name__ == "__main__": - args = parse_args() - main(args) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco.py deleted file mode 100644 index 3bd33c40263fc3a5bc44d09f5e3368ea9a859b0f..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './ms_rcnn_r50_caffe_fpn_1x_coco.py' -model = dict( - pretrained='open-mmlab://detectron2/resnet101_caffe', - backbone=dict(depth=101)) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco.py deleted file mode 100644 index 202bccedae84657737b0315394199208d0307ae4..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './ms_rcnn_r101_caffe_fpn_1x_coco.py' -# learning policy -lr_config = dict(step=[16, 22]) -runner = dict(type='EpochBasedRunner', max_epochs=24) diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/fpn_uniformer.py b/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/fpn_uniformer.py deleted file mode 100644 index 8aae98c5991055bfcc08e82ccdc09f8b1d9f8a8d..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/fpn_uniformer.py +++ /dev/null @@ -1,35 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='EncoderDecoder', - backbone=dict( - type='UniFormer', - embed_dim=[64, 128, 320, 512], - layers=[3, 4, 8, 3], - head_dim=64, - mlp_ratio=4., - qkv_bias=True, - drop_rate=0., - attn_drop_rate=0., - drop_path_rate=0.1), - neck=dict( - type='FPN', - in_channels=[64, 128, 320, 512], - out_channels=256, - num_outs=4), - decode_head=dict( - type='FPNHead', - in_channels=[256, 256, 256, 256], - in_index=[0, 1, 2, 3], - feature_strides=[4, 8, 16, 32], - channels=128, - dropout_ratio=0.1, - num_classes=150, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - # model training and testing settings - train_cfg=dict(), - test_cfg=dict(mode='whole') -) diff --git a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/one_click_installer_check.py b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/one_click_installer_check.py deleted file mode 100644 index 1a7dd2b9b8d510fc1229e813f56d8052ac800ff3..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/one_click_installer_check.py +++ /dev/null @@ -1,8 +0,0 @@ -from pathlib import Path -from modules.logging_colors import logger - -if Path('../webui.py').exists(): - logger.warning('\nIt looks like you are running an outdated version of ' - 'the one-click-installers.\n' - 'Please migrate your installation following the instructions here:\n' - 'https://github.com/oobabooga/text-generation-webui/wiki/Migrating-an-old-one%E2%80%90click-install') diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/ldm/modules/diffusionmodules/upscaling.py b/spaces/Anonymous-sub/Rerender/ControlNet/ldm/modules/diffusionmodules/upscaling.py deleted file mode 100644 index 03816662098ce1ffac79bd939b892e867ab91988..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/ldm/modules/diffusionmodules/upscaling.py +++ /dev/null @@ -1,81 +0,0 @@ -import torch -import torch.nn as nn -import numpy as np -from functools import partial - -from ldm.modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule -from ldm.util import default - - -class AbstractLowScaleModel(nn.Module): - # for concatenating a downsampled image to the latent representation - def __init__(self, noise_schedule_config=None): - super(AbstractLowScaleModel, self).__init__() - if noise_schedule_config is not None: - self.register_schedule(**noise_schedule_config) - - def register_schedule(self, beta_schedule="linear", timesteps=1000, - linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): - betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, - cosine_s=cosine_s) - alphas = 1. - betas - alphas_cumprod = np.cumprod(alphas, axis=0) - alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) - - timesteps, = betas.shape - self.num_timesteps = int(timesteps) - self.linear_start = linear_start - self.linear_end = linear_end - assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' - - to_torch = partial(torch.tensor, dtype=torch.float32) - - self.register_buffer('betas', to_torch(betas)) - self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) - self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) - - # calculations for diffusion q(x_t | x_{t-1}) and others - self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) - self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) - self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) - self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) - self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) - - 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) - - def forward(self, x): - return x, None - - def decode(self, x): - return x - - -class SimpleImageConcat(AbstractLowScaleModel): - # no noise level conditioning - def __init__(self): - super(SimpleImageConcat, self).__init__(noise_schedule_config=None) - self.max_noise_level = 0 - - def forward(self, x): - # fix to constant noise level - return x, torch.zeros(x.shape[0], device=x.device).long() - - -class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel): - def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False): - super().__init__(noise_schedule_config=noise_schedule_config) - self.max_noise_level = max_noise_level - - def forward(self, x, noise_level=None): - if noise_level is None: - noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long() - else: - assert isinstance(noise_level, torch.Tensor) - z = self.q_sample(x, noise_level) - return z, noise_level - - - diff --git a/spaces/Arnx/MusicGenXvAKN/tests/quantization/test_vq.py b/spaces/Arnx/MusicGenXvAKN/tests/quantization/test_vq.py deleted file mode 100644 index c215099fedacae35c6798fdd9b8420a447aa16bb..0000000000000000000000000000000000000000 --- a/spaces/Arnx/MusicGenXvAKN/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/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/packaging/_structures.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/packaging/_structures.py deleted file mode 100644 index 90a6465f9682c886363eea5327dac64bf623a6ff..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/packaging/_structures.py +++ /dev/null @@ -1,61 +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. - - -class InfinityType: - def __repr__(self) -> str: - return "Infinity" - - def __hash__(self) -> int: - return hash(repr(self)) - - def __lt__(self, other: object) -> bool: - return False - - def __le__(self, other: object) -> bool: - return False - - def __eq__(self, other: object) -> bool: - return isinstance(other, self.__class__) - - def __gt__(self, other: object) -> bool: - return True - - def __ge__(self, other: object) -> bool: - return True - - def __neg__(self: object) -> "NegativeInfinityType": - return NegativeInfinity - - -Infinity = InfinityType() - - -class NegativeInfinityType: - def __repr__(self) -> str: - return "-Infinity" - - def __hash__(self) -> int: - return hash(repr(self)) - - def __lt__(self, other: object) -> bool: - return True - - def __le__(self, other: object) -> bool: - return True - - def __eq__(self, other: object) -> bool: - return isinstance(other, self.__class__) - - def __gt__(self, other: object) -> bool: - return False - - def __ge__(self, other: object) -> bool: - return False - - def __neg__(self: object) -> InfinityType: - return Infinity - - -NegativeInfinity = NegativeInfinityType() diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/adapters.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/adapters.py deleted file mode 100644 index f68f7d467530845447278f6c0ad104b4beca9531..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/adapters.py +++ /dev/null @@ -1,584 +0,0 @@ -""" -requests.adapters -~~~~~~~~~~~~~~~~~ - -This module contains the transport adapters that Requests uses to define -and maintain connections. -""" - -import os.path -import socket # noqa: F401 - -from pip._vendor.urllib3.exceptions import ClosedPoolError, ConnectTimeoutError -from pip._vendor.urllib3.exceptions import HTTPError as _HTTPError -from pip._vendor.urllib3.exceptions import InvalidHeader as _InvalidHeader -from pip._vendor.urllib3.exceptions import ( - LocationValueError, - MaxRetryError, - NewConnectionError, - ProtocolError, -) -from pip._vendor.urllib3.exceptions import ProxyError as _ProxyError -from pip._vendor.urllib3.exceptions import ReadTimeoutError, ResponseError -from pip._vendor.urllib3.exceptions import SSLError as _SSLError -from pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url -from pip._vendor.urllib3.response import HTTPResponse -from pip._vendor.urllib3.util import Timeout as TimeoutSauce -from pip._vendor.urllib3.util import parse_url -from pip._vendor.urllib3.util.retry import Retry - -from .auth import _basic_auth_str -from .compat import basestring, urlparse -from .cookies import extract_cookies_to_jar -from .exceptions import ( - ConnectionError, - ConnectTimeout, - InvalidHeader, - InvalidProxyURL, - InvalidSchema, - InvalidURL, - ProxyError, - ReadTimeout, - RetryError, - SSLError, -) -from .models import Response -from .structures import CaseInsensitiveDict -from .utils import ( - DEFAULT_CA_BUNDLE_PATH, - extract_zipped_paths, - get_auth_from_url, - get_encoding_from_headers, - prepend_scheme_if_needed, - select_proxy, - urldefragauth, -) - -try: - from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager -except ImportError: - - def SOCKSProxyManager(*args, **kwargs): - raise InvalidSchema("Missing dependencies for SOCKS support.") - - -DEFAULT_POOLBLOCK = False -DEFAULT_POOLSIZE = 10 -DEFAULT_RETRIES = 0 -DEFAULT_POOL_TIMEOUT = None - - -class BaseAdapter: - """The Base Transport Adapter""" - - def __init__(self): - super().__init__() - - def send( - self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None - ): - """Sends PreparedRequest object. Returns Response object. - - :param request: The :class:`PreparedRequest ` being sent. - :param stream: (optional) Whether to stream the request content. - :param timeout: (optional) How long to wait for the server to send - data before giving up, as a float, or a :ref:`(connect timeout, - read timeout) ` tuple. - :type timeout: float or tuple - :param verify: (optional) Either a boolean, in which case it controls whether we verify - the server's TLS certificate, or a string, in which case it must be a path - to a CA bundle to use - :param cert: (optional) Any user-provided SSL certificate to be trusted. - :param proxies: (optional) The proxies dictionary to apply to the request. - """ - raise NotImplementedError - - def close(self): - """Cleans up adapter specific items.""" - raise NotImplementedError - - -class HTTPAdapter(BaseAdapter): - """The built-in HTTP Adapter for urllib3. - - Provides a general-case interface for Requests sessions to contact HTTP and - HTTPS urls by implementing the Transport Adapter interface. This class will - usually be created by the :class:`Session ` class under the - covers. - - :param pool_connections: The number of urllib3 connection pools to cache. - :param pool_maxsize: The maximum number of connections to save in the pool. - :param max_retries: The maximum number of retries each connection - should attempt. Note, this applies only to failed DNS lookups, socket - connections and connection timeouts, never to requests where data has - made it to the server. By default, Requests does not retry failed - connections. If you need granular control over the conditions under - which we retry a request, import urllib3's ``Retry`` class and pass - that instead. - :param pool_block: Whether the connection pool should block for connections. - - Usage:: - - >>> import requests - >>> s = requests.Session() - >>> a = requests.adapters.HTTPAdapter(max_retries=3) - >>> s.mount('http://', a) - """ - - __attrs__ = [ - "max_retries", - "config", - "_pool_connections", - "_pool_maxsize", - "_pool_block", - ] - - def __init__( - self, - pool_connections=DEFAULT_POOLSIZE, - pool_maxsize=DEFAULT_POOLSIZE, - max_retries=DEFAULT_RETRIES, - pool_block=DEFAULT_POOLBLOCK, - ): - if max_retries == DEFAULT_RETRIES: - self.max_retries = Retry(0, read=False) - else: - self.max_retries = Retry.from_int(max_retries) - self.config = {} - self.proxy_manager = {} - - super().__init__() - - self._pool_connections = pool_connections - self._pool_maxsize = pool_maxsize - self._pool_block = pool_block - - self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) - - def __getstate__(self): - return {attr: getattr(self, attr, None) for attr in self.__attrs__} - - def __setstate__(self, state): - # Can't handle by adding 'proxy_manager' to self.__attrs__ because - # self.poolmanager uses a lambda function, which isn't pickleable. - self.proxy_manager = {} - self.config = {} - - for attr, value in state.items(): - setattr(self, attr, value) - - self.init_poolmanager( - self._pool_connections, self._pool_maxsize, block=self._pool_block - ) - - def init_poolmanager( - self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs - ): - """Initializes a urllib3 PoolManager. - - This method should not be called from user code, and is only - exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param connections: The number of urllib3 connection pools to cache. - :param maxsize: The maximum number of connections to save in the pool. - :param block: Block when no free connections are available. - :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. - """ - # save these values for pickling - self._pool_connections = connections - self._pool_maxsize = maxsize - self._pool_block = block - - self.poolmanager = PoolManager( - num_pools=connections, - maxsize=maxsize, - block=block, - strict=True, - **pool_kwargs, - ) - - def proxy_manager_for(self, proxy, **proxy_kwargs): - """Return urllib3 ProxyManager for the given proxy. - - This method should not be called from user code, and is only - exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param proxy: The proxy to return a urllib3 ProxyManager for. - :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. - :returns: ProxyManager - :rtype: urllib3.ProxyManager - """ - if proxy in self.proxy_manager: - manager = self.proxy_manager[proxy] - elif proxy.lower().startswith("socks"): - username, password = get_auth_from_url(proxy) - manager = self.proxy_manager[proxy] = SOCKSProxyManager( - proxy, - username=username, - password=password, - num_pools=self._pool_connections, - maxsize=self._pool_maxsize, - block=self._pool_block, - **proxy_kwargs, - ) - else: - proxy_headers = self.proxy_headers(proxy) - manager = self.proxy_manager[proxy] = proxy_from_url( - proxy, - proxy_headers=proxy_headers, - num_pools=self._pool_connections, - maxsize=self._pool_maxsize, - block=self._pool_block, - **proxy_kwargs, - ) - - return manager - - def cert_verify(self, conn, url, verify, cert): - """Verify a SSL certificate. This method should not be called from user - code, and is only exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param conn: The urllib3 connection object associated with the cert. - :param url: The requested URL. - :param verify: Either a boolean, in which case it controls whether we verify - the server's TLS certificate, or a string, in which case it must be a path - to a CA bundle to use - :param cert: The SSL certificate to verify. - """ - if url.lower().startswith("https") and verify: - - cert_loc = None - - # Allow self-specified cert location. - if verify is not True: - cert_loc = verify - - if not cert_loc: - cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) - - if not cert_loc or not os.path.exists(cert_loc): - raise OSError( - f"Could not find a suitable TLS CA certificate bundle, " - f"invalid path: {cert_loc}" - ) - - conn.cert_reqs = "CERT_REQUIRED" - - if not os.path.isdir(cert_loc): - conn.ca_certs = cert_loc - else: - conn.ca_cert_dir = cert_loc - else: - conn.cert_reqs = "CERT_NONE" - conn.ca_certs = None - conn.ca_cert_dir = None - - if cert: - if not isinstance(cert, basestring): - conn.cert_file = cert[0] - conn.key_file = cert[1] - else: - conn.cert_file = cert - conn.key_file = None - if conn.cert_file and not os.path.exists(conn.cert_file): - raise OSError( - f"Could not find the TLS certificate file, " - f"invalid path: {conn.cert_file}" - ) - if conn.key_file and not os.path.exists(conn.key_file): - raise OSError( - f"Could not find the TLS key file, invalid path: {conn.key_file}" - ) - - def build_response(self, req, resp): - """Builds a :class:`Response ` object from a urllib3 - response. This should not be called from user code, and is only exposed - for use when subclassing the - :class:`HTTPAdapter ` - - :param req: The :class:`PreparedRequest ` used to generate the response. - :param resp: The urllib3 response object. - :rtype: requests.Response - """ - response = Response() - - # Fallback to None if there's no status_code, for whatever reason. - response.status_code = getattr(resp, "status", None) - - # Make headers case-insensitive. - response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) - - # Set encoding. - response.encoding = get_encoding_from_headers(response.headers) - response.raw = resp - response.reason = response.raw.reason - - if isinstance(req.url, bytes): - response.url = req.url.decode("utf-8") - else: - response.url = req.url - - # Add new cookies from the server. - extract_cookies_to_jar(response.cookies, req, resp) - - # Give the Response some context. - response.request = req - response.connection = self - - return response - - def get_connection(self, url, proxies=None): - """Returns a urllib3 connection for the given URL. This should not be - called from user code, and is only exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param url: The URL to connect to. - :param proxies: (optional) A Requests-style dictionary of proxies used on this request. - :rtype: urllib3.ConnectionPool - """ - proxy = select_proxy(url, proxies) - - if proxy: - proxy = prepend_scheme_if_needed(proxy, "http") - proxy_url = parse_url(proxy) - if not proxy_url.host: - raise InvalidProxyURL( - "Please check proxy URL. It is malformed " - "and could be missing the host." - ) - proxy_manager = self.proxy_manager_for(proxy) - conn = proxy_manager.connection_from_url(url) - else: - # Only scheme should be lower case - parsed = urlparse(url) - url = parsed.geturl() - conn = self.poolmanager.connection_from_url(url) - - return conn - - def close(self): - """Disposes of any internal state. - - Currently, this closes the PoolManager and any active ProxyManager, - which closes any pooled connections. - """ - self.poolmanager.clear() - for proxy in self.proxy_manager.values(): - proxy.clear() - - def request_url(self, request, proxies): - """Obtain the url to use when making the final request. - - If the message is being sent through a HTTP proxy, the full URL has to - be used. Otherwise, we should only use the path portion of the URL. - - This should not be called from user code, and is only exposed for use - when subclassing the - :class:`HTTPAdapter `. - - :param request: The :class:`PreparedRequest ` being sent. - :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. - :rtype: str - """ - proxy = select_proxy(request.url, proxies) - scheme = urlparse(request.url).scheme - - is_proxied_http_request = proxy and scheme != "https" - using_socks_proxy = False - if proxy: - proxy_scheme = urlparse(proxy).scheme.lower() - using_socks_proxy = proxy_scheme.startswith("socks") - - url = request.path_url - if is_proxied_http_request and not using_socks_proxy: - url = urldefragauth(request.url) - - return url - - def add_headers(self, request, **kwargs): - """Add any headers needed by the connection. As of v2.0 this does - nothing by default, but is left for overriding by users that subclass - the :class:`HTTPAdapter `. - - This should not be called from user code, and is only exposed for use - when subclassing the - :class:`HTTPAdapter `. - - :param request: The :class:`PreparedRequest ` to add headers to. - :param kwargs: The keyword arguments from the call to send(). - """ - pass - - def proxy_headers(self, proxy): - """Returns a dictionary of the headers to add to any request sent - through a proxy. This works with urllib3 magic to ensure that they are - correctly sent to the proxy, rather than in a tunnelled request if - CONNECT is being used. - - This should not be called from user code, and is only exposed for use - when subclassing the - :class:`HTTPAdapter `. - - :param proxy: The url of the proxy being used for this request. - :rtype: dict - """ - headers = {} - username, password = get_auth_from_url(proxy) - - if username: - headers["Proxy-Authorization"] = _basic_auth_str(username, password) - - return headers - - def send( - self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None - ): - """Sends PreparedRequest object. Returns Response object. - - :param request: The :class:`PreparedRequest ` being sent. - :param stream: (optional) Whether to stream the request content. - :param timeout: (optional) How long to wait for the server to send - data before giving up, as a float, or a :ref:`(connect timeout, - read timeout) ` tuple. - :type timeout: float or tuple or urllib3 Timeout object - :param verify: (optional) Either a boolean, in which case it controls whether - we verify the server's TLS certificate, or a string, in which case it - must be a path to a CA bundle to use - :param cert: (optional) Any user-provided SSL certificate to be trusted. - :param proxies: (optional) The proxies dictionary to apply to the request. - :rtype: requests.Response - """ - - try: - conn = self.get_connection(request.url, proxies) - except LocationValueError as e: - raise InvalidURL(e, request=request) - - self.cert_verify(conn, request.url, verify, cert) - url = self.request_url(request, proxies) - self.add_headers( - request, - stream=stream, - timeout=timeout, - verify=verify, - cert=cert, - proxies=proxies, - ) - - chunked = not (request.body is None or "Content-Length" in request.headers) - - if isinstance(timeout, tuple): - try: - connect, read = timeout - timeout = TimeoutSauce(connect=connect, read=read) - except ValueError: - raise ValueError( - f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " - f"or a single float to set both timeouts to the same value." - ) - elif isinstance(timeout, TimeoutSauce): - pass - else: - timeout = TimeoutSauce(connect=timeout, read=timeout) - - try: - if not chunked: - resp = conn.urlopen( - method=request.method, - url=url, - body=request.body, - headers=request.headers, - redirect=False, - assert_same_host=False, - preload_content=False, - decode_content=False, - retries=self.max_retries, - timeout=timeout, - ) - - # Send the request. - else: - if hasattr(conn, "proxy_pool"): - conn = conn.proxy_pool - - low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) - - try: - skip_host = "Host" in request.headers - low_conn.putrequest( - request.method, - url, - skip_accept_encoding=True, - skip_host=skip_host, - ) - - for header, value in request.headers.items(): - low_conn.putheader(header, value) - - low_conn.endheaders() - - for i in request.body: - low_conn.send(hex(len(i))[2:].encode("utf-8")) - low_conn.send(b"\r\n") - low_conn.send(i) - low_conn.send(b"\r\n") - low_conn.send(b"0\r\n\r\n") - - # Receive the response from the server - r = low_conn.getresponse() - - resp = HTTPResponse.from_httplib( - r, - pool=conn, - connection=low_conn, - preload_content=False, - decode_content=False, - ) - except Exception: - # If we hit any problems here, clean up the connection. - # Then, raise so that we can handle the actual exception. - low_conn.close() - raise - - except (ProtocolError, OSError) as err: - raise ConnectionError(err, request=request) - - except MaxRetryError as e: - if isinstance(e.reason, ConnectTimeoutError): - # TODO: Remove this in 3.0.0: see #2811 - if not isinstance(e.reason, NewConnectionError): - raise ConnectTimeout(e, request=request) - - if isinstance(e.reason, ResponseError): - raise RetryError(e, request=request) - - if isinstance(e.reason, _ProxyError): - raise ProxyError(e, request=request) - - if isinstance(e.reason, _SSLError): - # This branch is for urllib3 v1.22 and later. - raise SSLError(e, request=request) - - raise ConnectionError(e, request=request) - - except ClosedPoolError as e: - raise ConnectionError(e, request=request) - - except _ProxyError as e: - raise ProxyError(e) - - except (_SSLError, _HTTPError) as e: - if isinstance(e, _SSLError): - # This branch is for urllib3 versions earlier than v1.22 - raise SSLError(e, request=request) - elif isinstance(e, ReadTimeoutError): - raise ReadTimeout(e, request=request) - elif isinstance(e, _InvalidHeader): - raise InvalidHeader(e, request=request) - else: - raise - - return self.build_response(request, resp) diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/msvc9compiler.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/msvc9compiler.py deleted file mode 100644 index 22021831086ea8b2db134f7a2310a803abf5f982..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/msvc9compiler.py +++ /dev/null @@ -1,832 +0,0 @@ -"""distutils.msvc9compiler - -Contains MSVCCompiler, an implementation of the abstract CCompiler class -for the Microsoft Visual Studio 2008. - -The module is compatible with VS 2005 and VS 2008. You can find legacy support -for older versions of VS in distutils.msvccompiler. -""" - -# Written by Perry Stoll -# hacked by Robin Becker and Thomas Heller to do a better job of -# finding DevStudio (through the registry) -# ported to VS2005 and VS 2008 by Christian Heimes - -import os -import subprocess -import sys -import re -import warnings - -from distutils.errors import ( - DistutilsExecError, - DistutilsPlatformError, - CompileError, - LibError, - LinkError, -) -from distutils.ccompiler import CCompiler, gen_lib_options -from distutils import log -from distutils.util import get_platform - -import winreg - -warnings.warn( - "msvc9compiler is deprecated and slated to be removed " - "in the future. Please discontinue use or file an issue " - "with pypa/distutils describing your use case.", - DeprecationWarning, -) - -RegOpenKeyEx = winreg.OpenKeyEx -RegEnumKey = winreg.EnumKey -RegEnumValue = winreg.EnumValue -RegError = winreg.error - -HKEYS = ( - winreg.HKEY_USERS, - winreg.HKEY_CURRENT_USER, - winreg.HKEY_LOCAL_MACHINE, - winreg.HKEY_CLASSES_ROOT, -) - -NATIVE_WIN64 = sys.platform == 'win32' and sys.maxsize > 2**32 -if NATIVE_WIN64: - # Visual C++ is a 32-bit application, so we need to look in - # the corresponding registry branch, if we're running a - # 64-bit Python on Win64 - VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f" - WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows" - NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework" -else: - VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f" - WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows" - NET_BASE = r"Software\Microsoft\.NETFramework" - -# A map keyed by get_platform() return values to values accepted by -# 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is -# the param to cross-compile on x86 targeting amd64.) -PLAT_TO_VCVARS = { - 'win32': 'x86', - 'win-amd64': 'amd64', -} - - -class Reg: - """Helper class to read values from the registry""" - - def get_value(cls, path, key): - for base in HKEYS: - d = cls.read_values(base, path) - if d and key in d: - return d[key] - raise KeyError(key) - - get_value = classmethod(get_value) - - def read_keys(cls, base, key): - """Return list of registry keys.""" - try: - handle = RegOpenKeyEx(base, key) - except RegError: - return None - L = [] - i = 0 - while True: - try: - k = RegEnumKey(handle, i) - except RegError: - break - L.append(k) - i += 1 - return L - - read_keys = classmethod(read_keys) - - def read_values(cls, base, key): - """Return dict of registry keys and values. - - All names are converted to lowercase. - """ - try: - handle = RegOpenKeyEx(base, key) - except RegError: - return None - d = {} - i = 0 - while True: - try: - name, value, type = RegEnumValue(handle, i) - except RegError: - break - name = name.lower() - d[cls.convert_mbcs(name)] = cls.convert_mbcs(value) - i += 1 - return d - - read_values = classmethod(read_values) - - def convert_mbcs(s): - dec = getattr(s, "decode", None) - if dec is not None: - try: - s = dec("mbcs") - except UnicodeError: - pass - return s - - convert_mbcs = staticmethod(convert_mbcs) - - -class MacroExpander: - def __init__(self, version): - self.macros = {} - self.vsbase = VS_BASE % version - self.load_macros(version) - - def set_macro(self, macro, path, key): - self.macros["$(%s)" % macro] = Reg.get_value(path, key) - - def load_macros(self, version): - self.set_macro("VCInstallDir", self.vsbase + r"\Setup\VC", "productdir") - self.set_macro("VSInstallDir", self.vsbase + r"\Setup\VS", "productdir") - self.set_macro("FrameworkDir", NET_BASE, "installroot") - try: - if version >= 8.0: - self.set_macro("FrameworkSDKDir", NET_BASE, "sdkinstallrootv2.0") - else: - raise KeyError("sdkinstallrootv2.0") - except KeyError: - raise DistutilsPlatformError( - """Python was built with Visual Studio 2008; -extensions must be built with a compiler than can generate compatible binaries. -Visual Studio 2008 was not found on this system. If you have Cygwin installed, -you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""" - ) - - if version >= 9.0: - self.set_macro("FrameworkVersion", self.vsbase, "clr version") - self.set_macro("WindowsSdkDir", WINSDK_BASE, "currentinstallfolder") - else: - p = r"Software\Microsoft\NET Framework Setup\Product" - for base in HKEYS: - try: - h = RegOpenKeyEx(base, p) - except RegError: - continue - key = RegEnumKey(h, 0) - d = Reg.get_value(base, r"{}\{}".format(p, key)) - self.macros["$(FrameworkVersion)"] = d["version"] - - def sub(self, s): - for k, v in self.macros.items(): - s = s.replace(k, v) - return s - - -def get_build_version(): - """Return the version of MSVC that was used to build Python. - - For Python 2.3 and up, the version number is included in - sys.version. For earlier versions, assume the compiler is MSVC 6. - """ - prefix = "MSC v." - i = sys.version.find(prefix) - if i == -1: - return 6 - i = i + len(prefix) - s, rest = sys.version[i:].split(" ", 1) - majorVersion = int(s[:-2]) - 6 - if majorVersion >= 13: - # v13 was skipped and should be v14 - majorVersion += 1 - minorVersion = int(s[2:3]) / 10.0 - # I don't think paths are affected by minor version in version 6 - if majorVersion == 6: - minorVersion = 0 - if majorVersion >= 6: - return majorVersion + minorVersion - # else we don't know what version of the compiler this is - return None - - -def normalize_and_reduce_paths(paths): - """Return a list of normalized paths with duplicates removed. - - The current order of paths is maintained. - """ - # Paths are normalized so things like: /a and /a/ aren't both preserved. - reduced_paths = [] - for p in paths: - np = os.path.normpath(p) - # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set. - if np not in reduced_paths: - reduced_paths.append(np) - return reduced_paths - - -def removeDuplicates(variable): - """Remove duplicate values of an environment variable.""" - oldList = variable.split(os.pathsep) - newList = [] - for i in oldList: - if i not in newList: - newList.append(i) - newVariable = os.pathsep.join(newList) - return newVariable - - -def find_vcvarsall(version): - """Find the vcvarsall.bat file - - At first it tries to find the productdir of VS 2008 in the registry. If - that fails it falls back to the VS90COMNTOOLS env var. - """ - vsbase = VS_BASE % version - try: - productdir = Reg.get_value(r"%s\Setup\VC" % vsbase, "productdir") - except KeyError: - log.debug("Unable to find productdir in registry") - productdir = None - - if not productdir or not os.path.isdir(productdir): - toolskey = "VS%0.f0COMNTOOLS" % version - toolsdir = os.environ.get(toolskey, None) - - if toolsdir and os.path.isdir(toolsdir): - productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") - productdir = os.path.abspath(productdir) - if not os.path.isdir(productdir): - log.debug("%s is not a valid directory" % productdir) - return None - else: - log.debug("Env var %s is not set or invalid" % toolskey) - if not productdir: - log.debug("No productdir found") - return None - vcvarsall = os.path.join(productdir, "vcvarsall.bat") - if os.path.isfile(vcvarsall): - return vcvarsall - log.debug("Unable to find vcvarsall.bat") - return None - - -def query_vcvarsall(version, arch="x86"): - """Launch vcvarsall.bat and read the settings from its environment""" - vcvarsall = find_vcvarsall(version) - interesting = {"include", "lib", "libpath", "path"} - result = {} - - if vcvarsall is None: - raise DistutilsPlatformError("Unable to find vcvarsall.bat") - log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) - popen = subprocess.Popen( - '"{}" {} & set'.format(vcvarsall, arch), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - try: - stdout, stderr = popen.communicate() - if popen.wait() != 0: - raise DistutilsPlatformError(stderr.decode("mbcs")) - - stdout = stdout.decode("mbcs") - for line in stdout.split("\n"): - line = Reg.convert_mbcs(line) - if '=' not in line: - continue - line = line.strip() - key, value = line.split('=', 1) - key = key.lower() - if key in interesting: - if value.endswith(os.pathsep): - value = value[:-1] - result[key] = removeDuplicates(value) - - finally: - popen.stdout.close() - popen.stderr.close() - - if len(result) != len(interesting): - raise ValueError(str(list(result.keys()))) - - return result - - -# More globals -VERSION = get_build_version() -# MACROS = MacroExpander(VERSION) - - -class MSVCCompiler(CCompiler): - """Concrete class that implements an interface to Microsoft Visual C++, - as defined by the CCompiler abstract class.""" - - compiler_type = 'msvc' - - # Just set this so CCompiler's constructor doesn't barf. We currently - # don't use the 'set_executables()' bureaucracy provided by CCompiler, - # as it really isn't necessary for this sort of single-compiler class. - # Would be nice to have a consistent interface with UnixCCompiler, - # though, so it's worth thinking about. - executables = {} - - # Private class data (need to distinguish C from C++ source for compiler) - _c_extensions = ['.c'] - _cpp_extensions = ['.cc', '.cpp', '.cxx'] - _rc_extensions = ['.rc'] - _mc_extensions = ['.mc'] - - # Needed for the filename generation methods provided by the - # base class, CCompiler. - src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions - res_extension = '.res' - obj_extension = '.obj' - static_lib_extension = '.lib' - shared_lib_extension = '.dll' - static_lib_format = shared_lib_format = '%s%s' - exe_extension = '.exe' - - def __init__(self, verbose=0, dry_run=0, force=0): - super().__init__(verbose, dry_run, force) - self.__version = VERSION - self.__root = r"Software\Microsoft\VisualStudio" - # self.__macros = MACROS - self.__paths = [] - # target platform (.plat_name is consistent with 'bdist') - self.plat_name = None - self.__arch = None # deprecated name - self.initialized = False - - def initialize(self, plat_name=None): # noqa: C901 - # multi-init means we would need to check platform same each time... - assert not self.initialized, "don't init multiple times" - if self.__version < 8.0: - raise DistutilsPlatformError( - "VC %0.1f is not supported by this module" % self.__version - ) - if plat_name is None: - plat_name = get_platform() - # sanity check for platforms to prevent obscure errors later. - ok_plats = 'win32', 'win-amd64' - if plat_name not in ok_plats: - raise DistutilsPlatformError( - "--plat-name must be one of {}".format(ok_plats) - ) - - if ( - "DISTUTILS_USE_SDK" in os.environ - and "MSSdk" in os.environ - and self.find_exe("cl.exe") - ): - # Assume that the SDK set up everything alright; don't try to be - # smarter - self.cc = "cl.exe" - self.linker = "link.exe" - self.lib = "lib.exe" - self.rc = "rc.exe" - self.mc = "mc.exe" - else: - # On x86, 'vcvars32.bat amd64' creates an env that doesn't work; - # to cross compile, you use 'x86_amd64'. - # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross - # compile use 'x86' (ie, it runs the x86 compiler directly) - if plat_name == get_platform() or plat_name == 'win32': - # native build or cross-compile to win32 - plat_spec = PLAT_TO_VCVARS[plat_name] - else: - # cross compile from win32 -> some 64bit - plat_spec = ( - PLAT_TO_VCVARS[get_platform()] + '_' + PLAT_TO_VCVARS[plat_name] - ) - - vc_env = query_vcvarsall(VERSION, plat_spec) - - self.__paths = vc_env['path'].split(os.pathsep) - os.environ['lib'] = vc_env['lib'] - os.environ['include'] = vc_env['include'] - - if len(self.__paths) == 0: - raise DistutilsPlatformError( - "Python was built with %s, " - "and extensions need to be built with the same " - "version of the compiler, but it isn't installed." % self.__product - ) - - self.cc = self.find_exe("cl.exe") - self.linker = self.find_exe("link.exe") - self.lib = self.find_exe("lib.exe") - self.rc = self.find_exe("rc.exe") # resource compiler - self.mc = self.find_exe("mc.exe") # message compiler - # self.set_path_env_var('lib') - # self.set_path_env_var('include') - - # extend the MSVC path with the current path - try: - for p in os.environ['path'].split(';'): - self.__paths.append(p) - except KeyError: - pass - self.__paths = normalize_and_reduce_paths(self.__paths) - os.environ['path'] = ";".join(self.__paths) - - self.preprocess_options = None - if self.__arch == "x86": - self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/DNDEBUG'] - self.compile_options_debug = [ - '/nologo', - '/Od', - '/MDd', - '/W3', - '/Z7', - '/D_DEBUG', - ] - else: - # Win64 - self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG'] - self.compile_options_debug = [ - '/nologo', - '/Od', - '/MDd', - '/W3', - '/GS-', - '/Z7', - '/D_DEBUG', - ] - - self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO'] - if self.__version >= 7: - self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'] - self.ldflags_static = ['/nologo'] - - self.initialized = True - - # -- Worker methods ------------------------------------------------ - - def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): - # Copied from ccompiler.py, extended to return .res as 'object'-file - # for .rc input file - if output_dir is None: - output_dir = '' - obj_names = [] - for src_name in source_filenames: - (base, ext) = os.path.splitext(src_name) - base = os.path.splitdrive(base)[1] # Chop off the drive - base = base[os.path.isabs(base) :] # If abs, chop off leading / - if ext not in self.src_extensions: - # Better to raise an exception instead of silently continuing - # and later complain about sources and targets having - # different lengths - raise CompileError("Don't know how to compile %s" % src_name) - if strip_dir: - base = os.path.basename(base) - if ext in self._rc_extensions: - obj_names.append(os.path.join(output_dir, base + self.res_extension)) - elif ext in self._mc_extensions: - obj_names.append(os.path.join(output_dir, base + self.res_extension)) - else: - obj_names.append(os.path.join(output_dir, base + self.obj_extension)) - return obj_names - - def compile( # noqa: C901 - self, - sources, - output_dir=None, - macros=None, - include_dirs=None, - debug=0, - extra_preargs=None, - extra_postargs=None, - depends=None, - ): - - if not self.initialized: - self.initialize() - compile_info = self._setup_compile( - output_dir, macros, include_dirs, sources, depends, extra_postargs - ) - macros, objects, extra_postargs, pp_opts, build = compile_info - - compile_opts = extra_preargs or [] - compile_opts.append('/c') - if debug: - compile_opts.extend(self.compile_options_debug) - else: - compile_opts.extend(self.compile_options) - - for obj in objects: - try: - src, ext = build[obj] - except KeyError: - continue - if debug: - # pass the full pathname to MSVC in debug mode, - # this allows the debugger to find the source file - # without asking the user to browse for it - src = os.path.abspath(src) - - if ext in self._c_extensions: - input_opt = "/Tc" + src - elif ext in self._cpp_extensions: - input_opt = "/Tp" + src - elif ext in self._rc_extensions: - # compile .RC to .RES file - input_opt = src - output_opt = "/fo" + obj - try: - self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt]) - except DistutilsExecError as msg: - raise CompileError(msg) - continue - elif ext in self._mc_extensions: - # Compile .MC to .RC file to .RES file. - # * '-h dir' specifies the directory for the - # generated include file - # * '-r dir' specifies the target directory of the - # generated RC file and the binary message resource - # it includes - # - # For now (since there are no options to change this), - # we use the source-directory for the include file and - # the build directory for the RC file and message - # resources. This works at least for win32all. - h_dir = os.path.dirname(src) - rc_dir = os.path.dirname(obj) - try: - # first compile .MC to .RC and .H file - self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src]) - base, _ = os.path.splitext(os.path.basename(src)) - rc_file = os.path.join(rc_dir, base + '.rc') - # then compile .RC to .RES file - self.spawn([self.rc] + ["/fo" + obj] + [rc_file]) - - except DistutilsExecError as msg: - raise CompileError(msg) - continue - else: - # how to handle this file? - raise CompileError( - "Don't know how to compile {} to {}".format(src, obj) - ) - - output_opt = "/Fo" + obj - try: - self.spawn( - [self.cc] - + compile_opts - + pp_opts - + [input_opt, output_opt] - + extra_postargs - ) - except DistutilsExecError as msg: - raise CompileError(msg) - - return objects - - def create_static_lib( - self, objects, output_libname, output_dir=None, debug=0, target_lang=None - ): - - if not self.initialized: - self.initialize() - (objects, output_dir) = self._fix_object_args(objects, output_dir) - output_filename = self.library_filename(output_libname, output_dir=output_dir) - - if self._need_link(objects, output_filename): - lib_args = objects + ['/OUT:' + output_filename] - if debug: - pass # XXX what goes here? - try: - self.spawn([self.lib] + lib_args) - except DistutilsExecError as msg: - raise LibError(msg) - else: - log.debug("skipping %s (up-to-date)", output_filename) - - def link( # noqa: C901 - self, - target_desc, - objects, - output_filename, - output_dir=None, - libraries=None, - library_dirs=None, - runtime_library_dirs=None, - export_symbols=None, - debug=0, - extra_preargs=None, - extra_postargs=None, - build_temp=None, - target_lang=None, - ): - - if not self.initialized: - self.initialize() - (objects, output_dir) = self._fix_object_args(objects, output_dir) - fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) - (libraries, library_dirs, runtime_library_dirs) = fixed_args - - if runtime_library_dirs: - self.warn( - "I don't know what to do with 'runtime_library_dirs': " - + str(runtime_library_dirs) - ) - - lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) - if output_dir is not None: - output_filename = os.path.join(output_dir, output_filename) - - if self._need_link(objects, output_filename): - if target_desc == CCompiler.EXECUTABLE: - if debug: - ldflags = self.ldflags_shared_debug[1:] - else: - ldflags = self.ldflags_shared[1:] - else: - if debug: - ldflags = self.ldflags_shared_debug - else: - ldflags = self.ldflags_shared - - export_opts = [] - for sym in export_symbols or []: - export_opts.append("/EXPORT:" + sym) - - ld_args = ( - ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename] - ) - - # The MSVC linker generates .lib and .exp files, which cannot be - # suppressed by any linker switches. The .lib files may even be - # needed! Make sure they are generated in the temporary build - # directory. Since they have different names for debug and release - # builds, they can go into the same directory. - build_temp = os.path.dirname(objects[0]) - if export_symbols is not None: - (dll_name, dll_ext) = os.path.splitext( - os.path.basename(output_filename) - ) - implib_file = os.path.join(build_temp, self.library_filename(dll_name)) - ld_args.append('/IMPLIB:' + implib_file) - - self.manifest_setup_ldargs(output_filename, build_temp, ld_args) - - if extra_preargs: - ld_args[:0] = extra_preargs - if extra_postargs: - ld_args.extend(extra_postargs) - - self.mkpath(os.path.dirname(output_filename)) - try: - self.spawn([self.linker] + ld_args) - except DistutilsExecError as msg: - raise LinkError(msg) - - # embed the manifest - # XXX - this is somewhat fragile - if mt.exe fails, distutils - # will still consider the DLL up-to-date, but it will not have a - # manifest. Maybe we should link to a temp file? OTOH, that - # implies a build environment error that shouldn't go undetected. - mfinfo = self.manifest_get_embed_info(target_desc, ld_args) - if mfinfo is not None: - mffilename, mfid = mfinfo - out_arg = '-outputresource:{};{}'.format(output_filename, mfid) - try: - self.spawn(['mt.exe', '-nologo', '-manifest', mffilename, out_arg]) - except DistutilsExecError as msg: - raise LinkError(msg) - else: - log.debug("skipping %s (up-to-date)", output_filename) - - def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): - # If we need a manifest at all, an embedded manifest is recommended. - # See MSDN article titled - # "How to: Embed a Manifest Inside a C/C++ Application" - # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx) - # Ask the linker to generate the manifest in the temp dir, so - # we can check it, and possibly embed it, later. - temp_manifest = os.path.join( - build_temp, os.path.basename(output_filename) + ".manifest" - ) - ld_args.append('/MANIFESTFILE:' + temp_manifest) - - def manifest_get_embed_info(self, target_desc, ld_args): - # If a manifest should be embedded, return a tuple of - # (manifest_filename, resource_id). Returns None if no manifest - # should be embedded. See http://bugs.python.org/issue7833 for why - # we want to avoid any manifest for extension modules if we can) - for arg in ld_args: - if arg.startswith("/MANIFESTFILE:"): - temp_manifest = arg.split(":", 1)[1] - break - else: - # no /MANIFESTFILE so nothing to do. - return None - if target_desc == CCompiler.EXECUTABLE: - # by default, executables always get the manifest with the - # CRT referenced. - mfid = 1 - else: - # Extension modules try and avoid any manifest if possible. - mfid = 2 - temp_manifest = self._remove_visual_c_ref(temp_manifest) - if temp_manifest is None: - return None - return temp_manifest, mfid - - def _remove_visual_c_ref(self, manifest_file): - try: - # Remove references to the Visual C runtime, so they will - # fall through to the Visual C dependency of Python.exe. - # This way, when installed for a restricted user (e.g. - # runtimes are not in WinSxS folder, but in Python's own - # folder), the runtimes do not need to be in every folder - # with .pyd's. - # Returns either the filename of the modified manifest or - # None if no manifest should be embedded. - manifest_f = open(manifest_file) - try: - manifest_buf = manifest_f.read() - finally: - manifest_f.close() - pattern = re.compile( - r"""|)""", - re.DOTALL, - ) - manifest_buf = re.sub(pattern, "", manifest_buf) - pattern = r"\s*" - manifest_buf = re.sub(pattern, "", manifest_buf) - # Now see if any other assemblies are referenced - if not, we - # don't want a manifest embedded. - pattern = re.compile( - r"""|)""", - re.DOTALL, - ) - if re.search(pattern, manifest_buf) is None: - return None - - manifest_f = open(manifest_file, 'w') - try: - manifest_f.write(manifest_buf) - return manifest_file - finally: - manifest_f.close() - except OSError: - pass - - # -- Miscellaneous methods ----------------------------------------- - # These are all used by the 'gen_lib_options() function, in - # ccompiler.py. - - def library_dir_option(self, dir): - return "/LIBPATH:" + dir - - def runtime_library_dir_option(self, dir): - raise DistutilsPlatformError( - "don't know how to set runtime library search path for MSVC++" - ) - - def library_option(self, lib): - return self.library_filename(lib) - - def find_library_file(self, dirs, lib, debug=0): - # Prefer a debugging library if found (and requested), but deal - # with it if we don't have one. - if debug: - try_names = [lib + "_d", lib] - else: - try_names = [lib] - for dir in dirs: - for name in try_names: - libfile = os.path.join(dir, self.library_filename(name)) - if os.path.exists(libfile): - return libfile - else: - # Oops, didn't find it in *any* of 'dirs' - return None - - # Helper methods for using the MSVC registry settings - - def find_exe(self, exe): - """Return path to an MSVC executable program. - - Tries to find the program in several places: first, one of the - MSVC program search paths from the registry; next, the directories - in the PATH environment variable. If any of those work, return an - absolute path that is known to exist. If none of them work, just - return the original program name, 'exe'. - """ - for p in self.__paths: - fn = os.path.join(os.path.abspath(p), exe) - if os.path.isfile(fn): - return fn - - # didn't find it; try existing path - for p in os.environ['Path'].split(';'): - fn = os.path.join(os.path.abspath(p), exe) - if os.path.isfile(fn): - return fn - - return exe diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.py deleted file mode 100644 index cf0954e1a30546d781bf25781ec716ef92a77e32..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.py +++ /dev/null @@ -1,30 +0,0 @@ -import collections - - -# from jaraco.collections 3.3 -class FreezableDefaultDict(collections.defaultdict): - """ - Often it is desirable to prevent the mutation of - a default dict after its initial construction, such - as to prevent mutation during iteration. - - >>> dd = FreezableDefaultDict(list) - >>> dd[0].append('1') - >>> dd.freeze() - >>> dd[1] - [] - >>> len(dd) - 1 - """ - - def __missing__(self, key): - return getattr(self, '_frozen', super().__missing__)(key) - - def freeze(self): - self._frozen = lambda key: self.default_factory() - - -class Pair(collections.namedtuple('Pair', 'name value')): - @classmethod - def parse(cls, text): - return cls(*map(str.strip, text.split("=", 1))) diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/version.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/version.py deleted file mode 100644 index 95e1869658566aac3060562d8cd5a6b647887d1e..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/version.py +++ /dev/null @@ -1,6 +0,0 @@ -import pkg_resources - -try: - __version__ = pkg_resources.get_distribution('setuptools').version -except Exception: - __version__ = 'unknown' diff --git a/spaces/Audio-AGI/WavJourney/utils.py b/spaces/Audio-AGI/WavJourney/utils.py deleted file mode 100644 index 8d0d9d31fe740b4a0c958ee6e709e0bdac9e3023..0000000000000000000000000000000000000000 --- a/spaces/Audio-AGI/WavJourney/utils.py +++ /dev/null @@ -1,82 +0,0 @@ -import os -import re -import torch -import numpy as np -import yaml -from pathlib import Path - - -#### path related code BEGIN #### -def get_session_path(session_id): - return Path(f'output/sessions/{session_id}') - -def get_system_voice_preset_path(): - return Path('data/voice_presets') - -def get_session_voice_preset_path(session_id): - return Path(f'{get_session_path(session_id)}/voice_presets') - -def get_session_audio_path(session_id): - return Path(f'{get_session_path(session_id)}/audio') - -def rescale_to_match_energy(segment1, segment2): - ratio = get_energy_ratio(segment1, segment2) - recaled_segment1 = segment1 / ratio - return recaled_segment1.numpy() -#### path related code END #### - -def text_to_abbrev_prompt(input_text): - return re.sub(r'[^a-zA-Z_]', '', '_'.join(input_text.split()[:5])) - -def get_energy(x): - return np.mean(x ** 2) - - -def get_energy_ratio(segment1, segment2): - energy1 = get_energy(segment1) - energy2 = max(get_energy(segment2), 1e-10) - ratio = (energy1 / energy2) ** 0.5 - ratio = torch.tensor(ratio) - ratio = torch.clamp(ratio, 0.02, 50) - return ratio - -def fade(audio_data, fade_duration=2, sr=32000): - audio_duration = audio_data.shape[0] / sr - - # automated choose fade duration - if audio_duration >=8: - # keep fade_duration 2 - pass - else: - fade_duration = audio_duration / 5 - - fade_sampels = int(sr * fade_duration) - fade_in = np.linspace(0, 1, fade_sampels) - fade_out = np.linspace(1, 0, fade_sampels) - - audio_data_fade_in = audio_data[:fade_sampels] * fade_in - audio_data_fade_out = audio_data[-fade_sampels:] * fade_out - - audio_data_faded = np.concatenate((audio_data_fade_in, audio_data[len(fade_in):-len(fade_out)], audio_data_fade_out)) - return audio_data_faded - -# def get_key(config='config.yaml'): -# with open('config.yaml', 'r') as file: -# config = yaml.safe_load(file) -# return config['OpenAI-Key'] if 'OpenAI-Key' in config else None - -def get_service_port(): - service_port = os.environ.get('WAVJOURNEY_SERVICE_PORT') - return service_port - -def get_service_url(): - service_url = os.environ.get('WAVJOURNEY_SERVICE_URL') - return service_url - -def get_api_key(): - api_key = os.environ.get('WAVJOURNEY_OPENAI_KEY') - return api_key - -def get_max_script_lines(): - max_lines = int(os.environ.get('WAVJOURNEY_MAX_SCRIPT_LINES', 999)) - return max_lines \ No newline at end of file diff --git a/spaces/Bart92/RVC_HF/mdx.py b/spaces/Bart92/RVC_HF/mdx.py deleted file mode 100644 index 4cc7c08b37bc371294f2f82b3382424a5455b7c2..0000000000000000000000000000000000000000 --- a/spaces/Bart92/RVC_HF/mdx.py +++ /dev/null @@ -1,228 +0,0 @@ -import torch -import onnxruntime as ort -from tqdm import tqdm -import warnings -import numpy as np -import hashlib -import queue -import threading - -warnings.filterwarnings("ignore") - -class MDX_Model: - def __init__(self, device, dim_f, dim_t, n_fft, hop=1024, stem_name=None, compensation=1.000): - self.dim_f = dim_f - self.dim_t = dim_t - self.dim_c = 4 - self.n_fft = n_fft - self.hop = hop - self.stem_name = stem_name - self.compensation = compensation - - 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) - - out_c = self.dim_c - - self.freq_pad = torch.zeros([1, out_c, self.n_bins-self.dim_f, self.dim_t]).to(device) - - 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,4,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,2,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,2,self.chunk_size]) - - -class MDX: - - DEFAULT_SR = 44100 - # Unit: seconds - DEFAULT_CHUNK_SIZE = 0 * DEFAULT_SR - DEFAULT_MARGIN_SIZE = 1 * DEFAULT_SR - - DEFAULT_PROCESSOR = 0 - - def __init__(self, model_path:str, params:MDX_Model, processor=DEFAULT_PROCESSOR): - - # Set the device and the provider (CPU or CUDA) - self.device = torch.device(f'cuda:{processor}') if processor >= 0 else torch.device('cpu') - self.provider = ['CUDAExecutionProvider'] if processor >= 0 else ['CPUExecutionProvider'] - - self.model = params - - # Load the ONNX model using ONNX Runtime - self.ort = ort.InferenceSession(model_path, providers=self.provider) - # Preload the model for faster performance - self.ort.run(None, {'input':torch.rand(1, 4, params.dim_f, params.dim_t).numpy()}) - self.process = lambda spec:self.ort.run(None, {'input': spec.cpu().numpy()})[0] - - self.prog = None - - @staticmethod - def get_hash(model_path): - try: - with open(model_path, 'rb') as f: - f.seek(- 10000 * 1024, 2) - model_hash = hashlib.md5(f.read()).hexdigest() - except: - model_hash = hashlib.md5(open(model_path,'rb').read()).hexdigest() - - return model_hash - - @staticmethod - def segment(wave, combine=True, chunk_size=DEFAULT_CHUNK_SIZE, margin_size=DEFAULT_MARGIN_SIZE): - """ - Segment or join segmented wave array - - Args: - wave: (np.array) Wave array to be segmented or joined - combine: (bool) If True, combines segmented wave array. If False, segments wave array. - chunk_size: (int) Size of each segment (in samples) - margin_size: (int) Size of margin between segments (in samples) - - Returns: - numpy array: Segmented or joined wave array - """ - - if combine: - processed_wave = None # Initializing as None instead of [] for later numpy array concatenation - for segment_count, segment in enumerate(wave): - start = 0 if segment_count == 0 else margin_size - end = None if segment_count == len(wave)-1 else -margin_size - if margin_size == 0: - end = None - if processed_wave is None: # Create array for first segment - processed_wave = segment[:, start:end] - else: # Concatenate to existing array for subsequent segments - processed_wave = np.concatenate((processed_wave, segment[:, start:end]), axis=-1) - - else: - processed_wave = [] - sample_count = wave.shape[-1] - - if chunk_size <= 0 or chunk_size > sample_count: - chunk_size = sample_count - - if margin_size > chunk_size: - margin_size = chunk_size - - for segment_count, skip in enumerate(range(0, sample_count, chunk_size)): - - margin = 0 if segment_count == 0 else margin_size - end = min(skip+chunk_size+margin_size, sample_count) - start = skip-margin - - cut = wave[:,start:end].copy() - processed_wave.append(cut) - - if end == sample_count: - break - - return processed_wave - - def pad_wave(self, wave): - """ - Pad the wave array to match the required chunk size - - Args: - wave: (np.array) Wave array to be padded - - Returns: - tuple: (padded_wave, pad, trim) - - padded_wave: Padded wave array - - pad: Number of samples that were padded - - trim: Number of samples that were trimmed - """ - n_sample = wave.shape[1] - trim = self.model.n_fft//2 - gen_size = self.model.chunk_size-2*trim - pad = gen_size - n_sample%gen_size - - # Padded wave - wave_p = np.concatenate((np.zeros((2,trim)), wave, np.zeros((2,pad)), np.zeros((2,trim))), 1) - - mix_waves = [] - for i in range(0, n_sample+pad, gen_size): - waves = np.array(wave_p[:, i:i+self.model.chunk_size]) - mix_waves.append(waves) - - mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(self.device) - - return mix_waves, pad, trim - - def _process_wave(self, mix_waves, trim, pad, q:queue.Queue, _id:int): - """ - Process each wave segment in a multi-threaded environment - - Args: - mix_waves: (torch.Tensor) Wave segments to be processed - trim: (int) Number of samples trimmed during padding - pad: (int) Number of samples padded during padding - q: (queue.Queue) Queue to hold the processed wave segments - _id: (int) Identifier of the processed wave segment - - Returns: - numpy array: Processed wave segment - """ - mix_waves = mix_waves.split(1) - with torch.no_grad(): - pw = [] - for mix_wave in mix_waves: - self.prog.update() - spec = self.model.stft(mix_wave) - processed_spec = torch.tensor(self.process(spec)) - processed_wav = self.model.istft(processed_spec.to(self.device)) - processed_wav = processed_wav[:,:,trim:-trim].transpose(0,1).reshape(2, -1).cpu().numpy() - pw.append(processed_wav) - processed_signal = np.concatenate(pw, axis=-1)[:, :-pad] - q.put({_id:processed_signal}) - return processed_signal - - def process_wave(self, wave:np.array, mt_threads=1): - """ - Process the wave array in a multi-threaded environment - - Args: - wave: (np.array) Wave array to be processed - mt_threads: (int) Number of threads to be used for processing - - Returns: - numpy array: Processed wave array - """ - self.prog = tqdm(total=0) - chunk = wave.shape[-1]//mt_threads - waves = self.segment(wave, False, chunk) - - # Create a queue to hold the processed wave segments - q = queue.Queue() - threads = [] - for c, batch in enumerate(waves): - mix_waves, pad, trim = self.pad_wave(batch) - self.prog.total = len(mix_waves)*mt_threads - thread = threading.Thread(target=self._process_wave, args=(mix_waves, trim, pad, q, c)) - thread.start() - threads.append(thread) - for thread in threads: - thread.join() - self.prog.close() - - processed_batches = [] - while not q.empty(): - processed_batches.append(q.get()) - processed_batches = [list(wave.values())[0] for wave in sorted(processed_batches, key=lambda d: list(d.keys())[0])] - assert len(processed_batches) == len(waves), 'Incomplete processed batches, please reduce batch size!' - return self.segment(processed_batches, True, chunk) \ No newline at end of file diff --git a/spaces/Beasto/Day_to_Night_Cyclegan/README.md b/spaces/Beasto/Day_to_Night_Cyclegan/README.md deleted file mode 100644 index b1bff378fb748b63646d93cf8b68e6e09ffca79c..0000000000000000000000000000000000000000 --- a/spaces/Beasto/Day_to_Night_Cyclegan/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Day To Night Cyclegan -emoji: 🏢 -colorFrom: gray -colorTo: pink -sdk: streamlit -sdk_version: 1.27.2 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/BetterAPI/BetterChat/src/lib/updateSettings.ts b/spaces/BetterAPI/BetterChat/src/lib/updateSettings.ts deleted file mode 100644 index d8cc90839ef3efbd7e54abf31ecfca1a48aab1a9..0000000000000000000000000000000000000000 --- a/spaces/BetterAPI/BetterChat/src/lib/updateSettings.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { invalidate } from "$app/navigation"; -import { base } from "$app/paths"; -import { error } from "$lib/stores/errors"; -import type { Settings } from "./types/Settings"; -import { UrlDependency } from "./types/UrlDependency"; - -export async function updateSettings( - settings: Partial> -): Promise { - try { - const res = await fetch(`${base}/settings`, { - method: "PATCH", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(settings), - }); - if (!res.ok) { - error.set("Error while updating settings, try again."); - return false; - } - await invalidate(UrlDependency.Settings); - return true; - } catch (err) { - console.error(err); - error.set(String(err)); - return false; - } -} diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/utils/temp_dir.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/utils/temp_dir.py deleted file mode 100644 index 8ee8a1cb18017880cd0bebd66bc2cec5702118c6..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/utils/temp_dir.py +++ /dev/null @@ -1,246 +0,0 @@ -import errno -import itertools -import logging -import os.path -import tempfile -from contextlib import ExitStack, contextmanager -from typing import Any, Dict, Generator, Optional, TypeVar, Union - -from pip._internal.utils.misc import enum, rmtree - -logger = logging.getLogger(__name__) - -_T = TypeVar("_T", bound="TempDirectory") - - -# Kinds of temporary directories. Only needed for ones that are -# globally-managed. -tempdir_kinds = enum( - BUILD_ENV="build-env", - EPHEM_WHEEL_CACHE="ephem-wheel-cache", - REQ_BUILD="req-build", -) - - -_tempdir_manager: Optional[ExitStack] = None - - -@contextmanager -def global_tempdir_manager() -> Generator[None, None, None]: - global _tempdir_manager - with ExitStack() as stack: - old_tempdir_manager, _tempdir_manager = _tempdir_manager, stack - try: - yield - finally: - _tempdir_manager = old_tempdir_manager - - -class TempDirectoryTypeRegistry: - """Manages temp directory behavior""" - - def __init__(self) -> None: - self._should_delete: Dict[str, bool] = {} - - def set_delete(self, kind: str, value: bool) -> None: - """Indicate whether a TempDirectory of the given kind should be - auto-deleted. - """ - self._should_delete[kind] = value - - def get_delete(self, kind: str) -> bool: - """Get configured auto-delete flag for a given TempDirectory type, - default True. - """ - return self._should_delete.get(kind, True) - - -_tempdir_registry: Optional[TempDirectoryTypeRegistry] = None - - -@contextmanager -def tempdir_registry() -> Generator[TempDirectoryTypeRegistry, None, None]: - """Provides a scoped global tempdir registry that can be used to dictate - whether directories should be deleted. - """ - global _tempdir_registry - old_tempdir_registry = _tempdir_registry - _tempdir_registry = TempDirectoryTypeRegistry() - try: - yield _tempdir_registry - finally: - _tempdir_registry = old_tempdir_registry - - -class _Default: - pass - - -_default = _Default() - - -class TempDirectory: - """Helper class that owns and cleans up a temporary directory. - - This class can be used as a context manager or as an OO representation of a - temporary directory. - - Attributes: - path - Location to the created temporary directory - delete - Whether the directory should be deleted when exiting - (when used as a contextmanager) - - Methods: - cleanup() - Deletes the temporary directory - - When used as a context manager, if the delete attribute is True, on - exiting the context the temporary directory is deleted. - """ - - def __init__( - self, - path: Optional[str] = None, - delete: Union[bool, None, _Default] = _default, - kind: str = "temp", - globally_managed: bool = False, - ): - super().__init__() - - if delete is _default: - if path is not None: - # If we were given an explicit directory, resolve delete option - # now. - delete = False - else: - # Otherwise, we wait until cleanup and see what - # tempdir_registry says. - delete = None - - # The only time we specify path is in for editables where it - # is the value of the --src option. - if path is None: - path = self._create(kind) - - self._path = path - self._deleted = False - self.delete = delete - self.kind = kind - - if globally_managed: - assert _tempdir_manager is not None - _tempdir_manager.enter_context(self) - - @property - def path(self) -> str: - assert not self._deleted, f"Attempted to access deleted path: {self._path}" - return self._path - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} {self.path!r}>" - - def __enter__(self: _T) -> _T: - return self - - def __exit__(self, exc: Any, value: Any, tb: Any) -> None: - if self.delete is not None: - delete = self.delete - elif _tempdir_registry: - delete = _tempdir_registry.get_delete(self.kind) - else: - delete = True - - if delete: - self.cleanup() - - def _create(self, kind: str) -> str: - """Create a temporary directory and store its path in self.path""" - # We realpath here because some systems have their default tmpdir - # symlinked to another directory. This tends to confuse build - # scripts, so we canonicalize the path by traversing potential - # symlinks here. - path = os.path.realpath(tempfile.mkdtemp(prefix=f"pip-{kind}-")) - logger.debug("Created temporary directory: %s", path) - return path - - def cleanup(self) -> None: - """Remove the temporary directory created and reset state""" - self._deleted = True - if not os.path.exists(self._path): - return - rmtree(self._path) - - -class AdjacentTempDirectory(TempDirectory): - """Helper class that creates a temporary directory adjacent to a real one. - - Attributes: - original - The original directory to create a temp directory for. - path - After calling create() or entering, contains the full - path to the temporary directory. - delete - Whether the directory should be deleted when exiting - (when used as a contextmanager) - - """ - - # The characters that may be used to name the temp directory - # We always prepend a ~ and then rotate through these until - # a usable name is found. - # pkg_resources raises a different error for .dist-info folder - # with leading '-' and invalid metadata - LEADING_CHARS = "-~.=%0123456789" - - def __init__(self, original: str, delete: Optional[bool] = None) -> None: - self.original = original.rstrip("/\\") - super().__init__(delete=delete) - - @classmethod - def _generate_names(cls, name: str) -> Generator[str, None, None]: - """Generates a series of temporary names. - - The algorithm replaces the leading characters in the name - with ones that are valid filesystem characters, but are not - valid package names (for both Python and pip definitions of - package). - """ - for i in range(1, len(name)): - for candidate in itertools.combinations_with_replacement( - cls.LEADING_CHARS, i - 1 - ): - new_name = "~" + "".join(candidate) + name[i:] - if new_name != name: - yield new_name - - # If we make it this far, we will have to make a longer name - for i in range(len(cls.LEADING_CHARS)): - for candidate in itertools.combinations_with_replacement( - cls.LEADING_CHARS, i - ): - new_name = "~" + "".join(candidate) + name - if new_name != name: - yield new_name - - def _create(self, kind: str) -> str: - root, name = os.path.split(self.original) - for candidate in self._generate_names(name): - path = os.path.join(root, candidate) - try: - os.mkdir(path) - except OSError as ex: - # Continue if the name exists already - if ex.errno != errno.EEXIST: - raise - else: - path = os.path.realpath(path) - break - else: - # Final fallback on the default behavior. - path = os.path.realpath(tempfile.mkdtemp(prefix=f"pip-{kind}-")) - - logger.debug("Created temporary directory: %s", path) - return path diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/s3transfer/download.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/s3transfer/download.py deleted file mode 100644 index dc8980d4ed12b797a9f344c56fb7b94e2b15dd12..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/s3transfer/download.py +++ /dev/null @@ -1,790 +0,0 @@ -# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of -# the License is located at -# -# http://aws.amazon.com/apache2.0/ -# -# or in the "license" file accompanying this file. This file 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 heapq -import logging -import threading - -from s3transfer.compat import seekable -from s3transfer.exceptions import RetriesExceededError -from s3transfer.futures import IN_MEMORY_DOWNLOAD_TAG -from s3transfer.tasks import SubmissionTask, Task -from s3transfer.utils import ( - S3_RETRYABLE_DOWNLOAD_ERRORS, - CountCallbackInvoker, - DeferredOpenFile, - FunctionContainer, - StreamReaderProgress, - calculate_num_parts, - calculate_range_parameter, - get_callbacks, - invoke_progress_callbacks, -) - -logger = logging.getLogger(__name__) - - -class DownloadOutputManager: - """Base manager class for handling various types of files for downloads - - This class is typically used for the DownloadSubmissionTask class to help - determine the following: - - * Provides the fileobj to write to downloads to - * Get a task to complete once everything downloaded has been written - - The answers/implementations differ for the various types of file outputs - that may be accepted. All implementations must subclass and override - public methods from this class. - """ - - def __init__(self, osutil, transfer_coordinator, io_executor): - self._osutil = osutil - self._transfer_coordinator = transfer_coordinator - self._io_executor = io_executor - - @classmethod - def is_compatible(cls, download_target, osutil): - """Determines if the target for the download is compatible with manager - - :param download_target: The target for which the upload will write - data to. - - :param osutil: The os utility to be used for the transfer - - :returns: True if the manager can handle the type of target specified - otherwise returns False. - """ - raise NotImplementedError('must implement is_compatible()') - - def get_download_task_tag(self): - """Get the tag (if any) to associate all GetObjectTasks - - :rtype: s3transfer.futures.TaskTag - :returns: The tag to associate all GetObjectTasks with - """ - return None - - def get_fileobj_for_io_writes(self, transfer_future): - """Get file-like object to use for io writes in the io executor - - :type transfer_future: s3transfer.futures.TransferFuture - :param transfer_future: The future associated with upload request - - returns: A file-like object to write to - """ - raise NotImplementedError('must implement get_fileobj_for_io_writes()') - - def queue_file_io_task(self, fileobj, data, offset): - """Queue IO write for submission to the IO executor. - - This method accepts an IO executor and information about the - downloaded data, and handles submitting this to the IO executor. - - This method may defer submission to the IO executor if necessary. - - """ - self._transfer_coordinator.submit( - self._io_executor, self.get_io_write_task(fileobj, data, offset) - ) - - def get_io_write_task(self, fileobj, data, offset): - """Get an IO write task for the requested set of data - - This task can be ran immediately or be submitted to the IO executor - for it to run. - - :type fileobj: file-like object - :param fileobj: The file-like object to write to - - :type data: bytes - :param data: The data to write out - - :type offset: integer - :param offset: The offset to write the data to in the file-like object - - :returns: An IO task to be used to write data to a file-like object - """ - return IOWriteTask( - self._transfer_coordinator, - main_kwargs={ - 'fileobj': fileobj, - 'data': data, - 'offset': offset, - }, - ) - - def get_final_io_task(self): - """Get the final io task to complete the download - - This is needed because based on the architecture of the TransferManager - the final tasks will be sent to the IO executor, but the executor - needs a final task for it to signal that the transfer is done and - all done callbacks can be run. - - :rtype: s3transfer.tasks.Task - :returns: A final task to completed in the io executor - """ - raise NotImplementedError('must implement get_final_io_task()') - - def _get_fileobj_from_filename(self, filename): - f = DeferredOpenFile( - filename, mode='wb', open_function=self._osutil.open - ) - # Make sure the file gets closed and we remove the temporary file - # if anything goes wrong during the process. - self._transfer_coordinator.add_failure_cleanup(f.close) - return f - - -class DownloadFilenameOutputManager(DownloadOutputManager): - def __init__(self, osutil, transfer_coordinator, io_executor): - super().__init__(osutil, transfer_coordinator, io_executor) - self._final_filename = None - self._temp_filename = None - self._temp_fileobj = None - - @classmethod - def is_compatible(cls, download_target, osutil): - return isinstance(download_target, str) - - def get_fileobj_for_io_writes(self, transfer_future): - fileobj = transfer_future.meta.call_args.fileobj - self._final_filename = fileobj - self._temp_filename = self._osutil.get_temp_filename(fileobj) - self._temp_fileobj = self._get_temp_fileobj() - return self._temp_fileobj - - def get_final_io_task(self): - # A task to rename the file from the temporary file to its final - # location is needed. This should be the last task needed to complete - # the download. - return IORenameFileTask( - transfer_coordinator=self._transfer_coordinator, - main_kwargs={ - 'fileobj': self._temp_fileobj, - 'final_filename': self._final_filename, - 'osutil': self._osutil, - }, - is_final=True, - ) - - def _get_temp_fileobj(self): - f = self._get_fileobj_from_filename(self._temp_filename) - self._transfer_coordinator.add_failure_cleanup( - self._osutil.remove_file, self._temp_filename - ) - return f - - -class DownloadSeekableOutputManager(DownloadOutputManager): - @classmethod - def is_compatible(cls, download_target, osutil): - return seekable(download_target) - - def get_fileobj_for_io_writes(self, transfer_future): - # Return the fileobj provided to the future. - return transfer_future.meta.call_args.fileobj - - def get_final_io_task(self): - # This task will serve the purpose of signaling when all of the io - # writes have finished so done callbacks can be called. - return CompleteDownloadNOOPTask( - transfer_coordinator=self._transfer_coordinator - ) - - -class DownloadNonSeekableOutputManager(DownloadOutputManager): - def __init__( - self, osutil, transfer_coordinator, io_executor, defer_queue=None - ): - super().__init__(osutil, transfer_coordinator, io_executor) - if defer_queue is None: - defer_queue = DeferQueue() - self._defer_queue = defer_queue - self._io_submit_lock = threading.Lock() - - @classmethod - def is_compatible(cls, download_target, osutil): - return hasattr(download_target, 'write') - - def get_download_task_tag(self): - return IN_MEMORY_DOWNLOAD_TAG - - def get_fileobj_for_io_writes(self, transfer_future): - return transfer_future.meta.call_args.fileobj - - def get_final_io_task(self): - return CompleteDownloadNOOPTask( - transfer_coordinator=self._transfer_coordinator - ) - - def queue_file_io_task(self, fileobj, data, offset): - with self._io_submit_lock: - writes = self._defer_queue.request_writes(offset, data) - for write in writes: - data = write['data'] - logger.debug( - "Queueing IO offset %s for fileobj: %s", - write['offset'], - fileobj, - ) - super().queue_file_io_task(fileobj, data, offset) - - def get_io_write_task(self, fileobj, data, offset): - return IOStreamingWriteTask( - self._transfer_coordinator, - main_kwargs={ - 'fileobj': fileobj, - 'data': data, - }, - ) - - -class DownloadSpecialFilenameOutputManager(DownloadNonSeekableOutputManager): - def __init__( - self, osutil, transfer_coordinator, io_executor, defer_queue=None - ): - super().__init__( - osutil, transfer_coordinator, io_executor, defer_queue - ) - self._fileobj = None - - @classmethod - def is_compatible(cls, download_target, osutil): - return isinstance(download_target, str) and osutil.is_special_file( - download_target - ) - - def get_fileobj_for_io_writes(self, transfer_future): - filename = transfer_future.meta.call_args.fileobj - self._fileobj = self._get_fileobj_from_filename(filename) - return self._fileobj - - def get_final_io_task(self): - # Make sure the file gets closed once the transfer is done. - return IOCloseTask( - transfer_coordinator=self._transfer_coordinator, - is_final=True, - main_kwargs={'fileobj': self._fileobj}, - ) - - -class DownloadSubmissionTask(SubmissionTask): - """Task for submitting tasks to execute a download""" - - def _get_download_output_manager_cls(self, transfer_future, osutil): - """Retrieves a class for managing output for a download - - :type transfer_future: s3transfer.futures.TransferFuture - :param transfer_future: The transfer future for the request - - :type osutil: s3transfer.utils.OSUtils - :param osutil: The os utility associated to the transfer - - :rtype: class of DownloadOutputManager - :returns: The appropriate class to use for managing a specific type of - input for downloads. - """ - download_manager_resolver_chain = [ - DownloadSpecialFilenameOutputManager, - DownloadFilenameOutputManager, - DownloadSeekableOutputManager, - DownloadNonSeekableOutputManager, - ] - - fileobj = transfer_future.meta.call_args.fileobj - for download_manager_cls in download_manager_resolver_chain: - if download_manager_cls.is_compatible(fileobj, osutil): - return download_manager_cls - raise RuntimeError( - 'Output {} of type: {} is not supported.'.format( - fileobj, type(fileobj) - ) - ) - - def _submit( - self, - client, - config, - osutil, - request_executor, - io_executor, - transfer_future, - bandwidth_limiter=None, - ): - """ - :param client: The client associated with the transfer manager - - :type config: s3transfer.manager.TransferConfig - :param config: The transfer config associated with the transfer - manager - - :type osutil: s3transfer.utils.OSUtil - :param osutil: The os utility associated to the transfer manager - - :type request_executor: s3transfer.futures.BoundedExecutor - :param request_executor: The request executor associated with the - transfer manager - - :type io_executor: s3transfer.futures.BoundedExecutor - :param io_executor: The io executor associated with the - transfer manager - - :type transfer_future: s3transfer.futures.TransferFuture - :param transfer_future: The transfer future associated with the - transfer request that tasks are being submitted for - - :type bandwidth_limiter: s3transfer.bandwidth.BandwidthLimiter - :param bandwidth_limiter: The bandwidth limiter to use when - downloading streams - """ - if transfer_future.meta.size is None: - # If a size was not provided figure out the size for the - # user. - response = client.head_object( - Bucket=transfer_future.meta.call_args.bucket, - Key=transfer_future.meta.call_args.key, - **transfer_future.meta.call_args.extra_args, - ) - transfer_future.meta.provide_transfer_size( - response['ContentLength'] - ) - - download_output_manager = self._get_download_output_manager_cls( - transfer_future, osutil - )(osutil, self._transfer_coordinator, io_executor) - - # If it is greater than threshold do a ranged download, otherwise - # do a regular GetObject download. - if transfer_future.meta.size < config.multipart_threshold: - self._submit_download_request( - client, - config, - osutil, - request_executor, - io_executor, - download_output_manager, - transfer_future, - bandwidth_limiter, - ) - else: - self._submit_ranged_download_request( - client, - config, - osutil, - request_executor, - io_executor, - download_output_manager, - transfer_future, - bandwidth_limiter, - ) - - def _submit_download_request( - self, - client, - config, - osutil, - request_executor, - io_executor, - download_output_manager, - transfer_future, - bandwidth_limiter, - ): - call_args = transfer_future.meta.call_args - - # Get a handle to the file that will be used for writing downloaded - # contents - fileobj = download_output_manager.get_fileobj_for_io_writes( - transfer_future - ) - - # Get the needed callbacks for the task - progress_callbacks = get_callbacks(transfer_future, 'progress') - - # Get any associated tags for the get object task. - get_object_tag = download_output_manager.get_download_task_tag() - - # Get the final io task to run once the download is complete. - final_task = download_output_manager.get_final_io_task() - - # Submit the task to download the object. - self._transfer_coordinator.submit( - request_executor, - ImmediatelyWriteIOGetObjectTask( - transfer_coordinator=self._transfer_coordinator, - main_kwargs={ - 'client': client, - 'bucket': call_args.bucket, - 'key': call_args.key, - 'fileobj': fileobj, - 'extra_args': call_args.extra_args, - 'callbacks': progress_callbacks, - 'max_attempts': config.num_download_attempts, - 'download_output_manager': download_output_manager, - 'io_chunksize': config.io_chunksize, - 'bandwidth_limiter': bandwidth_limiter, - }, - done_callbacks=[final_task], - ), - tag=get_object_tag, - ) - - def _submit_ranged_download_request( - self, - client, - config, - osutil, - request_executor, - io_executor, - download_output_manager, - transfer_future, - bandwidth_limiter, - ): - call_args = transfer_future.meta.call_args - - # Get the needed progress callbacks for the task - progress_callbacks = get_callbacks(transfer_future, 'progress') - - # Get a handle to the file that will be used for writing downloaded - # contents - fileobj = download_output_manager.get_fileobj_for_io_writes( - transfer_future - ) - - # Determine the number of parts - part_size = config.multipart_chunksize - num_parts = calculate_num_parts(transfer_future.meta.size, part_size) - - # Get any associated tags for the get object task. - get_object_tag = download_output_manager.get_download_task_tag() - - # Callback invoker to submit the final io task once all downloads - # are complete. - finalize_download_invoker = CountCallbackInvoker( - self._get_final_io_task_submission_callback( - download_output_manager, io_executor - ) - ) - for i in range(num_parts): - # Calculate the range parameter - range_parameter = calculate_range_parameter( - part_size, i, num_parts - ) - - # Inject the Range parameter to the parameters to be passed in - # as extra args - extra_args = {'Range': range_parameter} - extra_args.update(call_args.extra_args) - finalize_download_invoker.increment() - # Submit the ranged downloads - self._transfer_coordinator.submit( - request_executor, - GetObjectTask( - transfer_coordinator=self._transfer_coordinator, - main_kwargs={ - 'client': client, - 'bucket': call_args.bucket, - 'key': call_args.key, - 'fileobj': fileobj, - 'extra_args': extra_args, - 'callbacks': progress_callbacks, - 'max_attempts': config.num_download_attempts, - 'start_index': i * part_size, - 'download_output_manager': download_output_manager, - 'io_chunksize': config.io_chunksize, - 'bandwidth_limiter': bandwidth_limiter, - }, - done_callbacks=[finalize_download_invoker.decrement], - ), - tag=get_object_tag, - ) - finalize_download_invoker.finalize() - - def _get_final_io_task_submission_callback( - self, download_manager, io_executor - ): - final_task = download_manager.get_final_io_task() - return FunctionContainer( - self._transfer_coordinator.submit, io_executor, final_task - ) - - def _calculate_range_param(self, part_size, part_index, num_parts): - # Used to calculate the Range parameter - start_range = part_index * part_size - if part_index == num_parts - 1: - end_range = '' - else: - end_range = start_range + part_size - 1 - range_param = f'bytes={start_range}-{end_range}' - return range_param - - -class GetObjectTask(Task): - def _main( - self, - client, - bucket, - key, - fileobj, - extra_args, - callbacks, - max_attempts, - download_output_manager, - io_chunksize, - start_index=0, - bandwidth_limiter=None, - ): - """Downloads an object and places content into io queue - - :param client: The client to use when calling GetObject - :param bucket: The bucket to download from - :param key: The key to download from - :param fileobj: The file handle to write content to - :param exta_args: Any extra arguments to include in GetObject request - :param callbacks: List of progress callbacks to invoke on download - :param max_attempts: The number of retries to do when downloading - :param download_output_manager: The download output manager associated - with the current download. - :param io_chunksize: The size of each io chunk to read from the - download stream and queue in the io queue. - :param start_index: The location in the file to start writing the - content of the key to. - :param bandwidth_limiter: The bandwidth limiter to use when throttling - the downloading of data in streams. - """ - last_exception = None - for i in range(max_attempts): - try: - current_index = start_index - response = client.get_object( - Bucket=bucket, Key=key, **extra_args - ) - streaming_body = StreamReaderProgress( - response['Body'], callbacks - ) - if bandwidth_limiter: - streaming_body = ( - bandwidth_limiter.get_bandwith_limited_stream( - streaming_body, self._transfer_coordinator - ) - ) - - chunks = DownloadChunkIterator(streaming_body, io_chunksize) - for chunk in chunks: - # If the transfer is done because of a cancellation - # or error somewhere else, stop trying to submit more - # data to be written and break out of the download. - if not self._transfer_coordinator.done(): - self._handle_io( - download_output_manager, - fileobj, - chunk, - current_index, - ) - current_index += len(chunk) - else: - return - return - except S3_RETRYABLE_DOWNLOAD_ERRORS as e: - logger.debug( - "Retrying exception caught (%s), " - "retrying request, (attempt %s / %s)", - e, - i, - max_attempts, - exc_info=True, - ) - last_exception = e - # Also invoke the progress callbacks to indicate that we - # are trying to download the stream again and all progress - # for this GetObject has been lost. - invoke_progress_callbacks( - callbacks, start_index - current_index - ) - continue - raise RetriesExceededError(last_exception) - - def _handle_io(self, download_output_manager, fileobj, chunk, index): - download_output_manager.queue_file_io_task(fileobj, chunk, index) - - -class ImmediatelyWriteIOGetObjectTask(GetObjectTask): - """GetObjectTask that immediately writes to the provided file object - - This is useful for downloads where it is known only one thread is - downloading the object so there is no reason to go through the - overhead of using an IO queue and executor. - """ - - def _handle_io(self, download_output_manager, fileobj, chunk, index): - task = download_output_manager.get_io_write_task(fileobj, chunk, index) - task() - - -class IOWriteTask(Task): - def _main(self, fileobj, data, offset): - """Pulls off an io queue to write contents to a file - - :param fileobj: The file handle to write content to - :param data: The data to write - :param offset: The offset to write the data to. - """ - fileobj.seek(offset) - fileobj.write(data) - - -class IOStreamingWriteTask(Task): - """Task for writing data to a non-seekable stream.""" - - def _main(self, fileobj, data): - """Write data to a fileobj. - - Data will be written directly to the fileobj without - any prior seeking. - - :param fileobj: The fileobj to write content to - :param data: The data to write - - """ - fileobj.write(data) - - -class IORenameFileTask(Task): - """A task to rename a temporary file to its final filename - - :param fileobj: The file handle that content was written to. - :param final_filename: The final name of the file to rename to - upon completion of writing the contents. - :param osutil: OS utility - """ - - def _main(self, fileobj, final_filename, osutil): - fileobj.close() - osutil.rename_file(fileobj.name, final_filename) - - -class IOCloseTask(Task): - """A task to close out a file once the download is complete. - - :param fileobj: The fileobj to close. - """ - - def _main(self, fileobj): - fileobj.close() - - -class CompleteDownloadNOOPTask(Task): - """A NOOP task to serve as an indicator that the download is complete - - Note that the default for is_final is set to True because this should - always be the last task. - """ - - def __init__( - self, - transfer_coordinator, - main_kwargs=None, - pending_main_kwargs=None, - done_callbacks=None, - is_final=True, - ): - super().__init__( - transfer_coordinator=transfer_coordinator, - main_kwargs=main_kwargs, - pending_main_kwargs=pending_main_kwargs, - done_callbacks=done_callbacks, - is_final=is_final, - ) - - def _main(self): - pass - - -class DownloadChunkIterator: - def __init__(self, body, chunksize): - """Iterator to chunk out a downloaded S3 stream - - :param body: A readable file-like object - :param chunksize: The amount to read each time - """ - self._body = body - self._chunksize = chunksize - self._num_reads = 0 - - def __iter__(self): - return self - - def __next__(self): - chunk = self._body.read(self._chunksize) - self._num_reads += 1 - if chunk: - return chunk - elif self._num_reads == 1: - # Even though the response may have not had any - # content, we still want to account for an empty object's - # existence so return the empty chunk for that initial - # read. - return chunk - raise StopIteration() - - next = __next__ - - -class DeferQueue: - """IO queue that defers write requests until they are queued sequentially. - - This class is used to track IO data for a *single* fileobj. - - You can send data to this queue, and it will defer any IO write requests - until it has the next contiguous block available (starting at 0). - - """ - - def __init__(self): - self._writes = [] - self._pending_offsets = set() - self._next_offset = 0 - - def request_writes(self, offset, data): - """Request any available writes given new incoming data. - - You call this method by providing new data along with the - offset associated with the data. If that new data unlocks - any contiguous writes that can now be submitted, this - method will return all applicable writes. - - This is done with 1 method call so you don't have to - make two method calls (put(), get()) which acquires a lock - each method call. - - """ - if offset < self._next_offset: - # This is a request for a write that we've already - # seen. This can happen in the event of a retry - # where if we retry at at offset N/2, we'll requeue - # offsets 0-N/2 again. - return [] - writes = [] - if offset in self._pending_offsets: - # We've already queued this offset so this request is - # a duplicate. In this case we should ignore - # this request and prefer what's already queued. - return [] - heapq.heappush(self._writes, (offset, data)) - self._pending_offsets.add(offset) - while self._writes and self._writes[0][0] == self._next_offset: - next_write = heapq.heappop(self._writes) - writes.append({'offset': next_write[0], 'data': next_write[1]}) - self._pending_offsets.remove(next_write[0]) - self._next_offset += len(next_write[1]) - return writes diff --git a/spaces/CVPR/LIVE/thrust/thrust/detail/functional/argument.h b/spaces/CVPR/LIVE/thrust/thrust/detail/functional/argument.h deleted file mode 100644 index 0b7541716e5ddb6e15eb8c3bdb5f950dd7218677..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/detail/functional/argument.h +++ /dev/null @@ -1,75 +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. - */ - -// Portions of this code are derived from -// -// Manjunath Kudlur's Carbon library -// -// and -// -// Based on Boost.Phoenix v1.2 -// Copyright (c) 2001-2002 Joel de Guzman - -#pragma once - -#include -#include - -namespace thrust -{ -namespace detail -{ -namespace functional -{ - -template - struct argument_helper -{ - typedef typename thrust::tuple_element::type type; -}; - -template - struct argument_helper -{ - typedef thrust::null_type type; -}; - - -template - class argument -{ - public: - template - struct result - : argument_helper - { - }; - - __host__ __device__ - THRUST_CONSTEXPR argument(){} - - template - __host__ __device__ - typename result::type eval(const Env &e) const - { - return thrust::get(e); - } // end eval() -}; // end argument - -} // end functional -} // end detail -} // end thrust - diff --git a/spaces/CVPR/LIVE/thrust/thrust/memory.h b/spaces/CVPR/LIVE/thrust/thrust/memory.h deleted file mode 100644 index 9ef8833f57a0c00187732a93df515196a05a1491..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/memory.h +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*! \file thrust/memory.h - * \brief Abstractions for Thrust's memory model. - */ - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace thrust -{ - -/*! \defgroup memory_management Memory Management - * - * All Thrust functionalities related to memory allocation and deallocation. - * - */ - -/** \addtogroup memory_management_classes Memory Management Classes - * \ingroup memory_management - * \{ - */ - -// define pointer for the purpose of Doxygenating it -// it is actually defined elsewhere -#if 0 -/*! \p pointer stores a pointer to an object allocated in memory. Like \p device_ptr, this - * type ensures type safety when dispatching standard algorithms on ranges resident in memory. - * - * \p pointer generalizes \p device_ptr by relaxing the backend system associated with the \p pointer. - * Instead of the backend system specified by \p THRUST_DEFAULT_DEVICE_BACKEND, \p pointer's - * system is given by its second template parameter, \p Tag. For the purpose of Thrust dispatch, - * device_ptr and pointer are considered equivalent. - * - * The raw pointer encapsulated by a \p pointer may be obtained through its get member function - * or the \p raw_pointer_cast free function. - * - * \tparam Element specifies the type of the pointed-to object. - * - * \tparam Tag specifies the system with which this \p pointer is associated. This may be any Thrust - * backend system, or a user-defined tag. - * - * \tparam Reference allows the client to specify the reference type returned upon derereference. - * By default, this type is reference. - * - * \tparam Derived allows the client to specify the name of the derived type when \p pointer is used as - * a base class. This is useful to ensure that arithmetic on values of the derived type return - * values of the derived type as a result. By default, this type is pointer. - * - * \note \p pointer is not a smart pointer; it is the client's responsibility to deallocate memory - * pointer to by \p pointer. - * - * \see device_ptr - * \see reference - * \see raw_pointer_cast - */ -template - class pointer -{ - public: - /*! The type of the raw pointer - */ - typedef typename super_t::base_type raw_pointer; - - /*! \p pointer's default constructor initializes its encapsulated pointer to \c 0 - */ - __host__ __device__ - pointer(); - - /*! This constructor allows construction of a pointer from a T*. - * - * \param ptr A raw pointer to copy from, presumed to point to a location in \p Tag's memory. - * \tparam OtherElement \p OtherElement shall be convertible to \p Element. - */ - template - __host__ __device__ - explicit pointer(OtherElement *ptr); - - /*! This contructor allows initialization from another pointer-like object. - * - * \param other The \p OtherPointer to copy. - * - * \tparam OtherPointer The tag associated with \p OtherPointer shall be convertible to \p Tag, - * and its element type shall be convertible to \p Element. - */ - template - __host__ __device__ - pointer(const OtherPointer &other, - typename thrust::detail::enable_if_pointer_is_convertible< - OtherPointer, - pointer - >::type * = 0); - - /*! Assignment operator allows assigning from another pointer-like object with related type. - * - * \param other The other pointer-like object to assign from. - * \return *this - * - * \tparam OtherPointer The tag associated with \p OtherPointer shall be convertible to \p Tag, - * and its element type shall be convertible to \p Element. - */ - template - __host__ __device__ - typename thrust::detail::enable_if_pointer_is_convertible< - OtherPointer, - pointer, - derived_type & - >::type - operator=(const OtherPointer &other); - - /*! \p get returns this \p pointer's encapsulated raw pointer. - * \return This \p pointer's raw pointer. - */ - __host__ __device__ - Element *get() const; -}; -#endif - -// define pointer for the purpose of Doxygenating it -// it is actually defined elsewhere -#if 0 -/*! \p reference is a wrapped reference to an object stored in memory. \p reference generalizes - * \p device_reference by relaxing the type of pointer associated with the object. \p reference - * is the type of the result of dereferencing a tagged pointer-like object such as \p pointer, and - * intermediates operations on objects existing in a remote memory. - * - * \tparam Element specifies the type of the referent object. - * \tparam Pointer specifies the type of the result of taking the address of \p reference. - * \tparam Derived allows the client to specify the name of the derived type when \p reference is used as - * a base class. This is useful to ensure that assignment to objects of the derived type return - * values of the derived type as a result. By default, this type is reference. - */ -template - class reference -{ - public: - /*! The type of this \p reference's wrapped pointers. - */ - typedef Pointer pointer; - - /*! The \p value_type of this \p reference. - */ - typedef typename thrust::detail::remove_const::type value_type; - - /*! This copy constructor initializes this \p reference - * to refer to an object pointed to by the given \p pointer. After - * this \p reference is constructed, it shall refer to the - * object pointed to by \p ptr. - * - * \param ptr A \p pointer to copy from. - */ - __host__ __device__ - explicit reference(const pointer &ptr); - - /*! This copy constructor accepts a const reference to another - * \p reference of related type. After this \p reference is constructed, - * it shall refer to the same object as \p other. - * - * \param other A \p reference to copy from. - * \tparam OtherElement the element type of the other \p reference. - * \tparam OtherPointer the pointer type of the other \p reference. - * \tparam OtherDerived the derived type of the other \p reference. - * - * \note This constructor is templated primarily to allow initialization of - * reference from reference. - */ - template - __host__ __device__ - reference(const reference &other, - typename thrust::detail::enable_if_convertible< - typename reference::pointer, - pointer - >::type * = 0); - - /*! Copy assignment operator copy assigns from another \p reference. - * - * \param other The other \p reference to assign from. - * \return static_cast(*this) - */ - __host__ __device__ - derived_type &operator=(const reference &other); - - /*! Assignment operator copy assigns from another \p reference of related type. - * - * \param other The other \p reference to assign from. - * \return static_cast(*this) - * - * \tparam OtherElement the element type of the other \p reference. - * \tparam OtherPointer the pointer type of the other \p reference. - * \tparam OtherDerived the derived type of the other \p reference. - */ - template - __host__ __device__ - derived_type &operator=(const reference &other); - - /*! Assignment operator assigns from a \p value_type. - * - * \param x The \p value_type to assign from. - * \return static_cast(*this). - */ - __host__ __device__ - derived_type &operator=(const value_type &x); - - /*! Address-of operator returns a \p pointer pointing to the object - * referenced by this \p reference. It does not return the address of this - * \p reference. - * - * \return A \p pointer pointing to the referenct object. - */ - __host__ __device__ - pointer operator&() const; - - /*! Conversion operator converts this \p reference to \p value_type by - * returning a copy of the referent object. - * - * \return A copy of the referent object. - */ - __host__ __device__ - operator value_type () const; - - /*! Swaps the value of the referent object with another. - * - * \param other The other \p reference with which to swap. - * \note The argument is of type \p derived_type rather than \p reference. - */ - __host__ __device__ - void swap(derived_type &other); - - /*! Prefix increment operator increments the referent object. - * - * \return static_Cast(*this). - * - * \note Documentation for other arithmetic operators omitted for brevity. - */ - derived_type &operator++(); -}; -#endif - -/*! \} - */ - -/*! - * \addtogroup memory_management_functions Memory Management Functions - * \ingroup memory_management - * \{ - */ - - -/*! \addtogroup allocation_functions - * \{ - */ - - -/*! This version of \p malloc allocates untyped uninitialized storage associated with a given system. - * - * \param system The Thrust system with which to associate the storage. - * \param n The number of bytes of storage to allocate. - * \return If allocation succeeds, a pointer to the allocated storage; a null pointer otherwise. - * The pointer must be deallocated with \p thrust::free. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * - * \pre \p DerivedPolicy must be publically derived from thrust::execution_policy. - * - * The following code snippet demonstrates how to use \p malloc to allocate a range of memory - * associated with Thrust's device system. - * - * \code - * #include - * ... - * // allocate some memory with thrust::malloc - * const int N = 100; - * thrust::device_system_tag device_sys; - * thrust::pointer void_ptr = thrust::malloc(device_sys, N); - * - * // manipulate memory - * ... - * - * // deallocate void_ptr with thrust::free - * thrust::free(device_sys, void_ptr); - * \endcode - * - * \see free - * \see device_malloc - */ -template -__host__ __device__ -pointer malloc(const thrust::detail::execution_policy_base &system, std::size_t n); - - -/*! This version of \p malloc allocates typed uninitialized storage associated with a given system. - * - * \param system The Thrust system with which to associate the storage. - * \param n The number of elements of type \c T which the storage should accomodate. - * \return If allocation succeeds, a pointer to an allocation large enough to accomodate \c n - * elements of type \c T; a null pointer otherwise. - * The pointer must be deallocated with \p thrust::free. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * - * \pre \p DerivedPolicy must be publically derived from thrust::execution_policy. - * - * The following code snippet demonstrates how to use \p malloc to allocate a range of memory - * to accomodate integers associated with Thrust's device system. - * - * \code - * #include - * ... - * // allocate storage for 100 ints with thrust::malloc - * const int N = 100; - * thrust::device_system_tag device_sys; - * thrust::pointer ptr = thrust::malloc(device_sys, N); - * - * // manipulate memory - * ... - * - * // deallocate ptr with thrust::free - * thrust::free(device_sys, ptr); - * \endcode - * - * \see free - * \see device_malloc - */ -template -__host__ __device__ -pointer malloc(const thrust::detail::execution_policy_base &system, std::size_t n); - - -/*! \p get_temporary_buffer returns a pointer to storage associated with a given Thrust system sufficient to store up to - * \p n objects of type \c T. If not enough storage is available to accomodate \p n objects, an implementation may return - * a smaller buffer. The number of objects the returned buffer can accomodate is also returned. - * - * Thrust uses \p get_temporary_buffer internally when allocating temporary storage required by algorithm implementations. - * - * The storage allocated with \p get_temporary_buffer must be returned to the system with \p return_temporary_buffer. - * - * \param system The Thrust system with which to associate the storage. - * \param n The requested number of objects of type \c T the storage should accomodate. - * \return A pair \c p such that p.first is a pointer to the allocated storage and p.second is the number of - * contiguous objects of type \c T that the storage can accomodate. If no storage can be allocated, p.first if - * no storage can be obtained. The storage must be returned to the system using \p return_temporary_buffer. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * - * \pre \p DerivedPolicy must be publically derived from thrust::execution_policy. - * - * The following code snippet demonstrates how to use \p get_temporary_buffer to allocate a range of memory - * to accomodate integers associated with Thrust's device system. - * - * \code - * #include - * ... - * // allocate storage for 100 ints with thrust::get_temporary_buffer - * const int N = 100; - * - * typedef thrust::pair< - * thrust::pointer, - * std::ptrdiff_t - * > ptr_and_size_t; - * - * thrust::device_system_tag device_sys; - * ptr_and_size_t ptr_and_size = thrust::get_temporary_buffer(device_sys, N); - * - * // manipulate up to 100 ints - * for(int i = 0; i < ptr_and_size.second; ++i) - * { - * *ptr_and_size.first = i; - * } - * - * // deallocate storage with thrust::return_temporary_buffer - * thrust::return_temporary_buffer(device_sys, ptr_and_size.first); - * \endcode - * - * \see malloc - * \see return_temporary_buffer - */ -template -__host__ __device__ -thrust::pair, typename thrust::pointer::difference_type> -get_temporary_buffer(const thrust::detail::execution_policy_base &system, typename thrust::pointer::difference_type n); - - -/*! \} allocation_functions - */ - - -/*! \addtogroup deallocation_functions - * \{ - */ - - -/*! \p free deallocates the storage previously allocated by \p thrust::malloc. - * - * \param system The Thrust system with which the storage is associated. - * \param ptr A pointer previously returned by \p thrust::malloc. If \p ptr is null, \p free - * does nothing. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * - * \pre \p ptr shall have been returned by a previous call to thrust::malloc(system, n) or thrust::malloc(system, n) for some type \c T. - * - * The following code snippet demonstrates how to use \p free to deallocate a range of memory - * previously allocated with \p thrust::malloc. - * - * \code - * #include - * ... - * // allocate storage for 100 ints with thrust::malloc - * const int N = 100; - * thrust::device_system_tag device_sys; - * thrust::pointer ptr = thrust::malloc(device_sys, N); - * - * // mainpulate memory - * ... - * - * // deallocate ptr with thrust::free - * thrust::free(device_sys, ptr); - * \endcode - */ -template -__host__ __device__ -void free(const thrust::detail::execution_policy_base &system, Pointer ptr); - - -/*! \p return_temporary_buffer deallocates storage associated with a given Thrust system previously allocated by \p get_temporary_buffer. - * - * Thrust uses \p return_temporary_buffer internally when deallocating temporary storage required by algorithm implementations. - * - * \param system The Thrust system with which the storage is associated. - * \param p A pointer previously returned by \p thrust::get_temporary_buffer. If \p ptr is null, \p return_temporary_buffer does nothing. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * - * \pre \p p shall have been previously allocated by \p thrust::get_temporary_buffer. - * - * The following code snippet demonstrates how to use \p return_temporary_buffer to deallocate a range of memory - * previously allocated by \p get_temporary_buffer. - * - * \code - * #include - * ... - * // allocate storage for 100 ints with thrust::get_temporary_buffer - * const int N = 100; - * - * typedef thrust::pair< - * thrust::pointer, - * std::ptrdiff_t - * > ptr_and_size_t; - * - * thrust::device_system_tag device_sys; - * ptr_and_size_t ptr_and_size = thrust::get_temporary_buffer(device_sys, N); - * - * // manipulate up to 100 ints - * for(int i = 0; i < ptr_and_size.second; ++i) - * { - * *ptr_and_size.first = i; - * } - * - * // deallocate storage with thrust::return_temporary_buffer - * thrust::return_temporary_buffer(device_sys, ptr_and_size.first); - * \endcode - * - * \see free - * \see get_temporary_buffer - */ -template -__host__ __device__ -void return_temporary_buffer(const thrust::detail::execution_policy_base &system, Pointer p, std::ptrdiff_t n); - - -/*! \} deallocation_functions - */ - - -/*! \p raw_pointer_cast creates a "raw" pointer from a pointer-like type, - * simply returning the wrapped pointer, should it exist. - * - * \param ptr The pointer of interest. - * \return ptr.get(), if the expression is well formed; ptr, otherwise. - * \see raw_reference_cast - */ -template -__host__ __device__ -typename thrust::detail::pointer_traits::raw_pointer - raw_pointer_cast(Pointer ptr); - - -/*! \p raw_reference_cast creates a "raw" reference from a wrapped reference type, - * simply returning the underlying reference, should it exist. - * - * If the argument is not a reference wrapper, the result is a reference to the argument. - * - * \param ref The reference of interest. - * \return *thrust::raw_pointer_cast(&ref). - * \note There are two versions of \p raw_reference_cast. One for const references, - * and one for non-const. - * \see raw_pointer_cast - */ -template -__host__ __device__ -typename detail::raw_reference::type - raw_reference_cast(T &ref); - - -/*! \p raw_reference_cast creates a "raw" reference from a wrapped reference type, - * simply returning the underlying reference, should it exist. - * - * If the argument is not a reference wrapper, the result is a reference to the argument. - * - * \param ref The reference of interest. - * \return *thrust::raw_pointer_cast(&ref). - * \note There are two versions of \p raw_reference_cast. One for const references, - * and one for non-const. - * \see raw_pointer_cast - */ -template -__host__ __device__ -typename detail::raw_reference::type - raw_reference_cast(const T &ref); - - -/*! \} - */ - -} // end thrust - diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/tbb/detail/generate.h b/spaces/CVPR/LIVE/thrust/thrust/system/tbb/detail/generate.h deleted file mode 100644 index f907b6acc079577642c446d6f0736073defc44b8..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/tbb/detail/generate.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 generate -#include - diff --git a/spaces/CVPR/LIVE/vector.h b/spaces/CVPR/LIVE/vector.h deleted file mode 100644 index 3575b269b8f47cf26580bfa8cafbbf9af8ee1d7e..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/vector.h +++ /dev/null @@ -1,817 +0,0 @@ -#pragma once - -#include "diffvg.h" -#include -#include - -template -struct TVector2 { - DEVICE TVector2() {} - - template - DEVICE - TVector2(T2 x, T2 y) : x(T(x)), y(T(y)) {} - - template - DEVICE - TVector2(const TVector2 &v) : x(T(v.x)), y(T(v.y)) {} - - DEVICE T& operator[](int i) { - return *(&x + i); - } - - DEVICE T operator[](int i) const { - return *(&x + i); - } - - T x, y; -}; - -template -struct TVector3 { - DEVICE TVector3() {} - - template - DEVICE - TVector3(T2 x, T2 y, T2 z) : x(T(x)), y(T(y)), z(T(z)) {} - - template - DEVICE - TVector3(const TVector3 &v) : x(T(v.x)), y(T(v.y)), z(T(v.z)) {} - - DEVICE T& operator[](int i) { - return *(&x + i); - } - - DEVICE T operator[](int i) const { - return *(&x + i); - } - - T x, y, z; -}; - -template -struct TVector4 { - DEVICE TVector4() {} - - template - DEVICE - TVector4(T2 x, T2 y, T2 z, T2 w) : x(T(x)), y(T(y)), z(T(z)), w(T(w)) {} - - template - DEVICE - TVector4(const TVector4 &v) : x(T(v.x)), y(T(v.y)), z(T(v.z)), w(T(v.w)) {} - - - DEVICE T& operator[](int i) { - return *(&x + i); - } - - DEVICE T operator[](int i) const { - return *(&x + i); - } - - T x, y, z, w; -}; - -using Vector2f = TVector2; -using Vector2d = TVector2; -using Vector2i = TVector2; -using Vector2 = TVector2; -using Vector3i = TVector3; -using Vector3f = TVector3; -using Vector3d = TVector3; -using Vector3 = TVector3; -using Vector4f = TVector4; -using Vector4d = TVector4; -using Vector4 = TVector4; - -template -DEVICE -inline auto operator+(const TVector2 &v0, - const TVector2 &v1) -> TVector2 { - return TVector2{ - v0[0] + v1[0], v0[1] + v1[1]}; -} - -template -DEVICE -inline auto operator+(const T0 &v0, - const TVector2 &v1) -> TVector2 { - return TVector2{v0 + v1[0], v0 + v1[1]}; -} - -template -DEVICE -inline auto operator+(const T0 &v0, - const TVector3 &v1) -> TVector3 { - return TVector3{ - v0 + v1[0], v0 + v1[1], v0 + v1[2]}; -} - -template -DEVICE -inline auto operator+(const TVector2 &v0, - const T1 &v1) -> TVector2 { - return TVector2{ - v0[0] + v1, v0[1] + v1}; -} - -template -DEVICE -inline auto operator+(const TVector3 &v0, - const T1 &v1) -> TVector3 { - return TVector3{ - v0[0] + v1, v0[1] + v1, v0[2] + v1}; -} - -template -DEVICE -inline auto operator+(const TVector3 &v0, - const TVector3 &v1) -> TVector3 { - return TVector3{ - v0[0] + v1[0], v0[1] + v1[1], v0[2] + v1[2]}; -} - -template -DEVICE -inline auto operator+(const TVector4 &v0, - const TVector4 &v1) -> TVector4 { - return TVector4{ - v0[0] + v1[0], v0[1] + v1[1], v0[2] + v1[2], v0[3] + v1[3]}; -} - -template -DEVICE -inline auto operator+=(TVector2 &v0, - const TVector2 &v1) -> TVector2& { - v0[0] += v1[0]; - v0[1] += v1[1]; - return v0; -} - -template -DEVICE -inline auto operator+=(TVector3 &v0, - const TVector3 &v1) -> TVector3& { - v0[0] += v1[0]; - v0[1] += v1[1]; - v0[2] += v1[2]; - return v0; -} - -template -DEVICE -inline auto operator+=(TVector3 &v0, - const T1 &v1) -> TVector3& { - v0[0] += v1; - v0[1] += v1; - v0[2] += v1; - return v0; -} - -template -DEVICE -inline auto operator+=(TVector4 &v0, - const TVector4 &v1) -> TVector4& { - v0[0] += v1[0]; - v0[1] += v1[1]; - v0[2] += v1[2]; - v0[3] += v1[3]; - return v0; -} - -template -DEVICE -inline auto operator+=(TVector4 &v0, - const T1 &v1) -> TVector4& { - v0[0] += v1; - v0[1] += v1; - v0[2] += v1; - v0[3] += v1; - return v0; -} - -template -DEVICE -inline auto operator-(const T0 &v0, - const TVector2 &v1) -> TVector2 { - return TVector2{v0 - v1[0], v0 - v1[1]}; -} - -template -DEVICE -inline auto operator-(const T0 &v0, - const TVector3 &v1) -> TVector2 { - return TVector3{v0 - v1[0], v0 - v1[1], v0 - v1[2]}; -} - -template -DEVICE -inline auto operator-(const TVector2 &v0, - const T1 &v1) -> TVector2 { - return TVector2{v0[0] - v1, v0[1] - v1}; -} - -template -DEVICE -inline auto operator-(const TVector3 &v0, - const T1 &v1) -> TVector3 { - return TVector3{v0[0] - v1, v0[1] - v1, v0[2] - v1}; -} - -template -DEVICE -inline auto operator-(const TVector2 &v0, - const TVector2 &v1) -> TVector2 { - return TVector2{ - v0[0] - v1[0], v0[1] - v1[1]}; -} - -template -DEVICE -inline auto operator-(const TVector2 &v) -> TVector2 { - return TVector2{-v[0], -v[1]}; -} - -template -DEVICE -inline auto operator-(const TVector3 &v) -> TVector3 { - return TVector3{-v[0], -v[1], -v[2]}; -} - -template -DEVICE -inline auto operator-(const TVector3 &v0, - const TVector3 &v1) -> TVector3 { - return TVector3{ - v0[0] - v1[0], v0[1] - v1[1], v0[2] - v1[2]}; -} - -template -DEVICE -inline auto operator-(const TVector4 &v0, - const TVector4 &v1) -> TVector4 { - return TVector4{ - v0[0] - v1[0], v0[1] - v1[1], v0[2] - v1[2], v0[3] - v1[3]}; -} - -template -DEVICE -inline auto operator-=(TVector2 &v0, - const TVector2 &v1) -> TVector2& { - v0[0] -= v1[0]; - v0[1] -= v1[1]; - return v0; -} - -template -DEVICE -inline auto operator-=(TVector3 &v0, - const TVector3 &v1) -> TVector3& { - v0[0] -= v1[0]; - v0[1] -= v1[1]; - v0[2] -= v1[2]; - return v0; -} - -template -DEVICE -inline auto operator*(const TVector2 &v0, - const TVector2 &v1) -> TVector2 { - return TVector2{ - v0[0] * v1[0], v0[1] * v1[1]}; -} - -template -DEVICE -inline auto operator*(const TVector2 &v0, - const T1 &s) -> TVector2 { - return TVector2{ - v0[0] * s, v0[1] * s}; -} - -template -DEVICE -inline auto operator*(const T0 &s, - const TVector2 &v0) -> TVector2 { - return TVector2{s * v0[0], s * v0[1]}; -} - -template -DEVICE -inline auto operator*=(TVector2 &v0, - const T1 &s) -> TVector2& { - v0[0] *= s; - v0[1] *= s; - return v0; -} - -template -DEVICE -inline auto operator*(const TVector3 &v0, - const T1 &s) -> TVector3 { - return TVector3{ - v0[0] * s, v0[1] * s, v0[2] * s}; -} - -template -DEVICE -inline auto operator*(const T0 &s, - const TVector3 &v0) -> TVector3 { - return TVector3{ - s * v0[0], s * v0[1], s * v0[2]}; -} - -template -DEVICE -inline auto operator*=(TVector3 &v0, - const T1 &s) -> TVector3& { - v0[0] *= s; - v0[1] *= s; - v0[2] *= s; - return v0; -} - -template -DEVICE -inline auto operator*=(TVector4 &v0, - const T1 &s) -> TVector4& { - v0[0] *= s; - v0[1] *= s; - v0[2] *= s; - v0[3] *= s; - return v0; -} - -template -DEVICE -inline auto operator*(const TVector3 &v0, - const TVector3 &v1) -> TVector3 { - return TVector3{ - v0[0] * v1[0], v0[1] * v1[1], v0[2] * v1[2]}; -} - -template -DEVICE -inline auto operator*(const TVector4 &v0, - const T1 &s) -> TVector4 { - return TVector4{ - v0[0] * s, v0[1] * s, v0[2] * s, v0[3] * s}; -} - -template -DEVICE -inline auto operator*(const T0 &s, - const TVector4 &v0) -> TVector4 { - return TVector4{ - s * v0[0], s * v0[1], s * v0[2], s * v0[3]}; -} - -template -DEVICE -inline auto operator*(const TVector4 &v0, - const TVector4 &v1) -> TVector4 { - return TVector4{ - v0[0] * v1[0], v0[1] * v1[1], v0[2] * v1[2], v0[3] * v1[3]}; -} - -template -DEVICE -inline auto operator/(const TVector2 &v0, - const T1 &s) -> TVector2 { - auto inv_s = 1.f / s; - return v0 * inv_s; -} - -template -DEVICE -inline auto operator/(const TVector3 &v0, - const T1 &s) -> TVector3 { - auto inv_s = 1.f / s; - return v0 * inv_s; -} - -template -DEVICE -inline auto operator/(const TVector4 &v0, - const T1 &s) -> TVector4 { - auto inv_s = 1.f / s; - return v0 * inv_s; -} - -template -DEVICE -inline auto operator/(const T0 &s, - const TVector3 &v1) -> TVector3 { - return TVector3{ - s / v1[0], s / v1[2], s / v1[2]}; -} - -template -DEVICE -inline auto operator/(const TVector3 &v0, - const TVector3 &v1) -> TVector3 { - return TVector3{ - v0[0] / v1[0], v0[1] / v1[2], v0[2] / v1[2]}; -} - -template -DEVICE -inline auto operator/(const TVector2 &v0, - const TVector2 &v1) -> TVector2 { - return TVector2{ - v0[0] / v1[0], v0[1] / v1[1]}; -} - -template -DEVICE -inline auto operator/=(TVector3 &v0, - const T1 &s) -> TVector3& { - auto inv_s = 1.f / s; - v0[0] *= inv_s; - v0[1] *= inv_s; - v0[2] *= inv_s; - return v0; -} - -template -DEVICE -inline auto operator/=(TVector4 &v0, - const T1 &s) -> TVector4& { - auto inv_s = 1.f / s; - v0[0] *= inv_s; - v0[1] *= inv_s; - v0[2] *= inv_s; - v0[3] *= inv_s; - return v0; -} - -template -DEVICE -inline bool operator==(const TVector2 &v0, - const TVector2 &v1) { - return v0.x == v1.x && v0.y == v1.y; -} - -template -DEVICE -inline bool operator==(const TVector3 &v0, - const TVector3 &v1) { - return v0.x == v1.x && v0.y == v1.y && v0.z == v1.z; -} - -template -DEVICE -inline bool operator!=(const TVector3 &v0, - const TVector3 &v1) { - return v0.x != v1.x || v0.y != v1.y || v0.z != v1.z; -} - -template -DEVICE -inline TVector2 get_normal(const TVector2 &v) { - return TVector2{v.y, -v.x}; -} - -template -DEVICE -inline T length_squared(const TVector2 &v0) { - return square(v0[0]) + square(v0[1]); -} - -template -DEVICE -inline TVector2 d_length_squared(const TVector2 &v0, const T &d_l_sq) { - //l_sq = square(v0[0]) + square(v0[1]) - return 2 * d_l_sq * v0; -} - -template -DEVICE -inline T length(const TVector2 &v0) { - return sqrt(length_squared(v0)); -} - -template -DEVICE -inline TVector2 d_length(const TVector2 &v0, const T &d_l) { - auto l_sq = length_squared(v0); - auto l = sqrt(l_sq); - auto d_l_sq = 0.5f * d_l / l; - return d_length_squared(v0, T(d_l_sq)); -} - -template -DEVICE -inline T length_squared(const TVector3 &v0) { - return square(v0[0]) + square(v0[1]) + square(v0[2]); -} - -template -DEVICE -inline TVector3 d_length_squared(const TVector3 &v0, const T &d_l_sq) { - //l_sq = square(v0[0]) + square(v0[1]) + square(v0[2]) - return 2 * d_l_sq * v0; -} - -template -DEVICE -inline T length(const TVector3 &v0) { - return sqrt(length_squared(v0)); -} - -template -DEVICE -inline TVector3 d_length(const TVector3 &v0, const T &d_l) { - auto l_sq = length_squared(v0); - auto l = sqrt(l_sq); - auto d_l_sq = 0.5f * d_l / l; - return d_length_squared(v0, d_l_sq); -} - -template -DEVICE -inline auto distance_squared(const TVector2 &v0, - const TVector2 &v1) -> decltype(length_squared(v1 - v0)) { - return length_squared(v1 - v0); -} - -template -DEVICE -inline auto distance_squared(const TVector3 &v0, - const TVector3 &v1) -> decltype(length_squared(v1 - v0)) { - return length_squared(v1 - v0); -} - -template -DEVICE -inline auto distance(const TVector2 &v0, - const TVector2 &v1) -> decltype(length(v1 - v0)) { - return length(v1 - v0); -} - -template -DEVICE -inline void d_distance(const TVector2 &v0, - const TVector2 &v1, - const T &d_output, - TVector2 &d_v0, - TVector2 &d_v1) { - auto d_v1_v0 = d_length(v1 - v0, d_output); - d_v0 -= d_v1_v0; - d_v1 += d_v1_v0; -} - -template -DEVICE -inline auto distance(const TVector3 &v0, - const TVector3 &v1) -> decltype(length(v1 - v0)) { - return length(v1 - v0); -} - -template -DEVICE -inline void d_distance(const TVector3 &v0, - const TVector3 &v1, - const T &d_output, - TVector3 &d_v0, - TVector3 &d_v1) { - auto d_v1_v0 = d_length(v1 - v0, d_output); - d_v0 -= d_v1_v0; - d_v1 += d_v1_v0; -} - -template -DEVICE -inline TVector2 normalize(const TVector2 &v0) { - return v0 / length(v0); -} - -template -DEVICE -inline TVector2 d_normalize(const TVector2 &v0, const TVector2 &d_n) { - auto l = length(v0); - auto n = v0 / l; - auto d_v0 = d_n / l; - auto d_l = -dot(d_n, n) / l; - // l = length(v0) - d_v0 += d_length(v0, d_l); - return d_v0; -} - -template -DEVICE -inline TVector3 normalize(const TVector3 &v0) { - return v0 / length(v0); -} - -template -DEVICE -inline TVector3 d_normalize(const TVector3 &v0, const TVector3 &d_n) { - auto l = length(v0); - auto n = v0 / l; - auto d_v0 = d_n / l; - auto d_l = -dot(d_n, n) / l; - // l = length(v0) - d_v0 += d_length(v0, d_l); - return d_v0; -} - -template -DEVICE -inline auto dot(const TVector2 &v0, const TVector2 &v1) -> decltype(v0[0] * v1[0]) { - return v0[0] * v1[0] + - v0[1] * v1[1]; -} - -template -DEVICE -inline auto dot(const TVector3 &v0, const TVector3 &v1) -> decltype(v0[0] * v1[0]) { - return v0[0] * v1[0] + - v0[1] * v1[1] + - v0[2] * v1[2]; -} - -template -DEVICE -inline auto dot(const TVector4 &v0, const TVector4 &v1) -> decltype(v0[0] * v1[0]) { - return v0[0] * v1[0] + - v0[1] * v1[1] + - v0[2] * v1[2] + - v0[3] * v1[3]; -} - -template -DEVICE -inline auto cross(const TVector3 &v0, const TVector3 &v1) -> TVector3 { - return TVector3{ - v0[1] * v1[2] - v0[2] * v1[1], - v0[2] * v1[0] - v0[0] * v1[2], - v0[0] * v1[1] - v0[1] * v1[0]}; -} - -template -DEVICE -inline void d_cross(const TVector3 &v0, const TVector3 &v1, const TVector3 &d_output, - TVector3 &d_v0, TVector3 &d_v1) { - d_v0 += cross(v1, d_output); - d_v1 += cross(d_output, v0); -} - -template -DEVICE -inline T luminance(const TVector3 &v) { - return 0.212671f * v[0] + - 0.715160f * v[1] + - 0.072169f * v[2]; -} - -template -DEVICE -inline T sum(const T &v) { - return v; -} - -template -DEVICE -inline T sum(const TVector2 &v) { - return v[0] + v[1]; -} - -template -DEVICE -inline T sum(const TVector3 &v) { - return v[0] + v[1] + v[2]; -} - -template -DEVICE -inline T sum(const TVector4 &v) { - return v[0] + v[1] + v[2] + v[3]; -} - -template -DEVICE -void coordinate_system(const TVector3 &n, TVector3 &x, TVector3 &y) { - if (n[2] < -1.f + 1e-6f) { - x = TVector3{T(0), T(-1), T(0)}; - y = TVector3{T(-1), T(0), T(0)}; - } else { - auto a = 1.f / (1.f + n[2]); - auto b = -n[0] * n[1] * a; - x = TVector3{1.f - square(n[0]) * a, b, -n[0]}; - y = TVector3{b, 1.f - square(n[1]) * a, -n[1]}; - } -} - -template -DEVICE -void d_coordinate_system(const TVector3 &n, const TVector3 &d_x, const TVector3 &d_y, - TVector3 &d_n) { - if (n[2] < -1.f + 1e-6f) { - //x = TVector3{T(0), T(-1), T(0)}; - //y = TVector3{T(-1), T(0), T(0)}; - // don't need to do anything - } else { - auto a = 1.f / (1.f + n[2]); - // auto b = -n[0] * n[1] * a; - // x = TVector3{1.f - square(n[0]) * a, b, -n[0]} - d_n[0] -= 2.f * n[0] * d_x[0] * a; - auto d_a = -square(n[0]) * d_x[0]; - auto d_b = d_x[1]; - d_n[0] -= d_x[2]; - // y = TVector3{b, 1.f - square(n[1]) * a, -n[1]} - d_b += d_y[0]; - d_n[1] -= 2.f * d_y[1] * n[1] * a; - d_a -= d_y[1] * square(n[1]); - d_n[1] -= d_y[2]; - // b = -n[0] * n[1] * a - d_n[0] -= d_b * n[1] * a; - d_n[1] -= d_b * n[0] * a; - d_a -= d_b * n[0] * n[1]; - // a = 1 / (1 + n[2]) - d_n[2] -= d_a * a / (1 + n[2]); - } -} - -DEVICE -inline bool isfinite(const Vector2 &v) { - return isfinite(v.x) && - isfinite(v.y); -} - -DEVICE -inline bool isfinite(const Vector3 &v) { - return isfinite(v.x) && - isfinite(v.y) && - isfinite(v.z); -} - -DEVICE -inline bool isfinite(const Vector4 &v) { - return isfinite(v.x) && - isfinite(v.y) && - isfinite(v.z) && - isfinite(v.w); -} - -DEVICE -inline bool is_zero(const Vector3 &v) { - return v.x == 0 && v.y == 0 && v.z == 0; -} - -template -inline std::ostream& operator<<(std::ostream &os, const TVector2 &v) { - return os << "(" << v[0] << ", " << v[1] << ")"; -} - -template -inline std::ostream& operator<<(std::ostream &os, const TVector3 &v) { - return os << "(" << v[0] << ", " << v[1] << ", " << v[2] << ")"; -} - -template -inline std::ostream& operator<<(std::ostream &os, const TVector4 &v) { - return os << "(" << v[0] << ", " << v[1] << ", " << v[2] << ", " << v[3] << ")"; -} - -DEVICE -inline -float det(const Vector2f &a, const Vector2f &b) { - return a.x*b.y-b.x*a.y; -} - -DEVICE -inline -Vector2f quadratic_closest_pt_approx(const Vector2f &b0, - const Vector2f &b1, - const Vector2f &b2, - float *t_ = nullptr) { - // From http://w3.impa.br/~diego/publications/NehHop08.pdf - float a=det(b0,b2), b=2*det(b1,b0), d=2*det(b2,b1); - float f=b*d-a*a; - Vector2f d21=b2-b1, d10=b1-b0, d20=b2-b0; - Vector2f gf=2*(b*d21+d*d10+a*d20); - gf=Vector2f(gf.y,-gf.x); - Vector2f pp=-f*gf/dot(gf,gf); - Vector2f d0p=b0-pp; - float ap=det(d0p,d20), bp=2*det(d10,d0p); - float t=clamp((ap+bp)/(2*a+b+d),0.f,1.f); - float tt = 1 - t; - if (t_ != nullptr) { - *t_ = t; - } - return (tt*tt)*b0 + (2*tt*t)*b1 + (t*t)*b2; -} - -DEVICE -inline -Vector2f quadratic_closest_pt_approx(const Vector2f &b0, - const Vector2f &b1, - const Vector2f &b2, - const Vector2f &pt, - float *t = nullptr) { - // Approximate closest point to a quadratic curve - return quadratic_closest_pt_approx(b0 - pt, b1 - pt, b2 - pt, t) + pt; -} diff --git a/spaces/CVPR/WALT/mmdet/datasets/dataset_wrappers.py b/spaces/CVPR/WALT/mmdet/datasets/dataset_wrappers.py deleted file mode 100644 index 55ad5cb60e581a96bdbd1fbbeebc2f46f8c4e899..0000000000000000000000000000000000000000 --- a/spaces/CVPR/WALT/mmdet/datasets/dataset_wrappers.py +++ /dev/null @@ -1,282 +0,0 @@ -import bisect -import math -from collections import defaultdict - -import numpy as np -from mmcv.utils import print_log -from torch.utils.data.dataset import ConcatDataset as _ConcatDataset - -from .builder import DATASETS -from .coco import CocoDataset - - -@DATASETS.register_module() -class ConcatDataset(_ConcatDataset): - """A wrapper of concatenated dataset. - - Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but - concat the group flag for image aspect ratio. - - Args: - datasets (list[:obj:`Dataset`]): A list of datasets. - separate_eval (bool): Whether to evaluate the results - separately if it is used as validation dataset. - Defaults to True. - """ - - def __init__(self, datasets, separate_eval=True): - super(ConcatDataset, self).__init__(datasets) - self.CLASSES = datasets[0].CLASSES - self.separate_eval = separate_eval - if not separate_eval: - if any([isinstance(ds, CocoDataset) for ds in datasets]): - raise NotImplementedError( - 'Evaluating concatenated CocoDataset as a whole is not' - ' supported! Please set "separate_eval=True"') - elif len(set([type(ds) for ds in datasets])) != 1: - raise NotImplementedError( - 'All the datasets should have same types') - - if hasattr(datasets[0], 'flag'): - flags = [] - for i in range(0, len(datasets)): - flags.append(datasets[i].flag) - self.flag = np.concatenate(flags) - - def get_cat_ids(self, idx): - """Get category ids of concatenated dataset by index. - - Args: - idx (int): Index of data. - - Returns: - list[int]: All categories in the image of specified index. - """ - - if idx < 0: - if -idx > len(self): - raise ValueError( - 'absolute value of index should not exceed dataset length') - idx = len(self) + idx - dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) - if dataset_idx == 0: - sample_idx = idx - else: - sample_idx = idx - self.cumulative_sizes[dataset_idx - 1] - return self.datasets[dataset_idx].get_cat_ids(sample_idx) - - def evaluate(self, results, logger=None, **kwargs): - """Evaluate the results. - - Args: - results (list[list | tuple]): Testing results of the dataset. - logger (logging.Logger | str | None): Logger used for printing - related information during evaluation. Default: None. - - Returns: - dict[str: float]: AP results of the total dataset or each separate - dataset if `self.separate_eval=True`. - """ - assert len(results) == self.cumulative_sizes[-1], \ - ('Dataset and results have different sizes: ' - f'{self.cumulative_sizes[-1]} v.s. {len(results)}') - - # Check whether all the datasets support evaluation - for dataset in self.datasets: - assert hasattr(dataset, 'evaluate'), \ - f'{type(dataset)} does not implement evaluate function' - - if self.separate_eval: - dataset_idx = -1 - total_eval_results = dict() - for size, dataset in zip(self.cumulative_sizes, self.datasets): - start_idx = 0 if dataset_idx == -1 else \ - self.cumulative_sizes[dataset_idx] - end_idx = self.cumulative_sizes[dataset_idx + 1] - - results_per_dataset = results[start_idx:end_idx] - print_log( - f'\nEvaluateing {dataset.ann_file} with ' - f'{len(results_per_dataset)} images now', - logger=logger) - - eval_results_per_dataset = dataset.evaluate( - results_per_dataset, logger=logger, **kwargs) - dataset_idx += 1 - for k, v in eval_results_per_dataset.items(): - total_eval_results.update({f'{dataset_idx}_{k}': v}) - - return total_eval_results - elif any([isinstance(ds, CocoDataset) for ds in self.datasets]): - raise NotImplementedError( - 'Evaluating concatenated CocoDataset as a whole is not' - ' supported! Please set "separate_eval=True"') - elif len(set([type(ds) for ds in self.datasets])) != 1: - raise NotImplementedError( - 'All the datasets should have same types') - else: - original_data_infos = self.datasets[0].data_infos - self.datasets[0].data_infos = sum( - [dataset.data_infos for dataset in self.datasets], []) - eval_results = self.datasets[0].evaluate( - results, logger=logger, **kwargs) - self.datasets[0].data_infos = original_data_infos - return eval_results - - -@DATASETS.register_module() -class RepeatDataset(object): - """A wrapper of repeated dataset. - - The length of repeated dataset will be `times` larger than the original - dataset. This is useful when the data loading time is long but the dataset - is small. Using RepeatDataset can reduce the data loading time between - epochs. - - Args: - dataset (:obj:`Dataset`): The dataset to be repeated. - times (int): Repeat times. - """ - - def __init__(self, dataset, times): - self.dataset = dataset - self.times = times - self.CLASSES = dataset.CLASSES - if hasattr(self.dataset, 'flag'): - self.flag = np.tile(self.dataset.flag, times) - - self._ori_len = len(self.dataset) - - def __getitem__(self, idx): - return self.dataset[idx % self._ori_len] - - def get_cat_ids(self, idx): - """Get category ids of repeat dataset by index. - - Args: - idx (int): Index of data. - - Returns: - list[int]: All categories in the image of specified index. - """ - - return self.dataset.get_cat_ids(idx % self._ori_len) - - def __len__(self): - """Length after repetition.""" - return self.times * self._ori_len - - -# Modified from https://github.com/facebookresearch/detectron2/blob/41d475b75a230221e21d9cac5d69655e3415e3a4/detectron2/data/samplers/distributed_sampler.py#L57 # noqa -@DATASETS.register_module() -class ClassBalancedDataset(object): - """A wrapper of repeated dataset with repeat factor. - - Suitable for training on class imbalanced datasets like LVIS. Following - the sampling strategy in the `paper `_, - in each epoch, an image may appear multiple times based on its - "repeat factor". - The repeat factor for an image is a function of the frequency the rarest - category labeled in that image. The "frequency of category c" in [0, 1] - is defined by the fraction of images in the training set (without repeats) - in which category c appears. - The dataset needs to instantiate :func:`self.get_cat_ids` to support - ClassBalancedDataset. - - The repeat factor is computed as followed. - - 1. For each category c, compute the fraction # of images - that contain it: :math:`f(c)` - 2. For each category c, compute the category-level repeat factor: - :math:`r(c) = max(1, sqrt(t/f(c)))` - 3. For each image I, compute the image-level repeat factor: - :math:`r(I) = max_{c in I} r(c)` - - Args: - dataset (:obj:`CustomDataset`): The dataset to be repeated. - oversample_thr (float): frequency threshold below which data is - repeated. For categories with ``f_c >= oversample_thr``, there is - no oversampling. For categories with ``f_c < oversample_thr``, the - degree of oversampling following the square-root inverse frequency - heuristic above. - filter_empty_gt (bool, optional): If set true, images without bounding - boxes will not be oversampled. Otherwise, they will be categorized - as the pure background class and involved into the oversampling. - Default: True. - """ - - def __init__(self, dataset, oversample_thr, filter_empty_gt=True): - self.dataset = dataset - self.oversample_thr = oversample_thr - self.filter_empty_gt = filter_empty_gt - self.CLASSES = dataset.CLASSES - - repeat_factors = self._get_repeat_factors(dataset, oversample_thr) - repeat_indices = [] - for dataset_idx, repeat_factor in enumerate(repeat_factors): - repeat_indices.extend([dataset_idx] * math.ceil(repeat_factor)) - self.repeat_indices = repeat_indices - - flags = [] - if hasattr(self.dataset, 'flag'): - for flag, repeat_factor in zip(self.dataset.flag, repeat_factors): - flags.extend([flag] * int(math.ceil(repeat_factor))) - assert len(flags) == len(repeat_indices) - self.flag = np.asarray(flags, dtype=np.uint8) - - def _get_repeat_factors(self, dataset, repeat_thr): - """Get repeat factor for each images in the dataset. - - Args: - dataset (:obj:`CustomDataset`): The dataset - repeat_thr (float): The threshold of frequency. If an image - contains the categories whose frequency below the threshold, - it would be repeated. - - Returns: - list[float]: The repeat factors for each images in the dataset. - """ - - # 1. For each category c, compute the fraction # of images - # that contain it: f(c) - category_freq = defaultdict(int) - num_images = len(dataset) - for idx in range(num_images): - cat_ids = set(self.dataset.get_cat_ids(idx)) - if len(cat_ids) == 0 and not self.filter_empty_gt: - cat_ids = set([len(self.CLASSES)]) - for cat_id in cat_ids: - category_freq[cat_id] += 1 - for k, v in category_freq.items(): - category_freq[k] = v / num_images - - # 2. For each category c, compute the category-level repeat factor: - # r(c) = max(1, sqrt(t/f(c))) - category_repeat = { - cat_id: max(1.0, math.sqrt(repeat_thr / cat_freq)) - for cat_id, cat_freq in category_freq.items() - } - - # 3. For each image I, compute the image-level repeat factor: - # r(I) = max_{c in I} r(c) - repeat_factors = [] - for idx in range(num_images): - cat_ids = set(self.dataset.get_cat_ids(idx)) - if len(cat_ids) == 0 and not self.filter_empty_gt: - cat_ids = set([len(self.CLASSES)]) - repeat_factor = 1 - if len(cat_ids) > 0: - repeat_factor = max( - {category_repeat[cat_id] - for cat_id in cat_ids}) - repeat_factors.append(repeat_factor) - - return repeat_factors - - def __getitem__(self, idx): - ori_index = self.repeat_indices[idx] - return self.dataset[ori_index] - - def __len__(self): - """Length after repetition.""" - return len(self.repeat_indices) diff --git a/spaces/CVPR/WALT/mmdet/models/detectors/__init__.py b/spaces/CVPR/WALT/mmdet/models/detectors/__init__.py deleted file mode 100644 index 04011130435cf9fdfadeb821919046b1bddab7d4..0000000000000000000000000000000000000000 --- a/spaces/CVPR/WALT/mmdet/models/detectors/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -from .atss import ATSS -from .base import BaseDetector -from .cascade_rcnn import CascadeRCNN -from .cornernet import CornerNet -from .detr import DETR -from .fast_rcnn import FastRCNN -from .faster_rcnn import FasterRCNN -from .fcos import FCOS -from .fovea import FOVEA -from .fsaf import FSAF -from .gfl import GFL -from .grid_rcnn import GridRCNN -from .htc import HybridTaskCascade -from .kd_one_stage import KnowledgeDistillationSingleStageDetector -from .mask_rcnn import MaskRCNN -from .mask_scoring_rcnn import MaskScoringRCNN -from .nasfcos import NASFCOS -from .paa import PAA -from .point_rend import PointRend -from .reppoints_detector import RepPointsDetector -from .retinanet import RetinaNet -from .rpn import RPN -from .scnet import SCNet -from .single_stage import SingleStageDetector -from .sparse_rcnn import SparseRCNN -from .trident_faster_rcnn import TridentFasterRCNN -from .two_stage import TwoStageDetector -from .vfnet import VFNet -from .yolact import YOLACT -from .yolo import YOLOV3 - -__all__ = [ - 'ATSS', 'BaseDetector', 'SingleStageDetector', - 'KnowledgeDistillationSingleStageDetector', 'TwoStageDetector', 'RPN', - 'FastRCNN', 'FasterRCNN', 'MaskRCNN', 'CascadeRCNN', 'HybridTaskCascade', - 'RetinaNet', 'FCOS', 'GridRCNN', 'MaskScoringRCNN', 'RepPointsDetector', - 'FOVEA', 'FSAF', 'NASFCOS', 'PointRend', 'GFL', 'CornerNet', 'PAA', - 'YOLOV3', 'YOLACT', 'VFNet', 'DETR', 'TridentFasterRCNN', 'SparseRCNN', - 'SCNet' -] diff --git a/spaces/CVPR/WALT/mmdet/models/necks/nas_fpn.py b/spaces/CVPR/WALT/mmdet/models/necks/nas_fpn.py deleted file mode 100644 index 8e333ce65d4d06c47c29af489526ba3142736ad7..0000000000000000000000000000000000000000 --- a/spaces/CVPR/WALT/mmdet/models/necks/nas_fpn.py +++ /dev/null @@ -1,160 +0,0 @@ -import torch.nn as nn -from mmcv.cnn import ConvModule, caffe2_xavier_init -from mmcv.ops.merge_cells import GlobalPoolingCell, SumCell - -from ..builder import NECKS - - -@NECKS.register_module() -class NASFPN(nn.Module): - """NAS-FPN. - - Implementation of `NAS-FPN: Learning Scalable Feature Pyramid Architecture - for Object Detection `_ - - Args: - in_channels (List[int]): Number of input channels per scale. - out_channels (int): Number of output channels (used at each scale) - num_outs (int): Number of output scales. - stack_times (int): The number of times the pyramid architecture will - be stacked. - start_level (int): Index of the start input backbone level used to - build the feature pyramid. Default: 0. - end_level (int): Index of the end input backbone level (exclusive) to - build the feature pyramid. Default: -1, which means the last level. - add_extra_convs (bool): It decides whether to add conv - layers on top of the original feature maps. Default to False. - If True, its actual mode is specified by `extra_convs_on_inputs`. - """ - - def __init__(self, - in_channels, - out_channels, - num_outs, - stack_times, - start_level=0, - end_level=-1, - add_extra_convs=False, - norm_cfg=None): - super(NASFPN, self).__init__() - assert isinstance(in_channels, list) - self.in_channels = in_channels - self.out_channels = out_channels - self.num_ins = len(in_channels) # num of input feature levels - self.num_outs = num_outs # num of output feature levels - self.stack_times = stack_times - self.norm_cfg = norm_cfg - - if end_level == -1: - self.backbone_end_level = self.num_ins - assert num_outs >= self.num_ins - start_level - else: - # if end_level < inputs, no extra level is allowed - self.backbone_end_level = end_level - assert end_level <= len(in_channels) - assert num_outs == end_level - start_level - self.start_level = start_level - self.end_level = end_level - self.add_extra_convs = add_extra_convs - - # add lateral connections - self.lateral_convs = nn.ModuleList() - for i in range(self.start_level, self.backbone_end_level): - l_conv = ConvModule( - in_channels[i], - out_channels, - 1, - norm_cfg=norm_cfg, - act_cfg=None) - self.lateral_convs.append(l_conv) - - # add extra downsample layers (stride-2 pooling or conv) - extra_levels = num_outs - self.backbone_end_level + self.start_level - self.extra_downsamples = nn.ModuleList() - for i in range(extra_levels): - extra_conv = ConvModule( - out_channels, out_channels, 1, norm_cfg=norm_cfg, act_cfg=None) - self.extra_downsamples.append( - nn.Sequential(extra_conv, nn.MaxPool2d(2, 2))) - - # add NAS FPN connections - self.fpn_stages = nn.ModuleList() - for _ in range(self.stack_times): - stage = nn.ModuleDict() - # gp(p6, p4) -> p4_1 - stage['gp_64_4'] = GlobalPoolingCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - # sum(p4_1, p4) -> p4_2 - stage['sum_44_4'] = SumCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - # sum(p4_2, p3) -> p3_out - stage['sum_43_3'] = SumCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - # sum(p3_out, p4_2) -> p4_out - stage['sum_34_4'] = SumCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - # sum(p5, gp(p4_out, p3_out)) -> p5_out - stage['gp_43_5'] = GlobalPoolingCell(with_out_conv=False) - stage['sum_55_5'] = SumCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - # sum(p7, gp(p5_out, p4_2)) -> p7_out - stage['gp_54_7'] = GlobalPoolingCell(with_out_conv=False) - stage['sum_77_7'] = SumCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - # gp(p7_out, p5_out) -> p6_out - stage['gp_75_6'] = GlobalPoolingCell( - in_channels=out_channels, - out_channels=out_channels, - out_norm_cfg=norm_cfg) - self.fpn_stages.append(stage) - - def init_weights(self): - """Initialize the weights of module.""" - for m in self.modules(): - if isinstance(m, nn.Conv2d): - caffe2_xavier_init(m) - - def forward(self, inputs): - """Forward function.""" - # build P3-P5 - feats = [ - lateral_conv(inputs[i + self.start_level]) - for i, lateral_conv in enumerate(self.lateral_convs) - ] - # build P6-P7 on top of P5 - for downsample in self.extra_downsamples: - feats.append(downsample(feats[-1])) - - p3, p4, p5, p6, p7 = feats - - for stage in self.fpn_stages: - # gp(p6, p4) -> p4_1 - p4_1 = stage['gp_64_4'](p6, p4, out_size=p4.shape[-2:]) - # sum(p4_1, p4) -> p4_2 - p4_2 = stage['sum_44_4'](p4_1, p4, out_size=p4.shape[-2:]) - # sum(p4_2, p3) -> p3_out - p3 = stage['sum_43_3'](p4_2, p3, out_size=p3.shape[-2:]) - # sum(p3_out, p4_2) -> p4_out - p4 = stage['sum_34_4'](p3, p4_2, out_size=p4.shape[-2:]) - # sum(p5, gp(p4_out, p3_out)) -> p5_out - p5_tmp = stage['gp_43_5'](p4, p3, out_size=p5.shape[-2:]) - p5 = stage['sum_55_5'](p5, p5_tmp, out_size=p5.shape[-2:]) - # sum(p7, gp(p5_out, p4_2)) -> p7_out - p7_tmp = stage['gp_54_7'](p5, p4_2, out_size=p7.shape[-2:]) - p7 = stage['sum_77_7'](p7, p7_tmp, out_size=p7.shape[-2:]) - # gp(p7_out, p5_out) -> p6_out - p6 = stage['gp_75_6'](p7, p5, out_size=p6.shape[-2:]) - - return p3, p4, p5, p6, p7 diff --git a/spaces/CVPR/regionclip-demo/detectron2/export/caffe2_patch.py b/spaces/CVPR/regionclip-demo/detectron2/export/caffe2_patch.py deleted file mode 100644 index c9eee594a27cdec29ce5f2b6f7730171eda3805e..0000000000000000000000000000000000000000 --- a/spaces/CVPR/regionclip-demo/detectron2/export/caffe2_patch.py +++ /dev/null @@ -1,152 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. - -import contextlib -from unittest import mock -import torch - -from detectron2.modeling import poolers -from detectron2.modeling.proposal_generator import rpn -from detectron2.modeling.roi_heads import keypoint_head, mask_head -from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers - -from .c10 import ( - Caffe2Compatible, - Caffe2FastRCNNOutputsInference, - Caffe2KeypointRCNNInference, - Caffe2MaskRCNNInference, - Caffe2ROIPooler, - Caffe2RPN, -) - - -class GenericMixin(object): - pass - - -class Caffe2CompatibleConverter(object): - """ - A GenericUpdater which implements the `create_from` interface, by modifying - module object and assign it with another class replaceCls. - """ - - def __init__(self, replaceCls): - self.replaceCls = replaceCls - - def create_from(self, module): - # update module's class to the new class - assert isinstance(module, torch.nn.Module) - if issubclass(self.replaceCls, GenericMixin): - # replaceCls should act as mixin, create a new class on-the-fly - new_class = type( - "{}MixedWith{}".format(self.replaceCls.__name__, module.__class__.__name__), - (self.replaceCls, module.__class__), - {}, # {"new_method": lambda self: ...}, - ) - module.__class__ = new_class - else: - # replaceCls is complete class, this allow arbitrary class swap - module.__class__ = self.replaceCls - - # initialize Caffe2Compatible - if isinstance(module, Caffe2Compatible): - module.tensor_mode = False - - return module - - -def patch(model, target, updater, *args, **kwargs): - """ - recursively (post-order) update all modules with the target type and its - subclasses, make a initialization/composition/inheritance/... via the - updater.create_from. - """ - for name, module in model.named_children(): - model._modules[name] = patch(module, target, updater, *args, **kwargs) - if isinstance(model, target): - return updater.create_from(model, *args, **kwargs) - return model - - -def patch_generalized_rcnn(model): - ccc = Caffe2CompatibleConverter - model = patch(model, rpn.RPN, ccc(Caffe2RPN)) - model = patch(model, poolers.ROIPooler, ccc(Caffe2ROIPooler)) - - return model - - -@contextlib.contextmanager -def mock_fastrcnn_outputs_inference( - tensor_mode, check=True, box_predictor_type=FastRCNNOutputLayers -): - with mock.patch.object( - box_predictor_type, - "inference", - autospec=True, - side_effect=Caffe2FastRCNNOutputsInference(tensor_mode), - ) as mocked_func: - yield - if check: - assert mocked_func.call_count > 0 - - -@contextlib.contextmanager -def mock_mask_rcnn_inference(tensor_mode, patched_module, check=True): - with mock.patch( - "{}.mask_rcnn_inference".format(patched_module), side_effect=Caffe2MaskRCNNInference() - ) as mocked_func: - yield - if check: - assert mocked_func.call_count > 0 - - -@contextlib.contextmanager -def mock_keypoint_rcnn_inference(tensor_mode, patched_module, use_heatmap_max_keypoint, check=True): - with mock.patch( - "{}.keypoint_rcnn_inference".format(patched_module), - side_effect=Caffe2KeypointRCNNInference(use_heatmap_max_keypoint), - ) as mocked_func: - yield - if check: - assert mocked_func.call_count > 0 - - -class ROIHeadsPatcher: - def __init__(self, heads, use_heatmap_max_keypoint): - self.heads = heads - self.use_heatmap_max_keypoint = use_heatmap_max_keypoint - - @contextlib.contextmanager - def mock_roi_heads(self, tensor_mode=True): - """ - Patching several inference functions inside ROIHeads and its subclasses - - Args: - tensor_mode (bool): whether the inputs/outputs are caffe2's tensor - format or not. Default to True. - """ - # NOTE: this requries the `keypoint_rcnn_inference` and `mask_rcnn_inference` - # are called inside the same file as BaseXxxHead due to using mock.patch. - kpt_heads_mod = keypoint_head.BaseKeypointRCNNHead.__module__ - mask_head_mod = mask_head.BaseMaskRCNNHead.__module__ - - mock_ctx_managers = [ - mock_fastrcnn_outputs_inference( - tensor_mode=tensor_mode, - check=True, - box_predictor_type=type(self.heads.box_predictor), - ) - ] - if getattr(self.heads, "keypoint_on", False): - mock_ctx_managers += [ - mock_keypoint_rcnn_inference( - tensor_mode, kpt_heads_mod, self.use_heatmap_max_keypoint - ) - ] - if getattr(self.heads, "mask_on", False): - mock_ctx_managers += [mock_mask_rcnn_inference(tensor_mode, mask_head_mod)] - - with contextlib.ExitStack() as stack: # python 3.3+ - for mgr in mock_ctx_managers: - stack.enter_context(mgr) - yield diff --git a/spaces/Cletrason/Cletrason-toad-mario-movie/app_canny_db.py b/spaces/Cletrason/Cletrason-toad-mario-movie/app_canny_db.py deleted file mode 100644 index 048305d5409f2f4bb10f3e0498f5c53d416977c6..0000000000000000000000000000000000000000 --- a/spaces/Cletrason/Cletrason-toad-mario-movie/app_canny_db.py +++ /dev/null @@ -1,103 +0,0 @@ -import gradio as gr -from model import Model -import gradio_utils -import os -on_huggingspace = os.environ.get("SPACE_AUTHOR_NAME") == "PAIR" - - -examples = [ - ['Anime DB', "woman1", "Portrait of detailed 1girl, feminine, soldier cinematic shot on canon 5d ultra realistic skin intricate clothes accurate hands Rory Lewis Artgerm WLOP Jeremy Lipking Jane Ansell studio lighting"], - ['Arcane DB', "woman1", "Oil painting of a beautiful girl arcane style, masterpiece, a high-quality, detailed, and professional photo"], - ['GTA-5 DB', "man1", "gtav style"], - ['GTA-5 DB', "woman3", "gtav style"], - ['Avatar DB', "woman2", "oil painting of a beautiful girl avatar style"], -] - - -def load_db_model(evt: gr.SelectData): - db_name = gradio_utils.get_db_name_from_id(evt.index) - return db_name - - -def canny_select(evt: gr.SelectData): - canny_name = gradio_utils.get_canny_name_from_id(evt.index) - return canny_name - - -def create_demo(model: Model): - - with gr.Blocks() as demo: - with gr.Row(): - gr.Markdown( - '## Text, Canny-Edge and DreamBooth Conditional Video Generation') - with gr.Row(): - gr.HTML( - """ -
-

- Description: Our current release supports only four predefined DreamBooth models and four "motion edges". So you must choose one DreamBooth model and one "motion edges" shown below, or use the examples. The keywords 1girl, arcane style, gtav, and avatar style correspond to the models from left to right. -

-
- """) - with gr.Row(): - with gr.Column(): - # input_video_path = gr.Video(source='upload', format="mp4", visible=False) - gr.Markdown("## Selection") - db_text_field = gr.Markdown('DB Model: **Anime DB** ') - canny_text_field = gr.Markdown('Motion: **woman1**') - prompt = gr.Textbox(label='Prompt') - run_button = gr.Button(label='Run') - with gr.Accordion('Advanced options', open=False): - watermark = gr.Radio(["Picsart AI Research", "Text2Video-Zero", - "None"], label="Watermark", value='Picsart AI Research') - chunk_size = gr.Slider( - label="Chunk size", minimum=2, maximum=16, value=12 if on_huggingspace else 8, step=1, visible=not on_huggingspace) - with gr.Column(): - result = gr.Image(label="Generated Video").style(height=400) - - with gr.Row(): - gallery_db = gr.Gallery(label="Db models", value=[('__assets__/db_files/anime.jpg', "anime"), ('__assets__/db_files/arcane.jpg', "Arcane"), ( - '__assets__/db_files/gta.jpg', "GTA-5 (Man)"), ('__assets__/db_files/avatar.jpg', "Avatar DB")]).style(grid=[4], height=50) - with gr.Row(): - gallery_canny = gr.Gallery(label="Motions", value=[('__assets__/db_files/woman1.gif', "woman1"), ('__assets__/db_files/woman2.gif', "woman2"), ( - '__assets__/db_files/man1.gif', "man1"), ('__assets__/db_files/woman3.gif', "woman3")]).style(grid=[4], height=50) - - db_selection = gr.Textbox(label="DB Model", visible=False) - canny_selection = gr.Textbox( - label="One of the above defined motions", visible=False) - - gallery_db.select(load_db_model, None, db_selection) - gallery_canny.select(canny_select, None, canny_selection) - - db_selection.change(on_db_selection_update, None, db_text_field) - canny_selection.change(on_canny_selection_update, - None, canny_text_field) - - inputs = [ - db_selection, - canny_selection, - prompt, - chunk_size, - watermark, - ] - - gr.Examples(examples=examples, - inputs=inputs, - outputs=result, - fn=model.process_controlnet_canny_db, - cache_examples=on_huggingspace, - ) - - run_button.click(fn=model.process_controlnet_canny_db, - inputs=inputs, - outputs=result,) - return demo - - -def on_db_selection_update(evt: gr.EventData): - - return f"DB model: **{evt._data}**" - - -def on_canny_selection_update(evt: gr.EventData): - return f"Motion: **{evt._data}**" diff --git a/spaces/CofAI/chat.b4/Dockerfile b/spaces/CofAI/chat.b4/Dockerfile deleted file mode 100644 index 1d30573a8626b2a6c142affbd385666ed44ebf6b..0000000000000000000000000000000000000000 --- a/spaces/CofAI/chat.b4/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM python:3.10-slim-buster - -WORKDIR /app - -COPY requirements.txt requirements.txt - -RUN python -m venv venv -ENV PATH="/app/venv/bin:$PATH" - -RUN apt-get update && \ - apt-get install -y --no-install-recommends build-essential libffi-dev cmake libcurl4-openssl-dev && \ - pip3 install --no-cache-dir -r requirements.txt - -COPY . . - -CMD ["python3", "./run.py"] \ No newline at end of file diff --git a/spaces/DAMO-NLP-SG/CLEX-Chat/config.py b/spaces/DAMO-NLP-SG/CLEX-Chat/config.py deleted file mode 100644 index 93544e53196d6f4af088bdb7a80878329007d65d..0000000000000000000000000000000000000000 --- a/spaces/DAMO-NLP-SG/CLEX-Chat/config.py +++ /dev/null @@ -1,33 +0,0 @@ -{ - "architectures": [ - "LlamaForCausalLM" - ], - "auto_map": { - "AutoConfig": "configuration_clex.CLEXLlamaConfig", - "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM" - }, - "bos_token_id": 1, - "eos_token_id": 2, - "hidden_act": "silu", - "hidden_size": 4096, - "initializer_range": 0.02, - "intermediate_size": 11008, - "max_position_embeddings": 4096, - "model_type": "llama", - "num_attention_heads": 32, - "num_hidden_layers": 32, - "num_key_value_heads": 32, - "pad_token_id": 0, - "pretraining_tp": 1, - "rms_norm_eps": 1e-05, - "tie_word_embeddings": false, - "use_cache": true, - "vocab_size": 32000, - "log_scale": false, - "use_flashattn": true, - "rope_scaling": { - "type": "clex", - "max_factor": 16, - "param_factor": 1, - } -} \ No newline at end of file diff --git a/spaces/DHEIVER/CoronaryAngioSegment/preprocess.py b/spaces/DHEIVER/CoronaryAngioSegment/preprocess.py deleted file mode 100644 index 3cb7bfa8c025add2b5cef515cbd832927ceb68a9..0000000000000000000000000000000000000000 --- a/spaces/DHEIVER/CoronaryAngioSegment/preprocess.py +++ /dev/null @@ -1,6 +0,0 @@ -import cv2 - -def unsharp_masking(img): - gaussian = cv2.GaussianBlur(img, (0, 0), 2.0) - img = cv2.addWeighted(img, 2.0, gaussian, -1.0, 0) - return img \ No newline at end of file diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/attrs/filters.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/attrs/filters.py deleted file mode 100644 index 52959005b088f0e5116c8b6acdbcc5937bbaacc8..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/attrs/filters.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.filters import * # noqa diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/dotenv/cli.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/dotenv/cli.py deleted file mode 100644 index 65ead46155f568a197a16b64c6335f1f28cda9a6..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/dotenv/cli.py +++ /dev/null @@ -1,199 +0,0 @@ -import json -import os -import shlex -import sys -from contextlib import contextmanager -from subprocess import Popen -from typing import Any, Dict, IO, Iterator, List - -try: - import click -except ImportError: - sys.stderr.write('It seems python-dotenv is not installed with cli option. \n' - 'Run pip install "python-dotenv[cli]" to fix this.') - sys.exit(1) - -from .main import dotenv_values, set_key, unset_key -from .version import __version__ - - -def enumerate_env(): - """ - Return a path for the ${pwd}/.env file. - - If pwd does not exist, return None. - """ - try: - cwd = os.getcwd() - except FileNotFoundError: - return None - path = os.path.join(cwd, '.env') - return path - - -@click.group() -@click.option('-f', '--file', default=enumerate_env(), - type=click.Path(file_okay=True), - help="Location of the .env file, defaults to .env file in current working directory.") -@click.option('-q', '--quote', default='always', - type=click.Choice(['always', 'never', 'auto']), - help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.") -@click.option('-e', '--export', default=False, - type=click.BOOL, - help="Whether to write the dot file as an executable bash script.") -@click.version_option(version=__version__) -@click.pass_context -def cli(ctx: click.Context, file: Any, quote: Any, export: Any) -> None: - """This script is used to set, get or unset values from a .env file.""" - ctx.obj = {'QUOTE': quote, 'EXPORT': export, 'FILE': file} - - -@contextmanager -def stream_file(path: os.PathLike) -> Iterator[IO[str]]: - """ - Open a file and yield the corresponding (decoded) stream. - - Exits with error code 2 if the file cannot be opened. - """ - - try: - with open(path) as stream: - yield stream - except OSError as exc: - print(f"Error opening env file: {exc}", file=sys.stderr) - exit(2) - - -@cli.command() -@click.pass_context -@click.option('--format', default='simple', - type=click.Choice(['simple', 'json', 'shell', 'export']), - help="The format in which to display the list. Default format is simple, " - "which displays name=value without quotes.") -def list(ctx: click.Context, format: bool) -> None: - """Display all the stored key/value.""" - file = ctx.obj['FILE'] - - with stream_file(file) as stream: - values = dotenv_values(stream=stream) - - if format == 'json': - click.echo(json.dumps(values, indent=2, sort_keys=True)) - else: - prefix = 'export ' if format == 'export' else '' - for k in sorted(values): - v = values[k] - if v is not None: - if format in ('export', 'shell'): - v = shlex.quote(v) - click.echo(f'{prefix}{k}={v}') - - -@cli.command() -@click.pass_context -@click.argument('key', required=True) -@click.argument('value', required=True) -def set(ctx: click.Context, key: Any, value: Any) -> None: - """Store the given key/value.""" - file = ctx.obj['FILE'] - quote = ctx.obj['QUOTE'] - export = ctx.obj['EXPORT'] - success, key, value = set_key(file, key, value, quote, export) - if success: - click.echo(f'{key}={value}') - else: - exit(1) - - -@cli.command() -@click.pass_context -@click.argument('key', required=True) -def get(ctx: click.Context, key: Any) -> None: - """Retrieve the value for the given key.""" - file = ctx.obj['FILE'] - - with stream_file(file) as stream: - values = dotenv_values(stream=stream) - - stored_value = values.get(key) - if stored_value: - click.echo(stored_value) - else: - exit(1) - - -@cli.command() -@click.pass_context -@click.argument('key', required=True) -def unset(ctx: click.Context, key: Any) -> None: - """Removes the given key.""" - file = ctx.obj['FILE'] - quote = ctx.obj['QUOTE'] - success, key = unset_key(file, key, quote) - if success: - click.echo(f"Successfully removed {key}") - else: - exit(1) - - -@cli.command(context_settings={'ignore_unknown_options': True}) -@click.pass_context -@click.option( - "--override/--no-override", - default=True, - help="Override variables from the environment file with those from the .env file.", -) -@click.argument('commandline', nargs=-1, type=click.UNPROCESSED) -def run(ctx: click.Context, override: bool, commandline: List[str]) -> None: - """Run command with environment variables present.""" - file = ctx.obj['FILE'] - if not os.path.isfile(file): - raise click.BadParameter( - f'Invalid value for \'-f\' "{file}" does not exist.', - ctx=ctx - ) - dotenv_as_dict = { - k: v - for (k, v) in dotenv_values(file).items() - if v is not None and (override or k not in os.environ) - } - - if not commandline: - click.echo('No command given.') - exit(1) - ret = run_command(commandline, dotenv_as_dict) - exit(ret) - - -def run_command(command: List[str], env: Dict[str, str]) -> int: - """Run command in sub process. - - Runs the command in a sub process with the variables from `env` - added in the current environment variables. - - Parameters - ---------- - command: List[str] - The command and it's parameters - env: Dict - The additional environment variables - - Returns - ------- - int - The return code of the command - - """ - # copy the current environment variables and add the vales from - # `env` - cmd_env = os.environ.copy() - cmd_env.update(env) - - p = Popen(command, - universal_newlines=True, - bufsize=0, - shell=False, - env=cmd_env) - _, _ = p.communicate() - - return p.returncode diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/misc/bezierTools.c b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/misc/bezierTools.c deleted file mode 100644 index 3c9d25e5ebe574b9bdf43b88c151207ae0d945c2..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/misc/bezierTools.c +++ /dev/null @@ -1,34575 +0,0 @@ -/* Generated by Cython 0.29.36 */ - -/* BEGIN: Cython Metadata -{ - "distutils": { - "name": "fontTools.misc.bezierTools", - "sources": [ - "Lib/fontTools/misc/bezierTools.py" - ] - }, - "module_name": "fontTools.misc.bezierTools" -} -END: Cython Metadata */ - -#ifndef PY_SSIZE_T_CLEAN -#define PY_SSIZE_T_CLEAN -#endif /* 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_36" -#define CYTHON_HEX_VERSION 0x001D24F0 -#define CYTHON_FUTURE_DIVISION 1 -#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 - #define CYTHON_COMPILING_IN_NOGIL 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 - #if PY_VERSION_HEX < 0x03090000 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) - #define CYTHON_PEP489_MULTI_PHASE_INIT 1 - #endif - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1 && PYPY_VERSION_NUM >= 0x07030C00) - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 - #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 - #endif -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #define CYTHON_COMPILING_IN_NOGIL 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 - #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 - #endif -#elif defined(PY_NOGIL) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #define CYTHON_COMPILING_IN_NOGIL 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #ifndef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #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 - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 1 - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 1 - #endif - #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 - #define CYTHON_COMPILING_IN_NOGIL 0 - #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 (PY_VERSION_HEX < 0x030C00A5) - #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 || PY_VERSION_HEX >= 0x030B00A2 - #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 - #if PY_VERSION_HEX >= 0x030B00A4 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #elif !defined(CYTHON_FAST_THREAD_STATE) - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL (PY_VERSION_HEX < 0x030A0000) - #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) && (PY_VERSION_HEX < 0x030C00A5)) - #endif - #if PY_VERSION_HEX >= 0x030B00A4 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 - #elif !defined(CYTHON_USE_EXC_INFO_STACK) - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif - #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #if PY_MAJOR_VERSION < 3 - #include "longintrepr.h" - #endif - #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 - -#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" - #define __Pyx_DefaultClassType PyType_Type -#if PY_VERSION_HEX >= 0x030B00A1 - static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int k, int l, int s, int f, - PyObject *code, PyObject *c, PyObject* n, PyObject *v, - PyObject *fv, PyObject *cell, PyObject* fn, - PyObject *name, int fline, PyObject *lnos) { - PyObject *kwds=NULL, *argcount=NULL, *posonlyargcount=NULL, *kwonlyargcount=NULL; - PyObject *nlocals=NULL, *stacksize=NULL, *flags=NULL, *replace=NULL, *call_result=NULL, *empty=NULL; - const char *fn_cstr=NULL; - const char *name_cstr=NULL; - PyCodeObject* co=NULL; - PyObject *type, *value, *traceback; - PyErr_Fetch(&type, &value, &traceback); - if (!(kwds=PyDict_New())) goto end; - if (!(argcount=PyLong_FromLong(a))) goto end; - if (PyDict_SetItemString(kwds, "co_argcount", argcount) != 0) goto end; - if (!(posonlyargcount=PyLong_FromLong(0))) goto end; - if (PyDict_SetItemString(kwds, "co_posonlyargcount", posonlyargcount) != 0) goto end; - if (!(kwonlyargcount=PyLong_FromLong(k))) goto end; - if (PyDict_SetItemString(kwds, "co_kwonlyargcount", kwonlyargcount) != 0) goto end; - if (!(nlocals=PyLong_FromLong(l))) goto end; - if (PyDict_SetItemString(kwds, "co_nlocals", nlocals) != 0) goto end; - if (!(stacksize=PyLong_FromLong(s))) goto end; - if (PyDict_SetItemString(kwds, "co_stacksize", stacksize) != 0) goto end; - if (!(flags=PyLong_FromLong(f))) goto end; - if (PyDict_SetItemString(kwds, "co_flags", flags) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_code", code) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_consts", c) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_names", n) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_varnames", v) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_freevars", fv) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_cellvars", cell) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_linetable", lnos) != 0) goto end; - if (!(fn_cstr=PyUnicode_AsUTF8AndSize(fn, NULL))) goto end; - if (!(name_cstr=PyUnicode_AsUTF8AndSize(name, NULL))) goto end; - if (!(co = PyCode_NewEmpty(fn_cstr, name_cstr, fline))) goto end; - if (!(replace = PyObject_GetAttrString((PyObject*)co, "replace"))) goto cleanup_code_too; - if (!(empty = PyTuple_New(0))) goto cleanup_code_too; // unfortunately __pyx_empty_tuple isn't available here - if (!(call_result = PyObject_Call(replace, empty, kwds))) goto cleanup_code_too; - Py_XDECREF((PyObject*)co); - co = (PyCodeObject*)call_result; - call_result = NULL; - if (0) { - cleanup_code_too: - Py_XDECREF((PyObject*)co); - co = NULL; - } - end: - Py_XDECREF(kwds); - Py_XDECREF(argcount); - Py_XDECREF(posonlyargcount); - Py_XDECREF(kwonlyargcount); - Py_XDECREF(nlocals); - Py_XDECREF(stacksize); - Py_XDECREF(replace); - Py_XDECREF(call_result); - Py_XDECREF(empty); - if (type) { - PyErr_Restore(type, value, traceback); - } - return co; - } -#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 -#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) -#else - #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) -#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 - #if PY_VERSION_HEX >= 0x030C0000 - #define __Pyx_PyUnicode_READY(op) (0) - #else - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #endif - #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 PY_VERSION_HEX >= 0x030C0000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #else - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #endif - #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 __Pyx_PyIndex_AsHash_t -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_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(WIN32) || defined(MS_WINDOWS) - #if !defined(_USE_MATH_DEFINES) - #define _USE_MATH_DEFINES - #endif -#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__fontTools__misc__bezierTools -#define __PYX_HAVE_API__fontTools__misc__bezierTools -/* Early includes */ -#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); -static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); -#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; - -/* Header.proto */ -#if !defined(CYTHON_CCOMPLEX) - #if defined(__cplusplus) - #define CYTHON_CCOMPLEX 1 - #elif defined(_Complex_I) - #define CYTHON_CCOMPLEX 1 - #else - #define CYTHON_CCOMPLEX 0 - #endif -#endif -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - #include - #else - #include - #endif -#endif -#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) - #undef _Complex_I - #define _Complex_I 1.0fj -#endif - - -static const char *__pyx_f[] = { - "Lib/fontTools/misc/bezierTools.py", -}; -/* Declarations.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - typedef ::std::complex< double > __pyx_t_double_complex; - #else - typedef double _Complex __pyx_t_double_complex; - #endif -#else - typedef struct { double real, imag; } __pyx_t_double_complex; -#endif -static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); - - -/*--- Type declarations ---*/ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr; -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr; -struct __pyx_defaults; -typedef struct __pyx_defaults __pyx_defaults; -struct __pyx_defaults { - PyObject *__pyx_arg_sqrt; -}; - -/* "fontTools/misc/bezierTools.py":507 - * - * - * def splitQuadratic(pt1, pt2, pt3, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at a given coordinate. - * - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic { - PyObject_HEAD - PyObject *__pyx_v_solutions; -}; - - -/* "fontTools/misc/bezierTools.py":546 - * a[isHorizontal], b[isHorizontal], c[isHorizontal] - where - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) # <<<<<<<<<<<<<< - * if not solutions: - * return [(pt1, pt2, pt3)] - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr { - PyObject_HEAD - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *__pyx_outer_scope; - PyObject *__pyx_v_t; -}; - - -/* "fontTools/misc/bezierTools.py":552 - * - * - * def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at a given coordinate. - * - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic { - PyObject_HEAD - PyObject *__pyx_v_solutions; -}; - - -/* "fontTools/misc/bezierTools.py":583 - * a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) # <<<<<<<<<<<<<< - * if not solutions: - * return [(pt1, pt2, pt3, pt4)] - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr { - PyObject_HEAD - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *__pyx_outer_scope; - PyObject *__pyx_v_t; -}; - - -/* "fontTools/misc/bezierTools.py":647 - * d=cython.complex, - * ) - * def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC { - PyObject_HEAD - __pyx_t_double_complex __pyx_v_a; - __pyx_t_double_complex __pyx_v_b; - __pyx_t_double_complex __pyx_v_c; - __pyx_t_double_complex __pyx_v_d; - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - __pyx_t_double_complex __pyx_v_pt4; - PyObject *__pyx_v_ts; -}; - - -/* "fontTools/misc/bezierTools.py":778 - * d1=cython.complex, - * ) - * def _splitCubicAtTC(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC { - PyObject_HEAD - __pyx_t_double_complex __pyx_v_a; - __pyx_t_double_complex __pyx_v_a1; - __pyx_t_double_complex __pyx_v_b; - __pyx_t_double_complex __pyx_v_b1; - __pyx_t_double_complex __pyx_v_c; - __pyx_t_double_complex __pyx_v_c1; - __pyx_t_double_complex __pyx_v_d; - __pyx_t_double_complex __pyx_v_d1; - double __pyx_v_delta; - double __pyx_v_delta_2; - double __pyx_v_delta_3; - PyObject *__pyx_v_i; - PyObject *__pyx_v_pt1; - PyObject *__pyx_v_pt2; - PyObject *__pyx_v_pt3; - PyObject *__pyx_v_pt4; - double __pyx_v_t1; - double __pyx_v_t1_2; - double __pyx_v_t1_3; - double __pyx_v_t2; - PyObject *__pyx_v_ts; - PyObject *__pyx_t_0; - Py_ssize_t __pyx_t_1; - PyObject *(*__pyx_t_2)(PyObject *); -}; - - -/* "fontTools/misc/bezierTools.py":1235 - * - * - * def _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t { - PyObject_HEAD - PyObject *__pyx_v_intersections; -}; - - -/* "fontTools/misc/bezierTools.py":1245 - * else: - * raise ValueError("Unknown curve degree") - * return sorted(i for i in intersections if 0.0 <= i <= 1) # <<<<<<<<<<<<<< - * - * - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr { - PyObject_HEAD - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *__pyx_outer_scope; - PyObject *__pyx_v_i; -}; - - -/* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t { - PyObject_HEAD - PyObject *__pyx_v_precision; -}; - - -/* "fontTools/misc/bezierTools.py":1449 - * - * - * def _segmentrepr(obj): # <<<<<<<<<<<<<< - * """ - * >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]]) - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr { - PyObject_HEAD - PyObject *__pyx_v_it; -}; - - -/* "fontTools/misc/bezierTools.py":1459 - * return "%g" % obj - * else: - * return "(%s)" % ", ".join(_segmentrepr(x) for x in it) # <<<<<<<<<<<<<< - * - * - */ -struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr { - PyObject_HEAD - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *__pyx_outer_scope; - PyObject *__pyx_v_x; -}; - - -/* --- 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); - -/* 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); - -/* 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) do {\ - 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);\ -} while(0) -#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} while(0) -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 - -/* 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 - -/* 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 -#if CYTHON_FAST_PYCALL - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" -#if PY_VERSION_HEX >= 0x030b00a6 - #ifndef Py_BUILD_CORE - #define Py_BUILD_CORE 1 - #endif - #include "internal/pycore_frame.h" -#endif - #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 // CYTHON_FAST_PYCALL -#endif - -/* 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 - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* IterFinish.proto */ -static CYTHON_INLINE int __Pyx_IterFinish(void); - -/* UnpackItemEndCheck.proto */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_TrueDivideObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_TrueDivideObjC(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceTrueDivide(op1, op2) : PyNumber_TrueDivide(op1, op2)) -#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); - -/* 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 - -/* WriteUnraisableException.proto */ -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename, - int full_traceback, int nogil); - -/* PyIntCompare.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_NeObjC(PyObject *op1, PyObject *op2, long intval, long inplace); - -/* 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 - -/* 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 - -/* 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 - -/* PyIntCompare.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, long intval, long inplace); - -/* None.proto */ -static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname); - -/* FetchCommonType.proto */ -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* 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 - -/* 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 - -/* PyObjectGetMethod.proto */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); - -/* PyObjectCallMethod1.proto */ -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); - -/* CoroutineBase.proto */ -typedef PyObject *(*__pyx_coroutine_body_t)(PyObject *, PyThreadState *, PyObject *); -#if CYTHON_USE_EXC_INFO_STACK -#define __Pyx_ExcInfoStruct _PyErr_StackItem -#else -typedef struct { - PyObject *exc_type; - PyObject *exc_value; - PyObject *exc_traceback; -} __Pyx_ExcInfoStruct; -#endif -typedef struct { - PyObject_HEAD - __pyx_coroutine_body_t body; - PyObject *closure; - __Pyx_ExcInfoStruct gi_exc_state; - PyObject *gi_weakreflist; - PyObject *classobj; - PyObject *yieldfrom; - PyObject *gi_name; - PyObject *gi_qualname; - PyObject *gi_modulename; - PyObject *gi_code; - PyObject *gi_frame; - int resume_label; - char is_running; -} __pyx_CoroutineObject; -static __pyx_CoroutineObject *__Pyx__Coroutine_New( - PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name); -static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( - __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name); -static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); -static int __Pyx_Coroutine_clear(PyObject *self); -static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); -static PyObject *__Pyx_Coroutine_Close(PyObject *self); -static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, PyObject *args); -#if CYTHON_USE_EXC_INFO_STACK -#define __Pyx_Coroutine_SwapException(self) -#define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) -#else -#define __Pyx_Coroutine_SwapException(self) {\ - __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ - __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ - } -#define __Pyx_Coroutine_ResetAndClearException(self) {\ - __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ - (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ - } -#endif -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ - __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) -#else -#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ - __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) -#endif -static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); -static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); - -/* 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 - -/* PatchModuleWithCoroutine.proto */ -static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code); - -/* PatchGeneratorABC.proto */ -static int __Pyx_patch_abc(void); - -/* Generator.proto */ -#define __Pyx_Generator_USED -static PyTypeObject *__pyx_GeneratorType = 0; -#define __Pyx_Generator_CheckExact(obj) (Py_TYPE(obj) == __pyx_GeneratorType) -#define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ - __Pyx__Coroutine_New(__pyx_GeneratorType, body, code, closure, name, qualname, module_name) -static PyObject *__Pyx_Generator_Next(PyObject *self); -static int __pyx_Generator_init(void); - -/* GeneratorYieldFrom.proto */ -static CYTHON_INLINE PyObject* __Pyx_Generator_Yield_From(__pyx_CoroutineObject *gen, PyObject *source); - -/* append.proto */ -static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); - -/* 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 - -/* py_abs.proto */ -#if CYTHON_USE_PYLONG_INTERNALS -static PyObject *__Pyx_PyLong_AbsNeg(PyObject *num); -#define __Pyx_PyNumber_Absolute(x)\ - ((likely(PyLong_CheckExact(x))) ?\ - (likely(Py_SIZE(x) >= 0) ? (Py_INCREF(x), (x)) : __Pyx_PyLong_AbsNeg(x)) :\ - PyNumber_Absolute(x)) -#else -#define __Pyx_PyNumber_Absolute(x) PyNumber_Absolute(x) -#endif - -/* PyFloatBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyFloat_TrueDivideObjC(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyFloat_TrueDivideObjC(op1, op2, floatval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceTrueDivide(op1, op2) : PyNumber_TrueDivide(op1, op2)) -#endif - -/* PyFloatBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyFloat_EqObjC(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyFloat_EqObjC(op1, op2, floatval, inplace, zerodivision_check)\ - (PyObject_RichCompare(op1, op2, Py_EQ)) - #endif - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* pow2.proto */ -#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None) - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_SubtractCObj(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_SubtractCObj(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2)) -#endif - -/* CythonFunctionShared.proto */ -#define __Pyx_CyFunction_USED 1 -#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 -#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 -#define __Pyx_CYFUNCTION_CCLASS 0x04 -#define __Pyx_CyFunction_GetClosure(f)\ - (((__pyx_CyFunctionObject *) (f))->func_closure) -#define __Pyx_CyFunction_GetClassObj(f)\ - (((__pyx_CyFunctionObject *) (f))->func_classobj) -#define __Pyx_CyFunction_Defaults(type, f)\ - ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) -#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ - ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) -typedef struct { - PyCFunctionObject func; -#if PY_VERSION_HEX < 0x030500A0 - PyObject *func_weakreflist; -#endif - PyObject *func_dict; - PyObject *func_name; - PyObject *func_qualname; - PyObject *func_doc; - PyObject *func_globals; - PyObject *func_code; - PyObject *func_closure; - PyObject *func_classobj; - void *defaults; - int defaults_pyobjects; - size_t defaults_size; // used by FusedFunction for copying defaults - int flags; - PyObject *defaults_tuple; - PyObject *defaults_kwdict; - PyObject *(*defaults_getter)(PyObject *); - PyObject *func_annotations; -} __pyx_CyFunctionObject; -static PyTypeObject *__pyx_CyFunctionType = 0; -#define __Pyx_CyFunction_Check(obj) (__Pyx_TypeCheck(obj, __pyx_CyFunctionType)) -static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, - int flags, PyObject* qualname, - PyObject *self, - PyObject *module, PyObject *globals, - PyObject* code); -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, - size_t size, - int pyobjects); -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, - PyObject *tuple); -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, - PyObject *dict); -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, - PyObject *dict); -static int __pyx_CyFunction_init(void); - -/* CythonFunction.proto */ -static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, - int flags, PyObject* qualname, - PyObject *closure, - PyObject *module, PyObject *globals, - PyObject* code); - -/* 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 -} - -/* pyfrozenset_new.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it); - -/* PySetContains.proto */ -static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq); - -/* 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 - -/* 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 - -/* IncludeStringH.proto */ -#include - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* 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); - -/* PyObjectCallNoArg.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); -#else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) -#endif - -/* 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); - -/* FromPy.proto */ -static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject*); - -/* ToPy.proto */ -#define __pyx_PyComplex_FromComplex(z)\ - PyComplex_FromDoubles((double)__Pyx_CREAL(z),\ - (double)__Pyx_CIMAG(z)) - -/* RealImag.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - #define __Pyx_CREAL(z) ((z).real()) - #define __Pyx_CIMAG(z) ((z).imag()) - #else - #define __Pyx_CREAL(z) (__real__(z)) - #define __Pyx_CIMAG(z) (__imag__(z)) - #endif -#else - #define __Pyx_CREAL(z) ((z).real) - #define __Pyx_CIMAG(z) ((z).imag) -#endif -#if defined(__cplusplus) && CYTHON_CCOMPLEX\ - && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) - #define __Pyx_SET_CREAL(z,x) ((z).real(x)) - #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) -#else - #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) - #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) -#endif - -/* Arithmetic.proto */ -#if CYTHON_CCOMPLEX - #define __Pyx_c_eq_double(a, b) ((a)==(b)) - #define __Pyx_c_sum_double(a, b) ((a)+(b)) - #define __Pyx_c_diff_double(a, b) ((a)-(b)) - #define __Pyx_c_prod_double(a, b) ((a)*(b)) - #define __Pyx_c_quot_double(a, b) ((a)/(b)) - #define __Pyx_c_neg_double(a) (-(a)) - #ifdef __cplusplus - #define __Pyx_c_is_zero_double(z) ((z)==(double)0) - #define __Pyx_c_conj_double(z) (::std::conj(z)) - #if 1 - #define __Pyx_c_abs_double(z) (::std::abs(z)) - #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) - #endif - #else - #define __Pyx_c_is_zero_double(z) ((z)==0) - #define __Pyx_c_conj_double(z) (conj(z)) - #if 1 - #define __Pyx_c_abs_double(z) (cabs(z)) - #define __Pyx_c_pow_double(a, b) (cpow(a, b)) - #endif - #endif -#else - static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); - static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); - #if 1 - static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); - #endif -#endif - -/* GCCDiagnostics.proto */ -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -#define __Pyx_HAS_GCC_DIAGNOSTIC -#endif - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* 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) - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - - -/* Module declarations from 'cython' */ - -/* Module declarations from 'fontTools.misc.bezierTools' */ -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr = 0; -static PyTypeObject *__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr = 0; -static CYTHON_INLINE double __pyx_f_9fontTools_4misc_11bezierTools__dot(__pyx_t_double_complex, __pyx_t_double_complex); /*proto*/ -static CYTHON_INLINE double __pyx_f_9fontTools_4misc_11bezierTools__intSecAtan(__pyx_t_double_complex); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_9fontTools_4misc_11bezierTools_calcCubicParametersC(__pyx_t_double_complex, __pyx_t_double_complex, __pyx_t_double_complex, __pyx_t_double_complex); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_9fontTools_4misc_11bezierTools_calcCubicPointsC(__pyx_t_double_complex, __pyx_t_double_complex, __pyx_t_double_complex, __pyx_t_double_complex); /*proto*/ -#define __Pyx_MODULE_NAME "fontTools.misc.bezierTools" -extern int __pyx_module_is_main_fontTools__misc__bezierTools; -int __pyx_module_is_main_fontTools__misc__bezierTools = 0; - -/* Implementation of 'fontTools.misc.bezierTools' */ -static PyObject *__pyx_builtin_AttributeError; -static PyObject *__pyx_builtin_ImportError; -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_round; -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_print; -static const char __pyx_k_Q[] = "Q"; -static const char __pyx_k_R[] = "R"; -static const char __pyx_k_a[] = "a"; -static const char __pyx_k_b[] = "b"; -static const char __pyx_k_c[] = "c"; -static const char __pyx_k_d[] = "d"; -static const char __pyx_k_e[] = "e"; -static const char __pyx_k_g[] = "%g"; -static const char __pyx_k_i[] = "i"; -static const char __pyx_k_n[] = "n"; -static const char __pyx_k_r[] = "r"; -static const char __pyx_k_s[] = "s"; -static const char __pyx_k_t[] = "t"; -static const char __pyx_k_x[] = "x"; -static const char __pyx_k_y[] = "y"; -static const char __pyx_k_DD[] = "DD"; -static const char __pyx_k_Q3[] = "Q3"; -static const char __pyx_k_R2[] = "R2"; -static const char __pyx_k__9[] = ", "; -static const char __pyx_k_a1[] = "a1"; -static const char __pyx_k_a2[] = "a2"; -static const char __pyx_k_a3[] = "a3"; -static const char __pyx_k_ax[] = "ax"; -static const char __pyx_k_ay[] = "ay"; -static const char __pyx_k_b1[] = "b1"; -static const char __pyx_k_bx[] = "bx"; -static const char __pyx_k_by[] = "by"; -static const char __pyx_k_c1[] = "c1"; -static const char __pyx_k_cx[] = "cx"; -static const char __pyx_k_cy[] = "cy"; -static const char __pyx_k_d0[] = "d0"; -static const char __pyx_k_d1[] = "d1"; -static const char __pyx_k_dx[] = "dx"; -static const char __pyx_k_dy[] = "dy"; -static const char __pyx_k_e1[] = "e1"; -static const char __pyx_k_e2[] = "e2"; -static const char __pyx_k_ex[] = "ex"; -static const char __pyx_k_ey[] = "ey"; -static const char __pyx_k_it[] = "it"; -static const char __pyx_k_p0[] = "p0"; -static const char __pyx_k_p1[] = "p1"; -static const char __pyx_k_p2[] = "p2"; -static const char __pyx_k_p3[] = "p3"; -static const char __pyx_k_pi[] = "pi"; -static const char __pyx_k_pt[] = "pt"; -static const char __pyx_k_px[] = "px"; -static const char __pyx_k_py[] = "py"; -static const char __pyx_k_s1[] = "s1"; -static const char __pyx_k_s2[] = "s2"; -static const char __pyx_k_sx[] = "sx"; -static const char __pyx_k_sy[] = "sy"; -static const char __pyx_k_t1[] = "t1"; -static const char __pyx_k_t2[] = "t2"; -static const char __pyx_k_ts[] = "ts"; -static const char __pyx_k_v0[] = "v0"; -static const char __pyx_k_v1[] = "v1"; -static const char __pyx_k_v2[] = "v2"; -static const char __pyx_k_v3[] = "v3"; -static const char __pyx_k_v4[] = "v4"; -static const char __pyx_k_x0[] = "x0"; -static const char __pyx_k_x1[] = "x1"; -static const char __pyx_k_x2[] = "x2"; -static const char __pyx_k_x3[] = "x3"; -static const char __pyx_k_x4[] = "x4"; -static const char __pyx_k_y1[] = "y1"; -static const char __pyx_k_y2[] = "y2"; -static const char __pyx_k_y3[] = "y3"; -static const char __pyx_k_y4[] = "y4"; -static const char __pyx_k_1_t[] = "_1_t"; -static const char __pyx_k_Len[] = "Len"; -static const char __pyx_k__91[] = "_"; -static const char __pyx_k_a1x[] = "a1x"; -static const char __pyx_k_a1y[] = "a1y"; -static const char __pyx_k_all[] = "__all__"; -static const char __pyx_k_ax2[] = "ax2"; -static const char __pyx_k_ax3[] = "ax3"; -static const char __pyx_k_ay2[] = "ay2"; -static const char __pyx_k_ay3[] = "ay3"; -static const char __pyx_k_b1x[] = "b1x"; -static const char __pyx_k_b1y[] = "b1y"; -static const char __pyx_k_box[] = "box"; -static const char __pyx_k_bx2[] = "bx2"; -static const char __pyx_k_by2[] = "by2"; -static const char __pyx_k_c11[] = "c11"; -static const char __pyx_k_c12[] = "c12"; -static const char __pyx_k_c1x[] = "c1x"; -static const char __pyx_k_c1y[] = "c1y"; -static const char __pyx_k_c21[] = "c21"; -static const char __pyx_k_c22[] = "c22"; -static const char __pyx_k_cos[] = "cos"; -static const char __pyx_k_d1x[] = "d1x"; -static const char __pyx_k_d1y[] = "d1y"; -static const char __pyx_k_e1x[] = "e1x"; -static const char __pyx_k_e1y[] = "e1y"; -static const char __pyx_k_e2x[] = "e2x"; -static const char __pyx_k_e2y[] = "e2y"; -static const char __pyx_k_end[] = "end"; -static const char __pyx_k_key[] = "key"; -static const char __pyx_k_mid[] = "mid"; -static const char __pyx_k_obj[] = "obj"; -static const char __pyx_k_one[] = "one"; -static const char __pyx_k_pt1[] = "pt1"; -static const char __pyx_k_pt2[] = "pt2"; -static const char __pyx_k_pt3[] = "pt3"; -static const char __pyx_k_pt4[] = "pt4"; -static const char __pyx_k_rDD[] = "rDD"; -static const char __pyx_k_rQ2[] = "rQ2"; -static const char __pyx_k_s1x[] = "s1x"; -static const char __pyx_k_s1y[] = "s1y"; -static const char __pyx_k_s2x[] = "s2x"; -static const char __pyx_k_s2y[] = "s2y"; -static const char __pyx_k_s_2[] = "(%s)"; -static const char __pyx_k_seg[] = "seg"; -static const char __pyx_k_sys[] = "sys"; -static const char __pyx_k_two[] = "two"; -static const char __pyx_k_a1_3[] = "a1_3"; -static const char __pyx_k_acos[] = "acos"; -static const char __pyx_k_arch[] = "arch"; -static const char __pyx_k_args[] = "args"; -static const char __pyx_k_exit[] = "exit"; -static const char __pyx_k_line[] = "line"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_math[] = "math"; -static const char __pyx_k_mult[] = "mult"; -static const char __pyx_k_name[] = "__name__"; -static const char __pyx_k_off1[] = "off1"; -static const char __pyx_k_off2[] = "off2"; -static const char __pyx_k_pt1x[] = "pt1x"; -static const char __pyx_k_pt1y[] = "pt1y"; -static const char __pyx_k_pt2x[] = "pt2x"; -static const char __pyx_k_pt2y[] = "pt2y"; -static const char __pyx_k_seen[] = "seen"; -static const char __pyx_k_seg1[] = "seg1"; -static const char __pyx_k_seg2[] = "seg2"; -static const char __pyx_k_send[] = "send"; -static const char __pyx_k_sqrt[] = "sqrt"; -static const char __pyx_k_t1_2[] = "t1_2"; -static const char __pyx_k_t1_3[] = "t1_3"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_1_t_2[] = "_1_t_2"; -static const char __pyx_k_R2_Q3[] = "R2_Q3"; -static const char __pyx_k_angle[] = "angle"; -static const char __pyx_k_asinh[] = "asinh"; -static const char __pyx_k_atan2[] = "atan2"; -static const char __pyx_k_close[] = "close"; -static const char __pyx_k_curve[] = "curve"; -static const char __pyx_k_delta[] = "delta"; -static const char __pyx_k_found[] = "found"; -static const char __pyx_k_midPt[] = "midPt"; -static const char __pyx_k_print[] = "print"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_roots[] = "roots"; -static const char __pyx_k_round[] = "round"; -static const char __pyx_k_scale[] = "scale"; -static const char __pyx_k_start[] = "start"; -static const char __pyx_k_theta[] = "theta"; -static const char __pyx_k_throw[] = "throw"; -static const char __pyx_k_where[] = "where"; -static const char __pyx_k_xDiff[] = "xDiff"; -static const char __pyx_k_yDiff[] = "yDiff"; -static const char __pyx_k_append[] = "append"; -static const char __pyx_k_curve1[] = "curve1"; -static const char __pyx_k_curve2[] = "curve2"; -static const char __pyx_k_cython[] = "cython"; -static const char __pyx_k_deriv3[] = "deriv3"; -static const char __pyx_k_failed[] = "failed"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_insert[] = "insert"; -static const char __pyx_k_line_t[] = "line_t"; -static const char __pyx_k_origin[] = "origin"; -static const char __pyx_k_points[] = "points"; -static const char __pyx_k_range1[] = "range1"; -static const char __pyx_k_range2[] = "range2"; -static const char __pyx_k_rotate[] = "rotate"; -static const char __pyx_k_xRoots[] = "xRoots"; -static const char __pyx_k_yRoots[] = "yRoots"; -static const char __pyx_k_2_t_1_t[] = "_2_t_1_t"; -static const char __pyx_k_bounds1[] = "bounds1"; -static const char __pyx_k_bounds2[] = "bounds2"; -static const char __pyx_k_delta_2[] = "delta_2"; -static const char __pyx_k_delta_3[] = "delta_3"; -static const char __pyx_k_doctest[] = "doctest"; -static const char __pyx_k_epsilon[] = "epsilon"; -static const char __pyx_k_genexpr[] = "genexpr"; -static const char __pyx_k_isclose[] = "isclose"; -static const char __pyx_k_segment[] = "segment"; -static const char __pyx_k_slope12[] = "slope12"; -static const char __pyx_k_slope34[] = "slope34"; -static const char __pyx_k_swapped[] = "swapped"; -static const char __pyx_k_testmod[] = "testmod"; -static const char __pyx_k_COMPILED[] = "COMPILED"; -static const char __pyx_k_Identity[] = "Identity"; -static const char __pyx_k_midpoint[] = "midpoint"; -static const char __pyx_k_origDist[] = "origDist"; -static const char __pyx_k_pointAtT[] = "pointAtT"; -static const char __pyx_k_rectArea[] = "rectArea"; -static const char __pyx_k_sectRect[] = "sectRect"; -static const char __pyx_k_segments[] = "segments"; -static const char __pyx_k_TypeError[] = "TypeError"; -static const char __pyx_k_c11_range[] = "c11_range"; -static const char __pyx_k_c12_range[] = "c12_range"; -static const char __pyx_k_c21_range[] = "c21_range"; -static const char __pyx_k_c22_range[] = "c22_range"; -static const char __pyx_k_precision[] = "precision"; -static const char __pyx_k_solutions[] = "solutions"; -static const char __pyx_k_splitLine[] = "splitLine"; -static const char __pyx_k_tolerance[] = "tolerance"; -static const char __pyx_k_translate[] = "translate"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_calcBounds[] = "calcBounds"; -static const char __pyx_k_intersects[] = "intersects"; -static const char __pyx_k_namedtuple[] = "namedtuple"; -static const char __pyx_k_solveCubic[] = "solveCubic"; -static const char __pyx_k_splitCubic[] = "splitCubic"; -static const char __pyx_k_unique_key[] = "unique_key"; -static const char __pyx_k_ImportError[] = "ImportError"; -static const char __pyx_k_collections[] = "collections"; -static const char __pyx_k_pointFinder[] = "pointFinder"; -static const char __pyx_k_segmentrepr[] = "_segmentrepr"; -static const char __pyx_k_Intersection[] = "Intersection"; -static const char __pyx_k_curve_bounds[] = "_curve_bounds"; -static const char __pyx_k_isHorizontal[] = "isHorizontal"; -static const char __pyx_k_linePointAtT[] = "linePointAtT"; -static const char __pyx_k_line_t_of_pt[] = "_line_t_of_pt"; -static const char __pyx_k_aligned_curve[] = "aligned_curve"; -static const char __pyx_k_cubicPointAtT[] = "cubicPointAtT"; -static const char __pyx_k_epsilonDigits[] = "epsilonDigits"; -static const char __pyx_k_intersections[] = "intersections"; -static const char __pyx_k_printSegments[] = "printSegments"; -static const char __pyx_k_splitCubicAtT[] = "_splitCubicAtT"; -static const char __pyx_k_unique_values[] = "unique_values"; -static const char __pyx_k_AttributeError[] = "AttributeError"; -static const char __pyx_k_cubicPointAtTC[] = "cubicPointAtTC"; -static const char __pyx_k_fontTools_misc[] = "fontTools.misc"; -static const char __pyx_k_solveQuadratic[] = "solveQuadratic"; -static const char __pyx_k_splitCubicAtTC[] = "splitCubicAtTC"; -static const char __pyx_k_splitQuadratic[] = "splitQuadratic"; -static const char __pyx_k_calcCubicBounds[] = "calcCubicBounds"; -static const char __pyx_k_calcCubicPoints[] = "calcCubicPoints"; -static const char __pyx_k_intersection_ts[] = "intersection_ts"; -static const char __pyx_k_segmentPointAtT[] = "segmentPointAtT"; -static const char __pyx_k_splitCubicAtT_2[] = "splitCubicAtT"; -static const char __pyx_k_transformPoints[] = "transformPoints"; -static const char __pyx_k_splitCubicAtTC_2[] = "_splitCubicAtTC"; -static const char __pyx_k_quadraticPointAtT[] = "quadraticPointAtT"; -static const char __pyx_k_splitQuadraticAtT[] = "_splitQuadraticAtT"; -static const char __pyx_k_calcCubicArcLength[] = "calcCubicArcLength"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_splitLine_line_450[] = "splitLine (line 450)"; -static const char __pyx_k_split_segment_at_t[] = "_split_segment_at_t"; -static const char __pyx_k_calcCubicArcLengthC[] = "calcCubicArcLengthC"; -static const char __pyx_k_calcCubicParameters[] = "calcCubicParameters"; -static const char __pyx_k_calcQuadraticBounds[] = "calcQuadraticBounds"; -static const char __pyx_k_calcQuadraticPoints[] = "calcQuadraticPoints"; -static const char __pyx_k_solveCubic_line_841[] = "solveCubic (line 841)"; -static const char __pyx_k_splitCubic_line_552[] = "splitCubic (line 552)"; -static const char __pyx_k_splitQuadraticAtT_2[] = "splitQuadraticAtT"; -static const char __pyx_k_Unknown_curve_degree[] = "Unknown curve degree"; -static const char __pyx_k_split_cubic_into_two[] = "_split_cubic_into_two"; -static const char __pyx_k_lineLineIntersections[] = "lineLineIntersections"; -static const char __pyx_k_segmentrepr_line_1449[] = "_segmentrepr (line 1449)"; -static const char __pyx_k_splitCubicIntoTwoAtTC[] = "splitCubicIntoTwoAtTC"; -static const char __pyx_k_calcQuadraticArcLength[] = "calcQuadraticArcLength"; -static const char __pyx_k_curveLineIntersections[] = "curveLineIntersections"; -static const char __pyx_k_splitCubicAtT_line_613[] = "splitCubicAtT (line 613)"; -static const char __pyx_k_calcQuadraticArcLengthC[] = "calcQuadraticArcLengthC"; -static const char __pyx_k_calcQuadraticParameters[] = "calcQuadraticParameters"; -static const char __pyx_k_curveCurveIntersections[] = "curveCurveIntersections"; -static const char __pyx_k_splitQuadratic_line_507[] = "splitQuadratic (line 507)"; -static const char __pyx_k_alignment_transformation[] = "_alignment_transformation"; -static const char __pyx_k_calcCubicBounds_line_412[] = "calcCubicBounds (line 412)"; -static const char __pyx_k_fontTools_misc_transform[] = "fontTools.misc.transform"; -static const char __pyx_k_approximateCubicArcLength[] = "approximateCubicArcLength"; -static const char __pyx_k_fontTools_misc_arrayTools[] = "fontTools.misc.arrayTools"; -static const char __pyx_k_splitCubic_locals_genexpr[] = "splitCubic..genexpr"; -static const char __pyx_k_approximateCubicArcLengthC[] = "approximateCubicArcLengthC"; -static const char __pyx_k_calcCubicArcLengthCRecurse[] = "_calcCubicArcLengthCRecurse"; -static const char __pyx_k_curve_line_intersections_t[] = "_curve_line_intersections_t"; -static const char __pyx_k_fontTools_misc_bezierTools[] = "fontTools.misc.bezierTools"; -static const char __pyx_k_segmentrepr_locals_genexpr[] = "_segmentrepr..genexpr"; -static const char __pyx_k_splitQuadraticAtT_line_589[] = "splitQuadraticAtT (line 589)"; -static const char __pyx_k_curve_curve_intersections_t[] = "_curve_curve_intersections_t"; -static const char __pyx_k_segmentSegmentIntersections[] = "segmentSegmentIntersections"; -static const char __pyx_k_calcQuadraticBounds_line_298[] = "calcQuadraticBounds (line 298)"; -static const char __pyx_k_approximateQuadraticArcLength[] = "approximateQuadraticArcLength"; -static const char __pyx_k_segmentrepr_1_2_3_2_3_4_0_1_2[] = "\n >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]])\n '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))'\n "; -static const char __pyx_k_splitQuadratic_locals_genexpr[] = "splitQuadratic..genexpr"; -static const char __pyx_k_approximateQuadraticArcLengthC[] = "approximateQuadraticArcLengthC"; -static const char __pyx_k_Approximates_the_arc_length_for[] = "Approximates the arc length for a cubic Bezier segment.\n\n Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.\n See :func:`calcCubicArcLength` for a slower but more accurate result.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n\n Returns:\n Arc length value.\n\n Example::\n\n >>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))\n 190.04332968932817\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))\n 154.8852074945903\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.\n 149.99999999999991\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.\n 136.9267662156362\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp\n 154.80848416537057\n "; -static const char __pyx_k_Calculates_the_arc_length_for_a[] = "Calculates the arc length for a quadratic Bezier segment.\n\n Args:\n pt1: Start point of the Bezier as 2D tuple.\n pt2: Handle point of the Bezier as 2D tuple.\n pt3: End point of the Bezier as 2D tuple.\n\n Returns:\n Arc length value.\n\n Example::\n\n >>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment\n 0.0\n >>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points\n 80.0\n >>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical\n 80.0\n >>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points\n 107.70329614269008\n >>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0))\n 154.02976155645263\n >>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0))\n 120.21581243984076\n >>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50))\n 102.53273816445825\n >>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside\n 66.66666666666667\n >>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back\n 40.0\n "; -static const char __pyx_k_Finds_intersections_between_two[] = "Finds intersections between two line segments.\n\n Args:\n s1, e1: Coordinates of the first line as 2D tuples.\n s2, e2: Coordinates of the second line as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n\n >>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))\n >>> len(a)\n 1\n >>> intersection = a[0]\n >>> intersection.pt\n (374.44882952482897, 313.73458370177315)\n >>> (intersection.t1, intersection.t2)\n (0.45069111555824465, 0.5408153767394238)\n "; -static const char __pyx_k_Solve_a_cubic_equation_Solves_a[] = "Solve a cubic equation.\n\n Solves *a*x*x*x + b*x*x + c*x + d = 0* where a, b, c and d are real.\n\n Args:\n a: coefficient of *x\302\263*\n b: coefficient of *x\302\262*\n c: coefficient of *x*\n d: constant term\n\n Returns:\n A list of roots. Note that the returned list is neither guaranteed to\n be sorted nor to contain unique values!\n\n Examples::\n\n >>> solveCubic(1, 1, -6, 0)\n [-3.0, -0.0, 2.0]\n >>> solveCubic(-10.0, -9.0, 48.0, -29.0)\n [-2.9, 1.0, 1.0]\n >>> solveCubic(-9.875, -9.0, 47.625, -28.75)\n [-2.911392, 1.0, 1.0]\n >>> solveCubic(1.0, -4.5, 6.75, -3.375)\n [1.5, 1.5, 1.5]\n >>> solveCubic(-12.0, 18.0, -9.0, 1.50023651123)\n [0.5, 0.5, 0.5]\n >>> solveCubic(\n ... 9.0, 0.0, 0.0, -7.62939453125e-05\n ... ) == [-0.0, -0.0, -0.0]\n True\n "; -static const char __pyx_k_Split_a_cubic_Bezier_curve_at_a[] = "Split a cubic Bezier curve at a given coordinate.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n where: Position at which to split the curve.\n isHorizontal: Direction of the ray splitting the curve. If true,\n ``where`` is interpreted as a Y coordinate; if false, then\n ``where`` is interpreted as an X coordinate.\n\n Returns:\n A list of two curve segments (each curve segment being four 2D tuples)\n if the curve was successfully split, or a list containing the original\n curve.\n\n Example::\n\n >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))\n ((0, 0), (25, 100), (75, 100), (100, 0))\n >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))\n ((0, 0), (12.5, 50), (31.25, 75), (50, 75))\n ((50, 75), (68.75, 75), (87.5, 50), (100, 0))\n >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))\n ((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))\n ((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))\n ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))\n "; -static const char __pyx_k_both_points_are_on_same_side_of[] = "_both_points_are_on_same_side_of_origin"; -static const char __pyx_k_calcQuadraticArcLength_line_151[] = "calcQuadraticArcLength (line 151)"; -static const char __pyx_k_curve_curve_intersections_t_loc[] = "_curve_curve_intersections_t..midpoint"; -static const char __pyx_k_curve_line_intersections_t_loca[] = "_curve_line_intersections_t..genexpr"; -static const char __pyx_k_lineLineIntersections_line_1147[] = "lineLineIntersections (line 1147)"; -static const char __pyx_k_Calculates_the_bounding_rectangl[] = "Calculates the bounding rectangle for a quadratic Bezier segment.\n\n Args:\n pt1: Start point of the Bezier as a 2D tuple.\n pt2: Handle point of the Bezier as a 2D tuple.\n pt3: End point of the Bezier as a 2D tuple.\n\n Returns:\n A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.\n\n Example::\n\n >>> calcQuadraticBounds((0, 0), (50, 100), (100, 0))\n (0, 0, 100, 50.0)\n >>> calcQuadraticBounds((0, 0), (100, 0), (100, 100))\n (0.0, 0.0, 100, 100)\n "; -static const char __pyx_k_Couldn_t_work_out_which_intersec[] = "Couldn't work out which intersection function to use"; -static const char __pyx_k_Finds_intersections_between_a_cu[] = "Finds intersections between a curve and a line.\n\n Args:\n curve: List of coordinates of the curve segment as 2D tuples.\n line: List of coordinates of the line segment as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n >>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ]\n >>> line = [ (25, 260), (230, 20) ]\n >>> intersections = curveLineIntersections(curve, line)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (84.9000930760723, 189.87306176459828)\n "; -static const char __pyx_k_Lib_fontTools_misc_bezierTools_p[] = "Lib/fontTools/misc/bezierTools.py"; -static const char __pyx_k_Split_a_cubic_Bezier_curve_at_on[] = "Split a cubic Bezier curve at one or more values of t.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n *ts: Positions at which to split the curve.\n\n Returns:\n A list of curve segments (each curve segment being four 2D tuples).\n\n Examples::\n\n >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))\n ((0, 0), (12.5, 50), (31.25, 75), (50, 75))\n ((50, 75), (68.75, 75), (87.5, 50), (100, 0))\n >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5, 0.75))\n ((0, 0), (12.5, 50), (31.25, 75), (50, 75))\n ((50, 75), (59.375, 75), (68.75, 68.75), (77.3438, 56.25))\n ((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0))\n "; -static const char __pyx_k_Split_a_line_at_a_given_coordina[] = "Split a line at a given coordinate.\n\n Args:\n pt1: Start point of line as 2D tuple.\n pt2: End point of line as 2D tuple.\n where: Position at which to split the line.\n isHorizontal: Direction of the ray splitting the line. If true,\n ``where`` is interpreted as a Y coordinate; if false, then\n ``where`` is interpreted as an X coordinate.\n\n Returns:\n A list of two line segments (each line segment being two 2D tuples)\n if the line was successfully split, or a list containing the original\n line.\n\n Example::\n\n >>> printSegments(splitLine((0, 0), (100, 100), 50, True))\n ((0, 0), (50, 50))\n ((50, 50), (100, 100))\n >>> printSegments(splitLine((0, 0), (100, 100), 100, True))\n ((0, 0), (100, 100))\n >>> printSegments(splitLine((0, 0), (100, 100), 0, True))\n ((0, 0), (0, 0))\n ((0, 0), (100, 100))\n >>> printSegments(splitLine((0, 0), (100, 100), 0, False))\n ((0, 0), (0, 0))\n ((0, 0), (100, 100))\n >>> printSegments(splitLine((100, 0), (0, 0), 50, False))\n ((100, 0), (50, 0))\n ((50, 0), (0, 0))\n >>> printSegments(splitLine((0, 100), (0, 0), 50, True))\n ((0, 100), (0, 50))\n ((0, 50), (0, 0))\n "; -static const char __pyx_k_Split_a_quadratic_Bezier_curve_a[] = "Split a quadratic Bezier curve at a given coordinate.\n\n Args:\n pt1,pt2,pt3: Control points of the Bezier as 2D tuples.\n where: Position at which to split the curve.\n isHorizontal: Direction of the ray splitting the curve. If true,\n ``where`` is interpreted as a Y coordinate; if false, then\n ``where`` is interpreted as an X coordinate.\n\n Returns:\n A list of two curve segments (each curve segment being three 2D tuples)\n if the curve was successfully split, or a list containing the original\n curve.\n\n Example::\n\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))\n ((0, 0), (50, 100), (100, 0))\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (75, 50), (100, 0))\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))\n ((0, 0), (12.5, 25), (25, 37.5))\n ((25, 37.5), (62.5, 75), (100, 0))\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))\n ((0, 0), (7.32233, 14.6447), (14.6447, 25))\n ((14.6447, 25), (50, 75), (85.3553, 25))\n ((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))\n >>> # XXX I'm not at all sure if the following behavior is desirable:\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (50, 50), (50, 50))\n ((50, 50), (75, 50), (100, 0))\n "; -static const char __pyx_k_approximateCubicArcLength_line_3[] = "approximateCubicArcLength (line 332)"; -static const char __pyx_k_curveCurveIntersections_line_137[] = "curveCurveIntersections (line 1373)"; -static const char __pyx_k_curveLineIntersections_line_1248[] = "curveLineIntersections (line 1248)"; -static const char __pyx_k_fontTools_misc_bezierTools_py_to[] = "fontTools.misc.bezierTools.py -- tools for working with Bezier path segments.\n"; -static const char __pyx_k_segmentSegmentIntersections_line[] = "segmentSegmentIntersections (line 1401)"; -static const char __pyx_k_Finds_intersections_between_two_2[] = "Finds intersections between two segments.\n\n Args:\n seg1: List of coordinates of the first segment as 2D tuples.\n seg2: List of coordinates of the second segment as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]\n >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]\n >>> intersections = segmentSegmentIntersections(curve1, curve2)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (81.7831487395506, 109.88904552375288)\n >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ]\n >>> line = [ (25, 260), (230, 20) ]\n >>> intersections = segmentSegmentIntersections(curve3, line)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (84.9000930760723, 189.87306176459828)\n\n "; -static const char __pyx_k_curve_curve_intersections_t_loc_2[] = "_curve_curve_intersections_t.."; -static const char __pyx_k_Calculates_the_bounding_rectangl_2[] = "Calculates the bounding rectangle for a quadratic Bezier segment.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n\n Returns:\n A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.\n\n Example::\n\n >>> calcCubicBounds((0, 0), (25, 100), (75, 100), (100, 0))\n (0, 0, 100, 75.0)\n >>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))\n (0.0, 0.0, 100, 100)\n >>> print(\"%f %f %f %f\" % calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)))\n 35.566243 0.000000 64.433757 75.000000\n "; -static const char __pyx_k_Finds_intersections_between_a_cu_2[] = "Finds intersections between a curve and a curve.\n\n Args:\n curve1: List of coordinates of the first curve segment as 2D tuples.\n curve2: List of coordinates of the second curve segment as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]\n >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]\n >>> intersections = curveCurveIntersections(curve1, curve2)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (81.7831487395506, 109.88904552375288)\n "; -static const char __pyx_k_Split_a_quadratic_Bezier_curve_a_2[] = "Split a quadratic Bezier curve at one or more values of t.\n\n Args:\n pt1,pt2,pt3: Control points of the Bezier as 2D tuples.\n *ts: Positions at which to split the curve.\n\n Returns:\n A list of curve segments (each curve segment being three 2D tuples).\n\n Examples::\n\n >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (75, 50), (100, 0))\n >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5, 0.75))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (62.5, 50), (75, 37.5))\n ((75, 37.5), (87.5, 25), (100, 0))\n "; -static PyObject *__pyx_n_s_1_t; -static PyObject *__pyx_n_s_1_t_2; -static PyObject *__pyx_n_s_2_t_1_t; -static PyObject *__pyx_kp_u_Approximates_the_arc_length_for; -static PyObject *__pyx_n_s_AttributeError; -static PyObject *__pyx_n_s_COMPILED; -static PyObject *__pyx_kp_u_Calculates_the_arc_length_for_a; -static PyObject *__pyx_kp_u_Calculates_the_bounding_rectangl; -static PyObject *__pyx_kp_u_Calculates_the_bounding_rectangl_2; -static PyObject *__pyx_kp_u_Couldn_t_work_out_which_intersec; -static PyObject *__pyx_n_s_DD; -static PyObject *__pyx_kp_u_Finds_intersections_between_a_cu; -static PyObject *__pyx_kp_u_Finds_intersections_between_a_cu_2; -static PyObject *__pyx_kp_u_Finds_intersections_between_two; -static PyObject *__pyx_kp_u_Finds_intersections_between_two_2; -static PyObject *__pyx_n_s_Identity; -static PyObject *__pyx_n_s_ImportError; -static PyObject *__pyx_n_s_Intersection; -static PyObject *__pyx_n_u_Intersection; -static PyObject *__pyx_n_s_Len; -static PyObject *__pyx_kp_s_Lib_fontTools_misc_bezierTools_p; -static PyObject *__pyx_n_s_Q; -static PyObject *__pyx_n_s_Q3; -static PyObject *__pyx_n_s_R; -static PyObject *__pyx_n_s_R2; -static PyObject *__pyx_n_s_R2_Q3; -static PyObject *__pyx_kp_u_Solve_a_cubic_equation_Solves_a; -static PyObject *__pyx_kp_u_Split_a_cubic_Bezier_curve_at_a; -static PyObject *__pyx_kp_u_Split_a_cubic_Bezier_curve_at_on; -static PyObject *__pyx_kp_u_Split_a_line_at_a_given_coordina; -static PyObject *__pyx_kp_u_Split_a_quadratic_Bezier_curve_a; -static PyObject *__pyx_kp_u_Split_a_quadratic_Bezier_curve_a_2; -static PyObject *__pyx_n_s_TypeError; -static PyObject *__pyx_kp_u_Unknown_curve_degree; -static PyObject *__pyx_n_s_ValueError; -static PyObject *__pyx_kp_u__9; -static PyObject *__pyx_n_s__91; -static PyObject *__pyx_n_s_a; -static PyObject *__pyx_n_s_a1; -static PyObject *__pyx_n_s_a1_3; -static PyObject *__pyx_n_s_a1x; -static PyObject *__pyx_n_s_a1y; -static PyObject *__pyx_n_s_a2; -static PyObject *__pyx_n_s_a3; -static PyObject *__pyx_n_s_acos; -static PyObject *__pyx_n_s_aligned_curve; -static PyObject *__pyx_n_s_alignment_transformation; -static PyObject *__pyx_n_s_all; -static PyObject *__pyx_n_s_angle; -static PyObject *__pyx_n_s_append; -static PyObject *__pyx_n_s_approximateCubicArcLength; -static PyObject *__pyx_n_u_approximateCubicArcLength; -static PyObject *__pyx_n_s_approximateCubicArcLengthC; -static PyObject *__pyx_n_u_approximateCubicArcLengthC; -static PyObject *__pyx_kp_u_approximateCubicArcLength_line_3; -static PyObject *__pyx_n_s_approximateQuadraticArcLength; -static PyObject *__pyx_n_u_approximateQuadraticArcLength; -static PyObject *__pyx_n_s_approximateQuadraticArcLengthC; -static PyObject *__pyx_n_u_approximateQuadraticArcLengthC; -static PyObject *__pyx_n_s_arch; -static PyObject *__pyx_n_s_args; -static PyObject *__pyx_n_s_asinh; -static PyObject *__pyx_n_s_atan2; -static PyObject *__pyx_n_s_ax; -static PyObject *__pyx_n_s_ax2; -static PyObject *__pyx_n_s_ax3; -static PyObject *__pyx_n_s_ay; -static PyObject *__pyx_n_s_ay2; -static PyObject *__pyx_n_s_ay3; -static PyObject *__pyx_n_s_b; -static PyObject *__pyx_n_s_b1; -static PyObject *__pyx_n_s_b1x; -static PyObject *__pyx_n_s_b1y; -static PyObject *__pyx_n_s_both_points_are_on_same_side_of; -static PyObject *__pyx_n_s_bounds1; -static PyObject *__pyx_n_s_bounds2; -static PyObject *__pyx_n_s_box; -static PyObject *__pyx_n_s_bx; -static PyObject *__pyx_n_s_bx2; -static PyObject *__pyx_n_s_by; -static PyObject *__pyx_n_s_by2; -static PyObject *__pyx_n_s_c; -static PyObject *__pyx_n_s_c1; -static PyObject *__pyx_n_s_c11; -static PyObject *__pyx_n_s_c11_range; -static PyObject *__pyx_n_s_c12; -static PyObject *__pyx_n_s_c12_range; -static PyObject *__pyx_n_s_c1x; -static PyObject *__pyx_n_s_c1y; -static PyObject *__pyx_n_s_c21; -static PyObject *__pyx_n_s_c21_range; -static PyObject *__pyx_n_s_c22; -static PyObject *__pyx_n_s_c22_range; -static PyObject *__pyx_n_s_calcBounds; -static PyObject *__pyx_n_s_calcCubicArcLength; -static PyObject *__pyx_n_u_calcCubicArcLength; -static PyObject *__pyx_n_s_calcCubicArcLengthC; -static PyObject *__pyx_n_u_calcCubicArcLengthC; -static PyObject *__pyx_n_s_calcCubicArcLengthCRecurse; -static PyObject *__pyx_n_s_calcCubicBounds; -static PyObject *__pyx_n_u_calcCubicBounds; -static PyObject *__pyx_kp_u_calcCubicBounds_line_412; -static PyObject *__pyx_n_s_calcCubicParameters; -static PyObject *__pyx_n_s_calcCubicPoints; -static PyObject *__pyx_n_s_calcQuadraticArcLength; -static PyObject *__pyx_n_u_calcQuadraticArcLength; -static PyObject *__pyx_n_s_calcQuadraticArcLengthC; -static PyObject *__pyx_n_u_calcQuadraticArcLengthC; -static PyObject *__pyx_kp_u_calcQuadraticArcLength_line_151; -static PyObject *__pyx_n_s_calcQuadraticBounds; -static PyObject *__pyx_n_u_calcQuadraticBounds; -static PyObject *__pyx_kp_u_calcQuadraticBounds_line_298; -static PyObject *__pyx_n_s_calcQuadraticParameters; -static PyObject *__pyx_n_s_calcQuadraticPoints; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_close; -static PyObject *__pyx_n_s_collections; -static PyObject *__pyx_n_s_cos; -static PyObject *__pyx_n_s_cubicPointAtT; -static PyObject *__pyx_n_u_cubicPointAtT; -static PyObject *__pyx_n_s_cubicPointAtTC; -static PyObject *__pyx_n_u_cubicPointAtTC; -static PyObject *__pyx_n_s_curve; -static PyObject *__pyx_n_s_curve1; -static PyObject *__pyx_n_s_curve2; -static PyObject *__pyx_n_s_curveCurveIntersections; -static PyObject *__pyx_n_u_curveCurveIntersections; -static PyObject *__pyx_kp_u_curveCurveIntersections_line_137; -static PyObject *__pyx_n_s_curveLineIntersections; -static PyObject *__pyx_n_u_curveLineIntersections; -static PyObject *__pyx_kp_u_curveLineIntersections_line_1248; -static PyObject *__pyx_n_s_curve_bounds; -static PyObject *__pyx_n_s_curve_curve_intersections_t; -static PyObject *__pyx_n_s_curve_curve_intersections_t_loc; -static PyObject *__pyx_n_s_curve_curve_intersections_t_loc_2; -static PyObject *__pyx_n_s_curve_line_intersections_t; -static PyObject *__pyx_n_s_curve_line_intersections_t_loca; -static PyObject *__pyx_n_s_cx; -static PyObject *__pyx_n_s_cy; -static PyObject *__pyx_n_s_cython; -static PyObject *__pyx_n_s_d; -static PyObject *__pyx_n_s_d0; -static PyObject *__pyx_n_s_d1; -static PyObject *__pyx_n_s_d1x; -static PyObject *__pyx_n_s_d1y; -static PyObject *__pyx_n_s_delta; -static PyObject *__pyx_n_s_delta_2; -static PyObject *__pyx_n_s_delta_3; -static PyObject *__pyx_n_s_deriv3; -static PyObject *__pyx_n_s_doctest; -static PyObject *__pyx_n_s_dx; -static PyObject *__pyx_n_s_dy; -static PyObject *__pyx_n_s_e; -static PyObject *__pyx_n_s_e1; -static PyObject *__pyx_n_s_e1x; -static PyObject *__pyx_n_s_e1y; -static PyObject *__pyx_n_s_e2; -static PyObject *__pyx_n_s_e2x; -static PyObject *__pyx_n_s_e2y; -static PyObject *__pyx_n_s_end; -static PyObject *__pyx_n_s_epsilon; -static PyObject *__pyx_n_s_epsilonDigits; -static PyObject *__pyx_n_s_ex; -static PyObject *__pyx_n_s_exit; -static PyObject *__pyx_n_s_ey; -static PyObject *__pyx_n_s_failed; -static PyObject *__pyx_n_s_fontTools_misc; -static PyObject *__pyx_n_s_fontTools_misc_arrayTools; -static PyObject *__pyx_n_s_fontTools_misc_bezierTools; -static PyObject *__pyx_n_s_fontTools_misc_transform; -static PyObject *__pyx_n_s_found; -static PyObject *__pyx_kp_u_g; -static PyObject *__pyx_n_s_genexpr; -static PyObject *__pyx_n_s_i; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_insert; -static PyObject *__pyx_n_s_intersection_ts; -static PyObject *__pyx_n_s_intersections; -static PyObject *__pyx_n_s_intersects; -static PyObject *__pyx_n_s_isHorizontal; -static PyObject *__pyx_n_s_isclose; -static PyObject *__pyx_n_s_it; -static PyObject *__pyx_n_s_key; -static PyObject *__pyx_n_s_line; -static PyObject *__pyx_n_s_lineLineIntersections; -static PyObject *__pyx_n_u_lineLineIntersections; -static PyObject *__pyx_kp_u_lineLineIntersections_line_1147; -static PyObject *__pyx_n_s_linePointAtT; -static PyObject *__pyx_n_u_linePointAtT; -static PyObject *__pyx_n_s_line_t; -static PyObject *__pyx_n_s_line_t_of_pt; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_u_main; -static PyObject *__pyx_n_s_math; -static PyObject *__pyx_n_s_mid; -static PyObject *__pyx_n_s_midPt; -static PyObject *__pyx_n_s_midpoint; -static PyObject *__pyx_n_s_mult; -static PyObject *__pyx_n_s_n; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_namedtuple; -static PyObject *__pyx_n_s_obj; -static PyObject *__pyx_n_s_off1; -static PyObject *__pyx_n_s_off2; -static PyObject *__pyx_n_s_one; -static PyObject *__pyx_n_s_origDist; -static PyObject *__pyx_n_s_origin; -static PyObject *__pyx_n_s_p0; -static PyObject *__pyx_n_s_p1; -static PyObject *__pyx_n_s_p2; -static PyObject *__pyx_n_s_p3; -static PyObject *__pyx_n_s_pi; -static PyObject *__pyx_n_s_pointAtT; -static PyObject *__pyx_n_s_pointFinder; -static PyObject *__pyx_n_s_points; -static PyObject *__pyx_n_s_precision; -static PyObject *__pyx_n_s_print; -static PyObject *__pyx_n_s_printSegments; -static PyObject *__pyx_n_s_pt; -static PyObject *__pyx_n_u_pt; -static PyObject *__pyx_n_s_pt1; -static PyObject *__pyx_n_s_pt1x; -static PyObject *__pyx_n_s_pt1y; -static PyObject *__pyx_n_s_pt2; -static PyObject *__pyx_n_s_pt2x; -static PyObject *__pyx_n_s_pt2y; -static PyObject *__pyx_n_s_pt3; -static PyObject *__pyx_n_s_pt4; -static PyObject *__pyx_n_s_px; -static PyObject *__pyx_n_s_py; -static PyObject *__pyx_n_s_quadraticPointAtT; -static PyObject *__pyx_n_u_quadraticPointAtT; -static PyObject *__pyx_n_s_r; -static PyObject *__pyx_n_s_rDD; -static PyObject *__pyx_n_s_rQ2; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_range1; -static PyObject *__pyx_n_s_range2; -static PyObject *__pyx_n_s_rectArea; -static PyObject *__pyx_n_s_roots; -static PyObject *__pyx_n_s_rotate; -static PyObject *__pyx_n_s_round; -static PyObject *__pyx_n_s_s; -static PyObject *__pyx_n_s_s1; -static PyObject *__pyx_n_s_s1x; -static PyObject *__pyx_n_s_s1y; -static PyObject *__pyx_n_s_s2; -static PyObject *__pyx_n_s_s2x; -static PyObject *__pyx_n_s_s2y; -static PyObject *__pyx_kp_u_s_2; -static PyObject *__pyx_n_s_scale; -static PyObject *__pyx_n_s_sectRect; -static PyObject *__pyx_n_s_seen; -static PyObject *__pyx_n_s_seg; -static PyObject *__pyx_n_s_seg1; -static PyObject *__pyx_n_s_seg2; -static PyObject *__pyx_n_s_segment; -static PyObject *__pyx_n_s_segmentPointAtT; -static PyObject *__pyx_n_u_segmentPointAtT; -static PyObject *__pyx_n_s_segmentSegmentIntersections; -static PyObject *__pyx_n_u_segmentSegmentIntersections; -static PyObject *__pyx_kp_u_segmentSegmentIntersections_line; -static PyObject *__pyx_n_s_segmentrepr; -static PyObject *__pyx_kp_u_segmentrepr_1_2_3_2_3_4_0_1_2; -static PyObject *__pyx_kp_u_segmentrepr_line_1449; -static PyObject *__pyx_n_s_segmentrepr_locals_genexpr; -static PyObject *__pyx_n_s_segments; -static PyObject *__pyx_n_s_send; -static PyObject *__pyx_n_s_slope12; -static PyObject *__pyx_n_s_slope34; -static PyObject *__pyx_n_s_solutions; -static PyObject *__pyx_n_s_solveCubic; -static PyObject *__pyx_n_u_solveCubic; -static PyObject *__pyx_kp_u_solveCubic_line_841; -static PyObject *__pyx_n_s_solveQuadratic; -static PyObject *__pyx_n_u_solveQuadratic; -static PyObject *__pyx_n_s_splitCubic; -static PyObject *__pyx_n_u_splitCubic; -static PyObject *__pyx_n_s_splitCubicAtT; -static PyObject *__pyx_n_s_splitCubicAtTC; -static PyObject *__pyx_n_u_splitCubicAtTC; -static PyObject *__pyx_n_s_splitCubicAtTC_2; -static PyObject *__pyx_n_s_splitCubicAtT_2; -static PyObject *__pyx_n_u_splitCubicAtT_2; -static PyObject *__pyx_kp_u_splitCubicAtT_line_613; -static PyObject *__pyx_n_s_splitCubicIntoTwoAtTC; -static PyObject *__pyx_n_u_splitCubicIntoTwoAtTC; -static PyObject *__pyx_kp_u_splitCubic_line_552; -static PyObject *__pyx_n_s_splitCubic_locals_genexpr; -static PyObject *__pyx_n_s_splitLine; -static PyObject *__pyx_n_u_splitLine; -static PyObject *__pyx_kp_u_splitLine_line_450; -static PyObject *__pyx_n_s_splitQuadratic; -static PyObject *__pyx_n_u_splitQuadratic; -static PyObject *__pyx_n_s_splitQuadraticAtT; -static PyObject *__pyx_n_s_splitQuadraticAtT_2; -static PyObject *__pyx_n_u_splitQuadraticAtT_2; -static PyObject *__pyx_kp_u_splitQuadraticAtT_line_589; -static PyObject *__pyx_kp_u_splitQuadratic_line_507; -static PyObject *__pyx_n_s_splitQuadratic_locals_genexpr; -static PyObject *__pyx_n_s_split_cubic_into_two; -static PyObject *__pyx_n_s_split_segment_at_t; -static PyObject *__pyx_n_s_sqrt; -static PyObject *__pyx_n_s_start; -static PyObject *__pyx_n_s_swapped; -static PyObject *__pyx_n_s_sx; -static PyObject *__pyx_n_s_sy; -static PyObject *__pyx_n_s_sys; -static PyObject *__pyx_n_s_t; -static PyObject *__pyx_n_s_t1; -static PyObject *__pyx_n_u_t1; -static PyObject *__pyx_n_s_t1_2; -static PyObject *__pyx_n_s_t1_3; -static PyObject *__pyx_n_s_t2; -static PyObject *__pyx_n_u_t2; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_testmod; -static PyObject *__pyx_n_s_theta; -static PyObject *__pyx_n_s_throw; -static PyObject *__pyx_n_s_tolerance; -static PyObject *__pyx_n_s_transformPoints; -static PyObject *__pyx_n_s_translate; -static PyObject *__pyx_n_s_ts; -static PyObject *__pyx_n_s_two; -static PyObject *__pyx_n_s_unique_key; -static PyObject *__pyx_n_s_unique_values; -static PyObject *__pyx_n_s_v0; -static PyObject *__pyx_n_s_v1; -static PyObject *__pyx_n_s_v2; -static PyObject *__pyx_n_s_v3; -static PyObject *__pyx_n_s_v4; -static PyObject *__pyx_n_s_where; -static PyObject *__pyx_n_s_x; -static PyObject *__pyx_n_s_x0; -static PyObject *__pyx_n_s_x1; -static PyObject *__pyx_n_s_x2; -static PyObject *__pyx_n_s_x3; -static PyObject *__pyx_n_s_x4; -static PyObject *__pyx_n_s_xDiff; -static PyObject *__pyx_n_s_xRoots; -static PyObject *__pyx_n_s_y; -static PyObject *__pyx_n_s_y1; -static PyObject *__pyx_n_s_y2; -static PyObject *__pyx_n_s_y3; -static PyObject *__pyx_n_s_y4; -static PyObject *__pyx_n_s_yDiff; -static PyObject *__pyx_n_s_yRoots; -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_calcCubicArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_tolerance); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_2_split_cubic_into_two(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_p0, PyObject *__pyx_v_p1, PyObject *__pyx_v_p2, PyObject *__pyx_v_p3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_4_calcCubicArcLengthCRecurse(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_mult, __pyx_t_double_complex __pyx_v_p0, __pyx_t_double_complex __pyx_v_p1, __pyx_t_double_complex __pyx_v_p2, __pyx_t_double_complex __pyx_v_p3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_6calcCubicArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, double __pyx_v_tolerance); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_8calcQuadraticArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_10calcQuadraticArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_12approximateQuadraticArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_14approximateQuadraticArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_16calcQuadraticBounds(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_18approximateCubicArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_20approximateCubicArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_22calcCubicBounds(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_24splitLine(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_where, PyObject *__pyx_v_isHorizontal); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_14splitQuadratic_genexpr(PyObject *__pyx_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_26splitQuadratic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_where, PyObject *__pyx_v_isHorizontal); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_10splitCubic_genexpr(PyObject *__pyx_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_28splitCubic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_where, PyObject *__pyx_v_isHorizontal); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_30splitQuadraticAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_32splitCubicAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_34splitCubicAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_37splitCubicIntoTwoAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, double __pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_39_splitQuadraticAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_41_splitCubicAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_43_splitCubicAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_a, __pyx_t_double_complex __pyx_v_b, __pyx_t_double_complex __pyx_v_c, __pyx_t_double_complex __pyx_v_d, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_94__defaults__(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_46solveQuadratic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_sqrt); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_48solveCubic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_50calcQuadraticParameters(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_52calcCubicParameters(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_54calcQuadraticPoints(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_56calcCubicPoints(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_58linePointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_60quadraticPointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_62cubicPointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_64cubicPointAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, double __pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_66segmentPointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_seg, PyObject *__pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_68_line_t_of_pt(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_s, PyObject *__pyx_v_e, PyObject *__pyx_v_pt); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_70_both_points_are_on_same_side_of_origin(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_origin); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_72lineLineIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_s1, PyObject *__pyx_v_e1, PyObject *__pyx_v_s2, PyObject *__pyx_v_e2); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_74_alignment_transformation(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_segment); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_genexpr(PyObject *__pyx_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_76_curve_line_intersections_t(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve, PyObject *__pyx_v_line); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_78curveLineIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve, PyObject *__pyx_v_line); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_80_curve_bounds(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_82_split_segment_at_t(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c, PyObject *__pyx_v_t); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_r); /* proto */ -static PyObject *__pyx_lambda_funcdef_lambda3(PyObject *__pyx_self, PyObject *__pyx_v_ts); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_84_curve_curve_intersections_t(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve1, PyObject *__pyx_v_curve2, PyObject *__pyx_v_precision, PyObject *__pyx_v_range1, PyObject *__pyx_v_range2); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_86curveCurveIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve1, PyObject *__pyx_v_curve2); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_88segmentSegmentIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_seg1, PyObject *__pyx_v_seg2); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_12_segmentrepr_genexpr(PyObject *__pyx_self); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_90_segmentrepr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj); /* proto */ -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_92printSegments(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_segments); /* proto */ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_float_0_0; -static PyObject *__pyx_float_0_5; -static PyObject *__pyx_float_1_0; -static PyObject *__pyx_float_2_0; -static PyObject *__pyx_float_3_0; -static PyObject *__pyx_float_4_0; -static PyObject *__pyx_float_9_0; -static PyObject *__pyx_float_1eneg_3; -static PyObject *__pyx_float_27_0; -static PyObject *__pyx_float_54_0; -static PyObject *__pyx_float_0_005; -static PyObject *__pyx_float_0_125; -static PyObject *__pyx_float_1eneg_10; -static PyObject *__pyx_float_neg_2_0; -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; -static PyObject *__pyx_int_3; -static PyObject *__pyx_int_6; -static PyObject *__pyx_int_neg_1; -static PyObject *__pyx_codeobj_; -static PyObject *__pyx_tuple__2; -static PyObject *__pyx_tuple__4; -static PyObject *__pyx_tuple__5; -static PyObject *__pyx_tuple__6; -static PyObject *__pyx_tuple__8; -static PyObject *__pyx_tuple__10; -static PyObject *__pyx_tuple__12; -static PyObject *__pyx_tuple__13; -static PyObject *__pyx_tuple__15; -static PyObject *__pyx_tuple__17; -static PyObject *__pyx_tuple__19; -static PyObject *__pyx_tuple__21; -static PyObject *__pyx_tuple__23; -static PyObject *__pyx_tuple__25; -static PyObject *__pyx_tuple__27; -static PyObject *__pyx_tuple__29; -static PyObject *__pyx_tuple__31; -static PyObject *__pyx_tuple__33; -static PyObject *__pyx_tuple__35; -static PyObject *__pyx_tuple__37; -static PyObject *__pyx_tuple__39; -static PyObject *__pyx_tuple__41; -static PyObject *__pyx_tuple__43; -static PyObject *__pyx_tuple__45; -static PyObject *__pyx_tuple__46; -static PyObject *__pyx_tuple__48; -static PyObject *__pyx_tuple__50; -static PyObject *__pyx_tuple__52; -static PyObject *__pyx_tuple__53; -static PyObject *__pyx_tuple__55; -static PyObject *__pyx_tuple__57; -static PyObject *__pyx_tuple__59; -static PyObject *__pyx_tuple__61; -static PyObject *__pyx_tuple__63; -static PyObject *__pyx_tuple__65; -static PyObject *__pyx_tuple__67; -static PyObject *__pyx_tuple__69; -static PyObject *__pyx_tuple__71; -static PyObject *__pyx_tuple__73; -static PyObject *__pyx_tuple__75; -static PyObject *__pyx_tuple__77; -static PyObject *__pyx_tuple__79; -static PyObject *__pyx_tuple__81; -static PyObject *__pyx_tuple__83; -static PyObject *__pyx_tuple__85; -static PyObject *__pyx_tuple__87; -static PyObject *__pyx_tuple__89; -static PyObject *__pyx_tuple__92; -static PyObject *__pyx_tuple__94; -static PyObject *__pyx_tuple__95; -static PyObject *__pyx_tuple__97; -static PyObject *__pyx_tuple__99; -static PyObject *__pyx_codeobj__3; -static PyObject *__pyx_codeobj__7; -static PyObject *__pyx_tuple__101; -static PyObject *__pyx_codeobj__11; -static PyObject *__pyx_codeobj__14; -static PyObject *__pyx_codeobj__16; -static PyObject *__pyx_codeobj__18; -static PyObject *__pyx_codeobj__20; -static PyObject *__pyx_codeobj__22; -static PyObject *__pyx_codeobj__24; -static PyObject *__pyx_codeobj__26; -static PyObject *__pyx_codeobj__28; -static PyObject *__pyx_codeobj__30; -static PyObject *__pyx_codeobj__32; -static PyObject *__pyx_codeobj__34; -static PyObject *__pyx_codeobj__36; -static PyObject *__pyx_codeobj__38; -static PyObject *__pyx_codeobj__40; -static PyObject *__pyx_codeobj__42; -static PyObject *__pyx_codeobj__44; -static PyObject *__pyx_codeobj__47; -static PyObject *__pyx_codeobj__49; -static PyObject *__pyx_codeobj__51; -static PyObject *__pyx_codeobj__54; -static PyObject *__pyx_codeobj__56; -static PyObject *__pyx_codeobj__58; -static PyObject *__pyx_codeobj__60; -static PyObject *__pyx_codeobj__62; -static PyObject *__pyx_codeobj__64; -static PyObject *__pyx_codeobj__66; -static PyObject *__pyx_codeobj__68; -static PyObject *__pyx_codeobj__70; -static PyObject *__pyx_codeobj__72; -static PyObject *__pyx_codeobj__74; -static PyObject *__pyx_codeobj__76; -static PyObject *__pyx_codeobj__78; -static PyObject *__pyx_codeobj__80; -static PyObject *__pyx_codeobj__82; -static PyObject *__pyx_codeobj__84; -static PyObject *__pyx_codeobj__86; -static PyObject *__pyx_codeobj__88; -static PyObject *__pyx_codeobj__90; -static PyObject *__pyx_codeobj__93; -static PyObject *__pyx_codeobj__96; -static PyObject *__pyx_codeobj__98; -static PyObject *__pyx_codeobj__100; -static PyObject *__pyx_codeobj__102; -/* Late includes */ - -/* "fontTools/misc/bezierTools.py":56 - * - * - * def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_1calcCubicArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_calcCubicArcLength[] = "calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005)\nCalculates the arc length for a cubic Bezier segment.\n\n Whereas :func:`approximateCubicArcLength` approximates the length, this\n function calculates it by \"measuring\", recursively dividing the curve\n until the divided segments are shorter than ``tolerance``.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n tolerance: Controls the precision of the calcuation.\n\n Returns:\n Arc length value.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_1calcCubicArcLength = {"calcCubicArcLength", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_1calcCubicArcLength, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_calcCubicArcLength}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_1calcCubicArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - PyObject *__pyx_v_tolerance = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcCubicArcLength (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,&__pyx_n_s_tolerance,0}; - PyObject* values[5] = {0,0,0,0,0}; - values[4] = ((PyObject *)((PyObject*)__pyx_float_0_005)); - 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicArcLength", 0, 4, 5, 1); __PYX_ERR(0, 56, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicArcLength", 0, 4, 5, 2); __PYX_ERR(0, 56, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicArcLength", 0, 4, 5, 3); __PYX_ERR(0, 56, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_tolerance); - if (value) { values[4] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcCubicArcLength") < 0)) __PYX_ERR(0, 56, __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); - 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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - __pyx_v_tolerance = values[4]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcCubicArcLength", 0, 4, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 56, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_calcCubicArcLength(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_tolerance); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_calcCubicArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_tolerance) { - 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicArcLength", 0); - - /* "fontTools/misc/bezierTools.py":70 - * Arc length value. - * """ - * return calcCubicArcLengthC( # <<<<<<<<<<<<<< - * complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4), tolerance - * ) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicArcLengthC); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":71 - * """ - * return calcCubicArcLengthC( - * complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4), tolerance # <<<<<<<<<<<<<< - * ) - * - */ - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[6] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7, __pyx_v_tolerance}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 5+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[6] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7, __pyx_v_tolerance}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 5+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(5+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 2+__pyx_t_8, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_9, 3+__pyx_t_8, __pyx_t_7); - __Pyx_INCREF(__pyx_v_tolerance); - __Pyx_GIVEREF(__pyx_v_tolerance); - PyTuple_SET_ITEM(__pyx_t_9, 4+__pyx_t_8, __pyx_v_tolerance); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":56 - * - * - * def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":75 - * - * - * def _split_cubic_into_two(p0, p1, p2, p3): # <<<<<<<<<<<<<< - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_3_split_cubic_into_two(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_2_split_cubic_into_two[] = "_split_cubic_into_two(p0, p1, p2, p3)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_3_split_cubic_into_two = {"_split_cubic_into_two", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_3_split_cubic_into_two, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_2_split_cubic_into_two}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_3_split_cubic_into_two(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_p0 = 0; - PyObject *__pyx_v_p1 = 0; - PyObject *__pyx_v_p2 = 0; - PyObject *__pyx_v_p3 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_split_cubic_into_two (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_p0,&__pyx_n_s_p1,&__pyx_n_s_p2,&__pyx_n_s_p3,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_p0)) != 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_p1)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_split_cubic_into_two", 1, 4, 4, 1); __PYX_ERR(0, 75, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_p2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_split_cubic_into_two", 1, 4, 4, 2); __PYX_ERR(0, 75, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_p3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_split_cubic_into_two", 1, 4, 4, 3); __PYX_ERR(0, 75, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_split_cubic_into_two") < 0)) __PYX_ERR(0, 75, __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_p0 = values[0]; - __pyx_v_p1 = values[1]; - __pyx_v_p2 = values[2]; - __pyx_v_p3 = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_split_cubic_into_two", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 75, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._split_cubic_into_two", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_2_split_cubic_into_two(__pyx_self, __pyx_v_p0, __pyx_v_p1, __pyx_v_p2, __pyx_v_p3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_2_split_cubic_into_two(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_p0, PyObject *__pyx_v_p1, PyObject *__pyx_v_p2, PyObject *__pyx_v_p3) { - PyObject *__pyx_v_mid = NULL; - PyObject *__pyx_v_deriv3 = 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_split_cubic_into_two", 0); - - /* "fontTools/misc/bezierTools.py":76 - * - * def _split_cubic_into_two(p0, p1, p2, p3): - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 # <<<<<<<<<<<<<< - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - * return ( - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_p1, __pyx_v_p2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_int_3, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_v_p0, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_p3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_2, __pyx_float_0_125); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_mid = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":77 - * def _split_cubic_into_two(p0, p1, p2, p3): - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 # <<<<<<<<<<<<<< - * return ( - * (p0, (p0 + p1) * 0.5, mid - deriv3, mid), - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_p3, __pyx_v_p2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Subtract(__pyx_t_1, __pyx_v_p1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_p0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_float_0_125); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_deriv3 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":78 - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - * return ( # <<<<<<<<<<<<<< - * (p0, (p0 + p1) * 0.5, mid - deriv3, mid), - * (mid, mid + deriv3, (p2 + p3) * 0.5, p3), - */ - __Pyx_XDECREF(__pyx_r); - - /* "fontTools/misc/bezierTools.py":79 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - * return ( - * (p0, (p0 + p1) * 0.5, mid - deriv3, mid), # <<<<<<<<<<<<<< - * (mid, mid + deriv3, (p2 + p3) * 0.5, p3), - * ) - */ - __pyx_t_2 = PyNumber_Add(__pyx_v_p0, __pyx_v_p1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_2, __pyx_float_0_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Subtract(__pyx_v_mid, __pyx_v_deriv3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_p0); - __Pyx_GIVEREF(__pyx_v_p0); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_p0); - __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_INCREF(__pyx_v_mid); - __Pyx_GIVEREF(__pyx_v_mid); - PyTuple_SET_ITEM(__pyx_t_3, 3, __pyx_v_mid); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":80 - * return ( - * (p0, (p0 + p1) * 0.5, mid - deriv3, mid), - * (mid, mid + deriv3, (p2 + p3) * 0.5, p3), # <<<<<<<<<<<<<< - * ) - * - */ - __pyx_t_2 = PyNumber_Add(__pyx_v_mid, __pyx_v_deriv3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_v_p2, __pyx_v_p3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_float_0_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_mid); - __Pyx_GIVEREF(__pyx_v_mid); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_mid); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_4); - __Pyx_INCREF(__pyx_v_p3); - __Pyx_GIVEREF(__pyx_v_p3); - PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_v_p3); - __pyx_t_2 = 0; - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":79 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - * return ( - * (p0, (p0 + p1) * 0.5, mid - deriv3, mid), # <<<<<<<<<<<<<< - * (mid, mid + deriv3, (p2 + p3) * 0.5, p3), - * ) - */ - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":75 - * - * - * def _split_cubic_into_two(p0, p1, p2, p3): # <<<<<<<<<<<<<< - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - */ - - /* 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("fontTools.misc.bezierTools._split_cubic_into_two", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_mid); - __Pyx_XDECREF(__pyx_v_deriv3); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":92 - * ) - * @cython.locals(mult=cython.double, arch=cython.double, box=cython.double) - * def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3): # <<<<<<<<<<<<<< - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_5_calcCubicArcLengthCRecurse(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_4_calcCubicArcLengthCRecurse[] = "_calcCubicArcLengthCRecurse(double mult, double complex p0, double complex p1, double complex p2, double complex p3)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_5_calcCubicArcLengthCRecurse = {"_calcCubicArcLengthCRecurse", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_5_calcCubicArcLengthCRecurse, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_4_calcCubicArcLengthCRecurse}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_5_calcCubicArcLengthCRecurse(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_mult; - __pyx_t_double_complex __pyx_v_p0; - __pyx_t_double_complex __pyx_v_p1; - __pyx_t_double_complex __pyx_v_p2; - __pyx_t_double_complex __pyx_v_p3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_calcCubicArcLengthCRecurse (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_mult,&__pyx_n_s_p0,&__pyx_n_s_p1,&__pyx_n_s_p2,&__pyx_n_s_p3,0}; - PyObject* values[5] = {0,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 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_mult)) != 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_p0)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_calcCubicArcLengthCRecurse", 1, 5, 5, 1); __PYX_ERR(0, 92, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_p1)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_calcCubicArcLengthCRecurse", 1, 5, 5, 2); __PYX_ERR(0, 92, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_p2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_calcCubicArcLengthCRecurse", 1, 5, 5, 3); __PYX_ERR(0, 92, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_p3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_calcCubicArcLengthCRecurse", 1, 5, 5, 4); __PYX_ERR(0, 92, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_calcCubicArcLengthCRecurse") < 0)) __PYX_ERR(0, 92, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - 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); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_mult = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_mult == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L3_error) - __pyx_v_p0 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L3_error) - __pyx_v_p1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L3_error) - __pyx_v_p2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L3_error) - __pyx_v_p3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[4]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_calcCubicArcLengthCRecurse", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 92, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._calcCubicArcLengthCRecurse", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_4_calcCubicArcLengthCRecurse(__pyx_self, __pyx_v_mult, __pyx_v_p0, __pyx_v_p1, __pyx_v_p2, __pyx_v_p3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_4_calcCubicArcLengthCRecurse(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_mult, __pyx_t_double_complex __pyx_v_p0, __pyx_t_double_complex __pyx_v_p1, __pyx_t_double_complex __pyx_v_p2, __pyx_t_double_complex __pyx_v_p3) { - double __pyx_v_arch; - double __pyx_v_box; - PyObject *__pyx_v_one = NULL; - PyObject *__pyx_v_two = NULL; - 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; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *(*__pyx_t_11)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_calcCubicArcLengthCRecurse", 0); - - /* "fontTools/misc/bezierTools.py":93 - * @cython.locals(mult=cython.double, arch=cython.double, box=cython.double) - * def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3): - * arch = abs(p0 - p3) # <<<<<<<<<<<<<< - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - * if arch * mult >= box: - */ - __pyx_v_arch = __Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p0, __pyx_v_p3)); - - /* "fontTools/misc/bezierTools.py":94 - * def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3): - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) # <<<<<<<<<<<<<< - * if arch * mult >= box: - * return (arch + box) * 0.5 - */ - __pyx_v_box = ((__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p0, __pyx_v_p1)) + __Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p1, __pyx_v_p2))) + __Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_p2, __pyx_v_p3))); - - /* "fontTools/misc/bezierTools.py":95 - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - * if arch * mult >= box: # <<<<<<<<<<<<<< - * return (arch + box) * 0.5 - * else: - */ - __pyx_t_1 = (((__pyx_v_arch * __pyx_v_mult) >= __pyx_v_box) != 0); - if (__pyx_t_1) { - - /* "fontTools/misc/bezierTools.py":96 - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - * if arch * mult >= box: - * return (arch + box) * 0.5 # <<<<<<<<<<<<<< - * else: - * one, two = _split_cubic_into_two(p0, p1, p2, p3) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble(((__pyx_v_arch + __pyx_v_box) * 0.5)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 96, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":95 - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - * if arch * mult >= box: # <<<<<<<<<<<<<< - * return (arch + box) * 0.5 - * else: - */ - } - - /* "fontTools/misc/bezierTools.py":98 - * return (arch + box) * 0.5 - * else: - * one, two = _split_cubic_into_two(p0, p1, p2, p3) # <<<<<<<<<<<<<< - * return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse( - * mult, *two - */ - /*else*/ { - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_split_cubic_into_two); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_v_p0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __pyx_PyComplex_FromComplex(__pyx_v_p1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __pyx_PyComplex_FromComplex(__pyx_v_p2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __pyx_PyComplex_FromComplex(__pyx_v_p3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = NULL; - __pyx_t_9 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_9 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[5] = {__pyx_t_8, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_9, 4+__pyx_t_9); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[5] = {__pyx_t_8, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_9, 4+__pyx_t_9); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(4+__pyx_t_9); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_8) { - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_8); __pyx_t_8 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_9, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_9, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_9, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_10, 3+__pyx_t_9, __pyx_t_7); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - 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(0, 98, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_10 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_10 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_10); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_11 = Py_TYPE(__pyx_t_7)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_11(__pyx_t_7); if (unlikely(!__pyx_t_3)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_10 = __pyx_t_11(__pyx_t_7); if (unlikely(!__pyx_t_10)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_10); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_7), 2) < 0) __PYX_ERR(0, 98, __pyx_L1_error) - __pyx_t_11 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L5_unpacking_done; - __pyx_L4_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_11 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 98, __pyx_L1_error) - __pyx_L5_unpacking_done:; - } - __pyx_v_one = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_two = __pyx_t_10; - __pyx_t_10 = 0; - - /* "fontTools/misc/bezierTools.py":99 - * else: - * one, two = _split_cubic_into_two(p0, p1, p2, p3) - * return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse( # <<<<<<<<<<<<<< - * mult, *two - * ) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicArcLengthCRecurse); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_10 = PyFloat_FromDouble(__pyx_v_mult); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_10); - __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PySequence_Tuple(__pyx_v_one); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_t_10); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_7, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_calcCubicArcLengthCRecurse); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "fontTools/misc/bezierTools.py":100 - * one, two = _split_cubic_into_two(p0, p1, p2, p3) - * return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse( - * mult, *two # <<<<<<<<<<<<<< - * ) - * - */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_mult); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":99 - * else: - * one, two = _split_cubic_into_two(p0, p1, p2, p3) - * return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse( # <<<<<<<<<<<<<< - * mult, *two - * ) - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":100 - * one, two = _split_cubic_into_two(p0, p1, p2, p3) - * return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse( - * mult, *two # <<<<<<<<<<<<<< - * ) - * - */ - __pyx_t_2 = __Pyx_PySequence_Tuple(__pyx_v_two); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":99 - * else: - * one, two = _split_cubic_into_two(p0, p1, p2, p3) - * return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse( # <<<<<<<<<<<<<< - * mult, *two - * ) - */ - __pyx_t_6 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Add(__pyx_t_10, __pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - } - - /* "fontTools/misc/bezierTools.py":92 - * ) - * @cython.locals(mult=cython.double, arch=cython.double, box=cython.double) - * def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3): # <<<<<<<<<<<<<< - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - */ - - /* 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_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("fontTools.misc.bezierTools._calcCubicArcLengthCRecurse", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_one); - __Pyx_XDECREF(__pyx_v_two); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":115 - * mult=cython.double, - * ) - * def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_7calcCubicArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_6calcCubicArcLengthC[] = "calcCubicArcLengthC(double complex pt1, double complex pt2, double complex pt3, double complex pt4, double tolerance=0.005)\nCalculates the arc length for a cubic Bezier segment.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.\n tolerance: Controls the precision of the calcuation.\n\n Returns:\n Arc length value.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_7calcCubicArcLengthC = {"calcCubicArcLengthC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_7calcCubicArcLengthC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_6calcCubicArcLengthC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_7calcCubicArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - __pyx_t_double_complex __pyx_v_pt4; - double __pyx_v_tolerance; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcCubicArcLengthC (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,&__pyx_n_s_tolerance,0}; - PyObject* values[5] = {0,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 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicArcLengthC", 0, 4, 5, 1); __PYX_ERR(0, 115, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicArcLengthC", 0, 4, 5, 2); __PYX_ERR(0, 115, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicArcLengthC", 0, 4, 5, 3); __PYX_ERR(0, 115, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_tolerance); - if (value) { values[4] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcCubicArcLengthC") < 0)) __PYX_ERR(0, 115, __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); - 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_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 115, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 115, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 115, __pyx_L3_error) - __pyx_v_pt4 = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 115, __pyx_L3_error) - if (values[4]) { - __pyx_v_tolerance = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_tolerance == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 115, __pyx_L3_error) - } else { - __pyx_v_tolerance = ((double)((double)0.005)); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcCubicArcLengthC", 0, 4, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 115, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_6calcCubicArcLengthC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_tolerance); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_6calcCubicArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, double __pyx_v_tolerance) { - double __pyx_v_mult; - 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; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicArcLengthC", 0); - - /* "fontTools/misc/bezierTools.py":125 - * Arc length value. - * """ - * mult = 1.0 + 1.5 * tolerance # The 1.5 is a empirical hack; no math # <<<<<<<<<<<<<< - * return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4) - * - */ - __pyx_v_mult = (1.0 + (1.5 * __pyx_v_tolerance)); - - /* "fontTools/misc/bezierTools.py":126 - * """ - * mult = 1.0 + 1.5 * tolerance # The 1.5 is a empirical hack; no math - * return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicArcLengthCRecurse); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_mult); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_v_pt1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __pyx_PyComplex_FromComplex(__pyx_v_pt2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __pyx_PyComplex_FromComplex(__pyx_v_pt3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __pyx_PyComplex_FromComplex(__pyx_v_pt4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = NULL; - __pyx_t_9 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_9 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[6] = {__pyx_t_8, __pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_9, 5+__pyx_t_9); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[6] = {__pyx_t_8, __pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_9, 5+__pyx_t_9); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(5+__pyx_t_9); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_8) { - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_8); __pyx_t_8 = NULL; - } - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_9, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_9, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_9, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_10, 3+__pyx_t_9, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_10, 4+__pyx_t_9, __pyx_t_7); - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":115 - * mult=cython.double, - * ) - * def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":137 - * @cython.returns(cython.double) - * @cython.locals(v1=cython.complex, v2=cython.complex) - * def _dot(v1, v2): # <<<<<<<<<<<<<< - * return (v1 * v2.conjugate()).real - * - */ - -static CYTHON_INLINE double __pyx_f_9fontTools_4misc_11bezierTools__dot(__pyx_t_double_complex __pyx_v_v1, __pyx_t_double_complex __pyx_v_v2) { - double __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_dot", 0); - - /* "fontTools/misc/bezierTools.py":138 - * @cython.locals(v1=cython.complex, v2=cython.complex) - * def _dot(v1, v2): - * return (v1 * v2.conjugate()).real # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __Pyx_CREAL(__Pyx_c_prod_double(__pyx_v_v1, __Pyx_c_conj_double(__pyx_v_v2))); - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":137 - * @cython.returns(cython.double) - * @cython.locals(v1=cython.complex, v2=cython.complex) - * def _dot(v1, v2): # <<<<<<<<<<<<<< - * return (v1 * v2.conjugate()).real - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":145 - * @cython.returns(cython.double) - * @cython.locals(x=cython.complex) - * def _intSecAtan(x): # <<<<<<<<<<<<<< - * # In : sympy.integrate(sp.sec(sp.atan(x))) - * # Out: x*sqrt(x**2 + 1)/2 + asinh(x)/2 - */ - -static CYTHON_INLINE double __pyx_f_9fontTools_4misc_11bezierTools__intSecAtan(__pyx_t_double_complex __pyx_v_x) { - double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - __pyx_t_double_complex __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - double __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_intSecAtan", 0); - - /* "fontTools/misc/bezierTools.py":148 - * # In : sympy.integrate(sp.sec(sp.atan(x))) - * # Out: x*sqrt(x**2 + 1)/2 + asinh(x)/2 - * return x * math.sqrt(x**2 + 1) / 2 + math.asinh(x) / 2 # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_math); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __Pyx_c_sum_double(__Pyx_c_pow_double(__pyx_v_x, __pyx_t_double_complex_from_parts(2, 0)), __pyx_t_double_complex_from_parts(1, 0)); - __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_2 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_6, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_TrueDivideObjC(__pyx_t_4, __pyx_int_2, 2, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_math); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asinh); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_4 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_6, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_TrueDivideObjC(__pyx_t_4, __pyx_int_2, 2, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __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_t_7 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_7 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_7; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":145 - * @cython.returns(cython.double) - * @cython.locals(x=cython.complex) - * def _intSecAtan(x): # <<<<<<<<<<<<<< - * # In : sympy.integrate(sp.sec(sp.atan(x))) - * # Out: x*sqrt(x**2 + 1)/2 + asinh(x)/2 - */ - - /* 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_XDECREF(__pyx_t_6); - __Pyx_WriteUnraisable("fontTools.misc.bezierTools._intSecAtan", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":151 - * - * - * def calcQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_9calcQuadraticArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_8calcQuadraticArcLength[] = "calcQuadraticArcLength(pt1, pt2, pt3)\nCalculates the arc length for a quadratic Bezier segment.\n\n Args:\n pt1: Start point of the Bezier as 2D tuple.\n pt2: Handle point of the Bezier as 2D tuple.\n pt3: End point of the Bezier as 2D tuple.\n\n Returns:\n Arc length value.\n\n Example::\n\n >>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment\n 0.0\n >>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points\n 80.0\n >>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical\n 80.0\n >>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points\n 107.70329614269008\n >>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0))\n 154.02976155645263\n >>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0))\n 120.21581243984076\n >>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50))\n 102.53273816445825\n >>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside\n 66.66666666666667\n >>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back\n 40.0\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_9calcQuadraticArcLength = {"calcQuadraticArcLength", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_9calcQuadraticArcLength, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_8calcQuadraticArcLength}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_9calcQuadraticArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcQuadraticArcLength (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticArcLength", 1, 3, 3, 1); __PYX_ERR(0, 151, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticArcLength", 1, 3, 3, 2); __PYX_ERR(0, 151, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcQuadraticArcLength") < 0)) __PYX_ERR(0, 151, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcQuadraticArcLength", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 151, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_8calcQuadraticArcLength(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_8calcQuadraticArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3) { - 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; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcQuadraticArcLength", 0); - - /* "fontTools/misc/bezierTools.py":183 - * 40.0 - * """ - * return calcQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3)) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcQuadraticArcLengthC); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(3+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_8, 2+__pyx_t_7, __pyx_t_6); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":151 - * - * - * def calcQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":205 - * Len=cython.double, - * ) - * def calcQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_11calcQuadraticArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_10calcQuadraticArcLengthC[] = "calcQuadraticArcLengthC(double complex pt1, double complex pt2, double complex pt3)\nCalculates the arc length for a quadratic Bezier segment.\n\n Args:\n pt1: Start point of the Bezier as a complex number.\n pt2: Handle point of the Bezier as a complex number.\n pt3: End point of the Bezier as a complex number.\n\n Returns:\n Arc length value.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_11calcQuadraticArcLengthC = {"calcQuadraticArcLengthC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_11calcQuadraticArcLengthC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_10calcQuadraticArcLengthC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_11calcQuadraticArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcQuadraticArcLengthC (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticArcLengthC", 1, 3, 3, 1); __PYX_ERR(0, 205, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticArcLengthC", 1, 3, 3, 2); __PYX_ERR(0, 205, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcQuadraticArcLengthC") < 0)) __PYX_ERR(0, 205, __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_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 205, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 205, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 205, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcQuadraticArcLengthC", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 205, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_10calcQuadraticArcLengthC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_10calcQuadraticArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3) { - double __pyx_v_scale; - double __pyx_v_origDist; - double __pyx_v_a; - double __pyx_v_b; - double __pyx_v_x0; - double __pyx_v_x1; - double __pyx_v_Len; - __pyx_t_double_complex __pyx_v_d0; - __pyx_t_double_complex __pyx_v_d1; - __pyx_t_double_complex __pyx_v_d; - __pyx_t_double_complex __pyx_v_n; - 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; - double __pyx_t_5; - double __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcQuadraticArcLengthC", 0); - - /* "fontTools/misc/bezierTools.py":218 - * # Analytical solution to the length of a quadratic bezier. - * # Documentation: https://github.com/fonttools/fonttools/issues/3055 - * d0 = pt2 - pt1 # <<<<<<<<<<<<<< - * d1 = pt3 - pt2 - * d = d1 - d0 - */ - __pyx_v_d0 = __Pyx_c_diff_double(__pyx_v_pt2, __pyx_v_pt1); - - /* "fontTools/misc/bezierTools.py":219 - * # Documentation: https://github.com/fonttools/fonttools/issues/3055 - * d0 = pt2 - pt1 - * d1 = pt3 - pt2 # <<<<<<<<<<<<<< - * d = d1 - d0 - * n = d * 1j - */ - __pyx_v_d1 = __Pyx_c_diff_double(__pyx_v_pt3, __pyx_v_pt2); - - /* "fontTools/misc/bezierTools.py":220 - * d0 = pt2 - pt1 - * d1 = pt3 - pt2 - * d = d1 - d0 # <<<<<<<<<<<<<< - * n = d * 1j - * scale = abs(n) - */ - __pyx_v_d = __Pyx_c_diff_double(__pyx_v_d1, __pyx_v_d0); - - /* "fontTools/misc/bezierTools.py":221 - * d1 = pt3 - pt2 - * d = d1 - d0 - * n = d * 1j # <<<<<<<<<<<<<< - * scale = abs(n) - * if scale == 0.0: - */ - __pyx_v_n = __Pyx_c_prod_double(__pyx_v_d, __pyx_t_double_complex_from_parts(0, 1.0)); - - /* "fontTools/misc/bezierTools.py":222 - * d = d1 - d0 - * n = d * 1j - * scale = abs(n) # <<<<<<<<<<<<<< - * if scale == 0.0: - * return abs(pt3 - pt1) - */ - __pyx_v_scale = __Pyx_c_abs_double(__pyx_v_n); - - /* "fontTools/misc/bezierTools.py":223 - * n = d * 1j - * scale = abs(n) - * if scale == 0.0: # <<<<<<<<<<<<<< - * return abs(pt3 - pt1) - * origDist = _dot(n, d0) - */ - __pyx_t_1 = ((__pyx_v_scale == 0.0) != 0); - if (__pyx_t_1) { - - /* "fontTools/misc/bezierTools.py":224 - * scale = abs(n) - * if scale == 0.0: - * return abs(pt3 - pt1) # <<<<<<<<<<<<<< - * origDist = _dot(n, d0) - * if abs(origDist) < epsilon: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble(__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_pt3, __pyx_v_pt1))); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 224, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":223 - * n = d * 1j - * scale = abs(n) - * if scale == 0.0: # <<<<<<<<<<<<<< - * return abs(pt3 - pt1) - * origDist = _dot(n, d0) - */ - } - - /* "fontTools/misc/bezierTools.py":225 - * if scale == 0.0: - * return abs(pt3 - pt1) - * origDist = _dot(n, d0) # <<<<<<<<<<<<<< - * if abs(origDist) < epsilon: - * if _dot(d0, d1) >= 0: - */ - __pyx_v_origDist = __pyx_f_9fontTools_4misc_11bezierTools__dot(__pyx_v_n, __pyx_v_d0); - - /* "fontTools/misc/bezierTools.py":226 - * return abs(pt3 - pt1) - * origDist = _dot(n, d0) - * if abs(origDist) < epsilon: # <<<<<<<<<<<<<< - * if _dot(d0, d1) >= 0: - * return abs(pt3 - pt1) - */ - __pyx_t_2 = PyFloat_FromDouble(fabs(__pyx_v_origDist)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 226, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 226, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_t_2, __pyx_t_3, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 226, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 226, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "fontTools/misc/bezierTools.py":227 - * origDist = _dot(n, d0) - * if abs(origDist) < epsilon: - * if _dot(d0, d1) >= 0: # <<<<<<<<<<<<<< - * return abs(pt3 - pt1) - * a, b = abs(d0), abs(d1) - */ - __pyx_t_1 = ((__pyx_f_9fontTools_4misc_11bezierTools__dot(__pyx_v_d0, __pyx_v_d1) >= 0.0) != 0); - if (__pyx_t_1) { - - /* "fontTools/misc/bezierTools.py":228 - * if abs(origDist) < epsilon: - * if _dot(d0, d1) >= 0: - * return abs(pt3 - pt1) # <<<<<<<<<<<<<< - * a, b = abs(d0), abs(d1) - * return (a * a + b * b) / (a + b) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyFloat_FromDouble(__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_pt3, __pyx_v_pt1))); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":227 - * origDist = _dot(n, d0) - * if abs(origDist) < epsilon: - * if _dot(d0, d1) >= 0: # <<<<<<<<<<<<<< - * return abs(pt3 - pt1) - * a, b = abs(d0), abs(d1) - */ - } - - /* "fontTools/misc/bezierTools.py":229 - * if _dot(d0, d1) >= 0: - * return abs(pt3 - pt1) - * a, b = abs(d0), abs(d1) # <<<<<<<<<<<<<< - * return (a * a + b * b) / (a + b) - * x0 = _dot(d, d0) / origDist - */ - __pyx_t_5 = __Pyx_c_abs_double(__pyx_v_d0); - __pyx_t_6 = __Pyx_c_abs_double(__pyx_v_d1); - __pyx_v_a = __pyx_t_5; - __pyx_v_b = __pyx_t_6; - - /* "fontTools/misc/bezierTools.py":230 - * return abs(pt3 - pt1) - * a, b = abs(d0), abs(d1) - * return (a * a + b * b) / (a + b) # <<<<<<<<<<<<<< - * x0 = _dot(d, d0) / origDist - * x1 = _dot(d, d1) / origDist - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_6 = ((__pyx_v_a * __pyx_v_a) + (__pyx_v_b * __pyx_v_b)); - __pyx_t_5 = (__pyx_v_a + __pyx_v_b); - if (unlikely(__pyx_t_5 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 230, __pyx_L1_error) - } - __pyx_t_4 = PyFloat_FromDouble((__pyx_t_6 / __pyx_t_5)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 230, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":226 - * return abs(pt3 - pt1) - * origDist = _dot(n, d0) - * if abs(origDist) < epsilon: # <<<<<<<<<<<<<< - * if _dot(d0, d1) >= 0: - * return abs(pt3 - pt1) - */ - } - - /* "fontTools/misc/bezierTools.py":231 - * a, b = abs(d0), abs(d1) - * return (a * a + b * b) / (a + b) - * x0 = _dot(d, d0) / origDist # <<<<<<<<<<<<<< - * x1 = _dot(d, d1) / origDist - * Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0))) - */ - __pyx_t_5 = __pyx_f_9fontTools_4misc_11bezierTools__dot(__pyx_v_d, __pyx_v_d0); - if (unlikely(__pyx_v_origDist == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 231, __pyx_L1_error) - } - __pyx_v_x0 = (__pyx_t_5 / __pyx_v_origDist); - - /* "fontTools/misc/bezierTools.py":232 - * return (a * a + b * b) / (a + b) - * x0 = _dot(d, d0) / origDist - * x1 = _dot(d, d1) / origDist # <<<<<<<<<<<<<< - * Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0))) - * return Len - */ - __pyx_t_5 = __pyx_f_9fontTools_4misc_11bezierTools__dot(__pyx_v_d, __pyx_v_d1); - if (unlikely(__pyx_v_origDist == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 232, __pyx_L1_error) - } - __pyx_v_x1 = (__pyx_t_5 / __pyx_v_origDist); - - /* "fontTools/misc/bezierTools.py":233 - * x0 = _dot(d, d0) / origDist - * x1 = _dot(d, d1) / origDist - * Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0))) # <<<<<<<<<<<<<< - * return Len - * - */ - __pyx_t_5 = ((2.0 * (__pyx_f_9fontTools_4misc_11bezierTools__intSecAtan(__pyx_t_double_complex_from_parts(__pyx_v_x1, 0)) - __pyx_f_9fontTools_4misc_11bezierTools__intSecAtan(__pyx_t_double_complex_from_parts(__pyx_v_x0, 0)))) * __pyx_v_origDist); - __pyx_t_6 = (__pyx_v_scale * (__pyx_v_x1 - __pyx_v_x0)); - if (unlikely(__pyx_t_6 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 233, __pyx_L1_error) - } - __pyx_v_Len = fabs((__pyx_t_5 / __pyx_t_6)); - - /* "fontTools/misc/bezierTools.py":234 - * x1 = _dot(d, d1) / origDist - * Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0))) - * return Len # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyFloat_FromDouble(__pyx_v_Len); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 234, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":205 - * Len=cython.double, - * ) - * def calcQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":237 - * - * - * def approximateQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_13approximateQuadraticArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_12approximateQuadraticArcLength[] = "approximateQuadraticArcLength(pt1, pt2, pt3)\nCalculates the arc length for a quadratic Bezier segment.\n\n Uses Gauss-Legendre quadrature for a branch-free approximation.\n See :func:`calcQuadraticArcLength` for a slower but more accurate result.\n\n Args:\n pt1: Start point of the Bezier as 2D tuple.\n pt2: Handle point of the Bezier as 2D tuple.\n pt3: End point of the Bezier as 2D tuple.\n\n Returns:\n Approximate arc length value.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_13approximateQuadraticArcLength = {"approximateQuadraticArcLength", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_13approximateQuadraticArcLength, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_12approximateQuadraticArcLength}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_13approximateQuadraticArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("approximateQuadraticArcLength (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateQuadraticArcLength", 1, 3, 3, 1); __PYX_ERR(0, 237, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateQuadraticArcLength", 1, 3, 3, 2); __PYX_ERR(0, 237, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "approximateQuadraticArcLength") < 0)) __PYX_ERR(0, 237, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("approximateQuadraticArcLength", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 237, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateQuadraticArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_12approximateQuadraticArcLength(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_12approximateQuadraticArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3) { - 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; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("approximateQuadraticArcLength", 0); - - /* "fontTools/misc/bezierTools.py":251 - * Approximate arc length value. - * """ - * return approximateQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3)) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_approximateQuadraticArcLengthC); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(3+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_8, 2+__pyx_t_7, __pyx_t_6); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":237 - * - * - * def approximateQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateQuadraticArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":265 - * v2=cython.double, - * ) - * def approximateQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_15approximateQuadraticArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_14approximateQuadraticArcLengthC[] = "approximateQuadraticArcLengthC(double complex pt1, double complex pt2, double complex pt3)\nCalculates the arc length for a quadratic Bezier segment.\n\n Uses Gauss-Legendre quadrature for a branch-free approximation.\n See :func:`calcQuadraticArcLength` for a slower but more accurate result.\n\n Args:\n pt1: Start point of the Bezier as a complex number.\n pt2: Handle point of the Bezier as a complex number.\n pt3: End point of the Bezier as a complex number.\n\n Returns:\n Approximate arc length value.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_15approximateQuadraticArcLengthC = {"approximateQuadraticArcLengthC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_15approximateQuadraticArcLengthC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_14approximateQuadraticArcLengthC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_15approximateQuadraticArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("approximateQuadraticArcLengthC (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateQuadraticArcLengthC", 1, 3, 3, 1); __PYX_ERR(0, 265, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateQuadraticArcLengthC", 1, 3, 3, 2); __PYX_ERR(0, 265, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "approximateQuadraticArcLengthC") < 0)) __PYX_ERR(0, 265, __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_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 265, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 265, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 265, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("approximateQuadraticArcLengthC", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 265, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateQuadraticArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_14approximateQuadraticArcLengthC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_14approximateQuadraticArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3) { - double __pyx_v_v0; - double __pyx_v_v1; - double __pyx_v_v2; - 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("approximateQuadraticArcLengthC", 0); - - /* "fontTools/misc/bezierTools.py":287 - * # abs(BezierCurveC[2].diff(t).subs({t:T})) for T in sorted(.5, .5sqrt(3/5)/2), - * # weighted 5/18, 8/18, 5/18 respectively. - * v0 = abs( # <<<<<<<<<<<<<< - * -0.492943519233745 * pt1 + 0.430331482911935 * pt2 + 0.0626120363218102 * pt3 - * ) - */ - __pyx_v_v0 = __Pyx_c_abs_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(-0.492943519233745, 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.430331482911935, 0), __pyx_v_pt2)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.0626120363218102, 0), __pyx_v_pt3))); - - /* "fontTools/misc/bezierTools.py":290 - * -0.492943519233745 * pt1 + 0.430331482911935 * pt2 + 0.0626120363218102 * pt3 - * ) - * v1 = abs(pt3 - pt1) * 0.4444444444444444 # <<<<<<<<<<<<<< - * v2 = abs( - * -0.0626120363218102 * pt1 - 0.430331482911935 * pt2 + 0.492943519233745 * pt3 - */ - __pyx_v_v1 = (__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_pt3, __pyx_v_pt1)) * 0.4444444444444444); - - /* "fontTools/misc/bezierTools.py":291 - * ) - * v1 = abs(pt3 - pt1) * 0.4444444444444444 - * v2 = abs( # <<<<<<<<<<<<<< - * -0.0626120363218102 * pt1 - 0.430331482911935 * pt2 + 0.492943519233745 * pt3 - * ) - */ - __pyx_v_v2 = __Pyx_c_abs_double(__Pyx_c_sum_double(__Pyx_c_diff_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(-0.0626120363218102, 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.430331482911935, 0), __pyx_v_pt2)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.492943519233745, 0), __pyx_v_pt3))); - - /* "fontTools/misc/bezierTools.py":295 - * ) - * - * return v0 + v1 + v2 # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((__pyx_v_v0 + __pyx_v_v1) + __pyx_v_v2)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 295, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":265 - * v2=cython.double, - * ) - * def approximateQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateQuadraticArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":298 - * - * - * def calcQuadraticBounds(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_17calcQuadraticBounds(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_16calcQuadraticBounds[] = "calcQuadraticBounds(pt1, pt2, pt3)\nCalculates the bounding rectangle for a quadratic Bezier segment.\n\n Args:\n pt1: Start point of the Bezier as a 2D tuple.\n pt2: Handle point of the Bezier as a 2D tuple.\n pt3: End point of the Bezier as a 2D tuple.\n\n Returns:\n A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.\n\n Example::\n\n >>> calcQuadraticBounds((0, 0), (50, 100), (100, 0))\n (0, 0, 100, 50.0)\n >>> calcQuadraticBounds((0, 0), (100, 0), (100, 100))\n (0.0, 0.0, 100, 100)\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_17calcQuadraticBounds = {"calcQuadraticBounds", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_17calcQuadraticBounds, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_16calcQuadraticBounds}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_17calcQuadraticBounds(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcQuadraticBounds (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticBounds", 1, 3, 3, 1); __PYX_ERR(0, 298, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticBounds", 1, 3, 3, 2); __PYX_ERR(0, 298, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcQuadraticBounds") < 0)) __PYX_ERR(0, 298, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcQuadraticBounds", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 298, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticBounds", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_16calcQuadraticBounds(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_16calcQuadraticBounds(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3) { - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_ax2 = NULL; - PyObject *__pyx_v_ay2 = NULL; - PyObject *__pyx_v_roots = NULL; - PyObject *__pyx_v_points = NULL; - PyObject *__pyx_7genexpr__pyx_v_t = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *(*__pyx_t_7)(PyObject *); - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __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("calcQuadraticBounds", 0); - - /* "fontTools/misc/bezierTools.py":316 - * (0.0, 0.0, 100, 100) - * """ - * (ax, ay), (bx, by), (cx, cy) = calcQuadraticParameters(pt1, pt2, pt3) # <<<<<<<<<<<<<< - * ax2 = ax * 2.0 - * ay2 = ay * 2.0 - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcQuadraticParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(3+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_pt3); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 316, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_3 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_3); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_6 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - index = 2; __pyx_t_3 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 3) < 0) __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - 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(0, 316, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_8 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_6 = PyList_GET_ITEM(sequence, 0); - __pyx_t_8 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(__pyx_t_8); - #else - __pyx_t_6 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_9 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_9)->tp_iternext; - index = 0; __pyx_t_6 = __pyx_t_7(__pyx_t_9); if (unlikely(!__pyx_t_6)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - index = 1; __pyx_t_8 = __pyx_t_7(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_9), 2) < 0) __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_ax = __pyx_t_6; - __pyx_t_6 = 0; - __pyx_v_ay = __pyx_t_8; - __pyx_t_8 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_5))) || (PyList_CheckExact(__pyx_t_5))) { - PyObject* sequence = __pyx_t_5; - 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(0, 316, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_8 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_8 = PyList_GET_ITEM(sequence, 0); - __pyx_t_6 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(__pyx_t_6); - #else - __pyx_t_8 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_9 = PyObject_GetIter(__pyx_t_5); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_9)->tp_iternext; - index = 0; __pyx_t_8 = __pyx_t_7(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_8); - index = 1; __pyx_t_6 = __pyx_t_7(__pyx_t_9); if (unlikely(!__pyx_t_6)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_9), 2) < 0) __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_bx = __pyx_t_8; - __pyx_t_8 = 0; - __pyx_v_by = __pyx_t_6; - __pyx_t_6 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { - 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(0, 316, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_8 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_6 = PyList_GET_ITEM(sequence, 0); - __pyx_t_8 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(__pyx_t_8); - #else - __pyx_t_6 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_9 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 316, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_9)->tp_iternext; - index = 0; __pyx_t_6 = __pyx_t_7(__pyx_t_9); if (unlikely(!__pyx_t_6)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - index = 1; __pyx_t_8 = __pyx_t_7(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_9), 2) < 0) __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_v_cx = __pyx_t_6; - __pyx_t_6 = 0; - __pyx_v_cy = __pyx_t_8; - __pyx_t_8 = 0; - - /* "fontTools/misc/bezierTools.py":317 - * """ - * (ax, ay), (bx, by), (cx, cy) = calcQuadraticParameters(pt1, pt2, pt3) - * ax2 = ax * 2.0 # <<<<<<<<<<<<<< - * ay2 = ay * 2.0 - * roots = [] - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_ax, __pyx_float_2_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 317, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ax2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":318 - * (ax, ay), (bx, by), (cx, cy) = calcQuadraticParameters(pt1, pt2, pt3) - * ax2 = ax * 2.0 - * ay2 = ay * 2.0 # <<<<<<<<<<<<<< - * roots = [] - * if ax2 != 0: - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_ay, __pyx_float_2_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ay2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":319 - * ax2 = ax * 2.0 - * ay2 = ay * 2.0 - * roots = [] # <<<<<<<<<<<<<< - * if ax2 != 0: - * roots.append(-bx / ax2) - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 319, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_roots = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":320 - * ay2 = ay * 2.0 - * roots = [] - * if ax2 != 0: # <<<<<<<<<<<<<< - * roots.append(-bx / ax2) - * if ay2 != 0: - */ - __pyx_t_1 = __Pyx_PyInt_NeObjC(__pyx_v_ax2, __pyx_int_0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 320, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 320, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_10) { - - /* "fontTools/misc/bezierTools.py":321 - * roots = [] - * if ax2 != 0: - * roots.append(-bx / ax2) # <<<<<<<<<<<<<< - * if ay2 != 0: - * roots.append(-by / ay2) - */ - __pyx_t_1 = PyNumber_Negative(__pyx_v_bx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 321, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_v_ax2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 321, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_roots, __pyx_t_3); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 321, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":320 - * ay2 = ay * 2.0 - * roots = [] - * if ax2 != 0: # <<<<<<<<<<<<<< - * roots.append(-bx / ax2) - * if ay2 != 0: - */ - } - - /* "fontTools/misc/bezierTools.py":322 - * if ax2 != 0: - * roots.append(-bx / ax2) - * if ay2 != 0: # <<<<<<<<<<<<<< - * roots.append(-by / ay2) - * points = [ - */ - __pyx_t_3 = __Pyx_PyInt_NeObjC(__pyx_v_ay2, __pyx_int_0, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 322, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 322, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_10) { - - /* "fontTools/misc/bezierTools.py":323 - * roots.append(-bx / ax2) - * if ay2 != 0: - * roots.append(-by / ay2) # <<<<<<<<<<<<<< - * points = [ - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) - */ - __pyx_t_3 = PyNumber_Negative(__pyx_v_by); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 323, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_v_ay2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 323, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_roots, __pyx_t_1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 323, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":322 - * if ax2 != 0: - * roots.append(-bx / ax2) - * if ay2 != 0: # <<<<<<<<<<<<<< - * roots.append(-by / ay2) - * points = [ - */ - } - - /* "fontTools/misc/bezierTools.py":328 - * for t in roots - * if 0 <= t < 1 - * ] + [pt1, pt3] # <<<<<<<<<<<<<< - * return calcBounds(points) - * - */ - { /* enter inner scope */ - - /* "fontTools/misc/bezierTools.py":324 - * if ay2 != 0: - * roots.append(-by / ay2) - * points = [ # <<<<<<<<<<<<<< - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) - * for t in roots - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 324, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_1); - - /* "fontTools/misc/bezierTools.py":326 - * points = [ - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) - * for t in roots # <<<<<<<<<<<<<< - * if 0 <= t < 1 - * ] + [pt1, pt3] - */ - __pyx_t_3 = __pyx_v_roots; __Pyx_INCREF(__pyx_t_3); __pyx_t_12 = 0; - for (;;) { - if (__pyx_t_12 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_12); __Pyx_INCREF(__pyx_t_5); __pyx_t_12++; if (unlikely(0 < 0)) __PYX_ERR(0, 326, __pyx_L15_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_12); __pyx_t_12++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 326, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_XDECREF_SET(__pyx_7genexpr__pyx_v_t, __pyx_t_5); - __pyx_t_5 = 0; - - /* "fontTools/misc/bezierTools.py":327 - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) - * for t in roots - * if 0 <= t < 1 # <<<<<<<<<<<<<< - * ] + [pt1, pt3] - * return calcBounds(points) - */ - __pyx_t_5 = PyObject_RichCompare(__pyx_int_0, __pyx_7genexpr__pyx_v_t, Py_LE); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 327, __pyx_L15_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_5)) { - __Pyx_DECREF(__pyx_t_5); - __pyx_t_5 = PyObject_RichCompare(__pyx_7genexpr__pyx_v_t, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 327, __pyx_L15_error) - } - __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 327, __pyx_L15_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_10) { - - /* "fontTools/misc/bezierTools.py":325 - * roots.append(-by / ay2) - * points = [ - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) # <<<<<<<<<<<<<< - * for t in roots - * if 0 <= t < 1 - */ - __pyx_t_5 = PyNumber_Multiply(__pyx_v_ax, __pyx_7genexpr__pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_5, __pyx_7genexpr__pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Multiply(__pyx_v_bx, __pyx_7genexpr__pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_8 = PyNumber_Add(__pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(__pyx_t_8, __pyx_v_cx); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_Multiply(__pyx_v_ay, __pyx_7genexpr__pyx_v_t); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_8, __pyx_7genexpr__pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_Multiply(__pyx_v_by, __pyx_7genexpr__pyx_v_t); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_6 = PyNumber_Add(__pyx_t_2, __pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_Add(__pyx_t_6, __pyx_v_cy); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 325, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_8); - __pyx_t_5 = 0; - __pyx_t_8 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_6))) __PYX_ERR(0, 324, __pyx_L15_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":327 - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) - * for t in roots - * if 0 <= t < 1 # <<<<<<<<<<<<<< - * ] + [pt1, pt3] - * return calcBounds(points) - */ - } - - /* "fontTools/misc/bezierTools.py":326 - * points = [ - * (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) - * for t in roots # <<<<<<<<<<<<<< - * if 0 <= t < 1 - * ] + [pt1, pt3] - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_7genexpr__pyx_v_t); __pyx_7genexpr__pyx_v_t = 0; - goto __pyx_L19_exit_scope; - __pyx_L15_error:; - __Pyx_XDECREF(__pyx_7genexpr__pyx_v_t); __pyx_7genexpr__pyx_v_t = 0; - goto __pyx_L1_error; - __pyx_L19_exit_scope:; - } /* exit inner scope */ - - /* "fontTools/misc/bezierTools.py":328 - * for t in roots - * if 0 <= t < 1 - * ] + [pt1, pt3] # <<<<<<<<<<<<<< - * return calcBounds(points) - * - */ - __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 328, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyList_SET_ITEM(__pyx_t_3, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyList_SET_ITEM(__pyx_t_3, 1, __pyx_v_pt3); - __pyx_t_6 = PyNumber_Add(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 328, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_points = ((PyObject*)__pyx_t_6); - __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":329 - * if 0 <= t < 1 - * ] + [pt1, pt3] - * return calcBounds(points) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_calcBounds); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_6 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_1, __pyx_v_points) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_points); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":298 - * - * - * def calcQuadraticBounds(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticBounds", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_ax2); - __Pyx_XDECREF(__pyx_v_ay2); - __Pyx_XDECREF(__pyx_v_roots); - __Pyx_XDECREF(__pyx_v_points); - __Pyx_XDECREF(__pyx_7genexpr__pyx_v_t); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":332 - * - * - * def approximateCubicArcLength(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_19approximateCubicArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_18approximateCubicArcLength[] = "approximateCubicArcLength(pt1, pt2, pt3, pt4)\nApproximates the arc length for a cubic Bezier segment.\n\n Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.\n See :func:`calcCubicArcLength` for a slower but more accurate result.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n\n Returns:\n Arc length value.\n\n Example::\n\n >>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))\n 190.04332968932817\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))\n 154.8852074945903\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.\n 149.99999999999991\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.\n 136.9267662156362\n >>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp\n 154.80848416537057\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_19approximateCubicArcLength = {"approximateCubicArcLength", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_19approximateCubicArcLength, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_18approximateCubicArcLength}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_19approximateCubicArcLength(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("approximateCubicArcLength (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLength", 1, 4, 4, 1); __PYX_ERR(0, 332, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLength", 1, 4, 4, 2); __PYX_ERR(0, 332, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLength", 1, 4, 4, 3); __PYX_ERR(0, 332, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "approximateCubicArcLength") < 0)) __PYX_ERR(0, 332, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLength", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 332, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateCubicArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_18approximateCubicArcLength(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_18approximateCubicArcLength(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4) { - 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("approximateCubicArcLength", 0); - - /* "fontTools/misc/bezierTools.py":357 - * 154.80848416537057 - * """ - * return approximateCubicArcLengthC( # <<<<<<<<<<<<<< - * complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4) - * ) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_approximateCubicArcLengthC); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 357, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":358 - * """ - * return approximateCubicArcLengthC( - * complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4) # <<<<<<<<<<<<<< - * ) - * - */ - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_pt4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 358, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 4+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 357, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 4+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 357, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(4+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 357, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 2+__pyx_t_8, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_9, 3+__pyx_t_8, __pyx_t_7); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 357, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":332 - * - * - * def approximateCubicArcLength(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateCubicArcLength", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":376 - * v4=cython.double, - * ) - * def approximateCubicArcLengthC(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_21approximateCubicArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_20approximateCubicArcLengthC[] = "approximateCubicArcLengthC(double complex pt1, double complex pt2, double complex pt3, double complex pt4)\nApproximates the arc length for a cubic Bezier segment.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.\n\n Returns:\n Arc length value.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_21approximateCubicArcLengthC = {"approximateCubicArcLengthC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_21approximateCubicArcLengthC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_20approximateCubicArcLengthC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_21approximateCubicArcLengthC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - __pyx_t_double_complex __pyx_v_pt4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("approximateCubicArcLengthC (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLengthC", 1, 4, 4, 1); __PYX_ERR(0, 376, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLengthC", 1, 4, 4, 2); __PYX_ERR(0, 376, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLengthC", 1, 4, 4, 3); __PYX_ERR(0, 376, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "approximateCubicArcLengthC") < 0)) __PYX_ERR(0, 376, __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_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 376, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 376, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 376, __pyx_L3_error) - __pyx_v_pt4 = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 376, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("approximateCubicArcLengthC", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 376, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateCubicArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_20approximateCubicArcLengthC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_20approximateCubicArcLengthC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4) { - double __pyx_v_v0; - double __pyx_v_v1; - double __pyx_v_v2; - double __pyx_v_v3; - double __pyx_v_v4; - 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("approximateCubicArcLengthC", 0); - - /* "fontTools/misc/bezierTools.py":393 - * # abs(BezierCurveC[3].diff(t).subs({t:T})) for T in sorted(0, .5(3/7)**.5/2, .5, 1), - * # weighted 1/20, 49/180, 32/90, 49/180, 1/20 respectively. - * v0 = abs(pt2 - pt1) * 0.15 # <<<<<<<<<<<<<< - * v1 = abs( - * -0.558983582205757 * pt1 - */ - __pyx_v_v0 = (__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_pt2, __pyx_v_pt1)) * 0.15); - - /* "fontTools/misc/bezierTools.py":394 - * # weighted 1/20, 49/180, 32/90, 49/180, 1/20 respectively. - * v0 = abs(pt2 - pt1) * 0.15 - * v1 = abs( # <<<<<<<<<<<<<< - * -0.558983582205757 * pt1 - * + 0.325650248872424 * pt2 - */ - __pyx_v_v1 = __Pyx_c_abs_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(-0.558983582205757, 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.325650248872424, 0), __pyx_v_pt2)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.208983582205757, 0), __pyx_v_pt3)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.024349751127576, 0), __pyx_v_pt4))); - - /* "fontTools/misc/bezierTools.py":400 - * + 0.024349751127576 * pt4 - * ) - * v2 = abs(pt4 - pt1 + pt3 - pt2) * 0.26666666666666666 # <<<<<<<<<<<<<< - * v3 = abs( - * -0.024349751127576 * pt1 - */ - __pyx_v_v2 = (__Pyx_c_abs_double(__Pyx_c_diff_double(__Pyx_c_sum_double(__Pyx_c_diff_double(__pyx_v_pt4, __pyx_v_pt1), __pyx_v_pt3), __pyx_v_pt2)) * 0.26666666666666666); - - /* "fontTools/misc/bezierTools.py":401 - * ) - * v2 = abs(pt4 - pt1 + pt3 - pt2) * 0.26666666666666666 - * v3 = abs( # <<<<<<<<<<<<<< - * -0.024349751127576 * pt1 - * - 0.208983582205757 * pt2 - */ - __pyx_v_v3 = __Pyx_c_abs_double(__Pyx_c_sum_double(__Pyx_c_diff_double(__Pyx_c_diff_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(-0.024349751127576, 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.208983582205757, 0), __pyx_v_pt2)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.325650248872424, 0), __pyx_v_pt3)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(0.558983582205757, 0), __pyx_v_pt4))); - - /* "fontTools/misc/bezierTools.py":407 - * + 0.558983582205757 * pt4 - * ) - * v4 = abs(pt4 - pt3) * 0.15 # <<<<<<<<<<<<<< - * - * return v0 + v1 + v2 + v3 + v4 - */ - __pyx_v_v4 = (__Pyx_c_abs_double(__Pyx_c_diff_double(__pyx_v_pt4, __pyx_v_pt3)) * 0.15); - - /* "fontTools/misc/bezierTools.py":409 - * v4 = abs(pt4 - pt3) * 0.15 - * - * return v0 + v1 + v2 + v3 + v4 # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((((__pyx_v_v0 + __pyx_v_v1) + __pyx_v_v2) + __pyx_v_v3) + __pyx_v_v4)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 409, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":376 - * v4=cython.double, - * ) - * def approximateCubicArcLengthC(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("fontTools.misc.bezierTools.approximateCubicArcLengthC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":412 - * - * - * def calcCubicBounds(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_23calcCubicBounds(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_22calcCubicBounds[] = "calcCubicBounds(pt1, pt2, pt3, pt4)\nCalculates the bounding rectangle for a quadratic Bezier segment.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n\n Returns:\n A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.\n\n Example::\n\n >>> calcCubicBounds((0, 0), (25, 100), (75, 100), (100, 0))\n (0, 0, 100, 75.0)\n >>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))\n (0.0, 0.0, 100, 100)\n >>> print(\"%f %f %f %f\" % calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)))\n 35.566243 0.000000 64.433757 75.000000\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_23calcCubicBounds = {"calcCubicBounds", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_23calcCubicBounds, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_22calcCubicBounds}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_23calcCubicBounds(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcCubicBounds (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicBounds", 1, 4, 4, 1); __PYX_ERR(0, 412, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicBounds", 1, 4, 4, 2); __PYX_ERR(0, 412, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicBounds", 1, 4, 4, 3); __PYX_ERR(0, 412, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcCubicBounds") < 0)) __PYX_ERR(0, 412, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcCubicBounds", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 412, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicBounds", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_22calcCubicBounds(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_22calcCubicBounds(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4) { - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_dx = NULL; - PyObject *__pyx_v_dy = NULL; - PyObject *__pyx_v_ax3 = NULL; - PyObject *__pyx_v_ay3 = NULL; - PyObject *__pyx_v_bx2 = NULL; - PyObject *__pyx_v_by2 = NULL; - PyObject *__pyx_v_xRoots = NULL; - PyObject *__pyx_v_yRoots = NULL; - PyObject *__pyx_v_roots = NULL; - PyObject *__pyx_v_points = NULL; - PyObject *__pyx_8genexpr1__pyx_v_t = NULL; - PyObject *__pyx_8genexpr2__pyx_v_t = NULL; - PyObject *__pyx_8genexpr3__pyx_v_t = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - Py_ssize_t __pyx_t_11; - PyObject *(*__pyx_t_12)(PyObject *); - int __pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicBounds", 0); - - /* "fontTools/misc/bezierTools.py":430 - * 35.566243 0.000000 64.433757 75.000000 - * """ - * (ax, ay), (bx, by), (cx, cy), (dx, dy) = calcCubicParameters(pt1, pt2, pt3, pt4) # <<<<<<<<<<<<<< - * # calc first derivative - * ax3 = ax * 3.0 - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(4+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_pt3); - __Pyx_INCREF(__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_v_pt4); - PyTuple_SET_ITEM(__pyx_t_5, 3+__pyx_t_4, __pyx_v_pt4); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 430, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_3 = PyList_GET_ITEM(sequence, 2); - __pyx_t_6 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_5,&__pyx_t_3,&__pyx_t_6}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_5,&__pyx_t_3,&__pyx_t_6}; - __pyx_t_7 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_8(__pyx_t_7); if (unlikely(!item)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 4) < 0) __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - 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(0, 430, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_7 = PyList_GET_ITEM(sequence, 0); - __pyx_t_9 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_9); - #else - __pyx_t_7 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_10 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_10)->tp_iternext; - index = 0; __pyx_t_7 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - index = 1; __pyx_t_9 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_10), 2) < 0) __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_ax = __pyx_t_7; - __pyx_t_7 = 0; - __pyx_v_ay = __pyx_t_9; - __pyx_t_9 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_5))) || (PyList_CheckExact(__pyx_t_5))) { - PyObject* sequence = __pyx_t_5; - 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(0, 430, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_9 = PyList_GET_ITEM(sequence, 0); - __pyx_t_7 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(__pyx_t_7); - #else - __pyx_t_9 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_10 = PyObject_GetIter(__pyx_t_5); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_10)->tp_iternext; - index = 0; __pyx_t_9 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_9); - index = 1; __pyx_t_7 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_10), 2) < 0) __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_bx = __pyx_t_9; - __pyx_t_9 = 0; - __pyx_v_by = __pyx_t_7; - __pyx_t_7 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { - 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(0, 430, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_7 = PyList_GET_ITEM(sequence, 0); - __pyx_t_9 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_9); - #else - __pyx_t_7 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_10 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_10)->tp_iternext; - index = 0; __pyx_t_7 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - index = 1; __pyx_t_9 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_9); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_10), 2) < 0) __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_v_cx = __pyx_t_7; - __pyx_t_7 = 0; - __pyx_v_cy = __pyx_t_9; - __pyx_t_9 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { - PyObject* sequence = __pyx_t_6; - 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(0, 430, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_9 = PyList_GET_ITEM(sequence, 0); - __pyx_t_7 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(__pyx_t_7); - #else - __pyx_t_9 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_10 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 430, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_10)->tp_iternext; - index = 0; __pyx_t_9 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_9); - index = 1; __pyx_t_7 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_10), 2) < 0) __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L12_unpacking_done; - __pyx_L11_unpacking_failed:; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 430, __pyx_L1_error) - __pyx_L12_unpacking_done:; - } - __pyx_v_dx = __pyx_t_9; - __pyx_t_9 = 0; - __pyx_v_dy = __pyx_t_7; - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":432 - * (ax, ay), (bx, by), (cx, cy), (dx, dy) = calcCubicParameters(pt1, pt2, pt3, pt4) - * # calc first derivative - * ax3 = ax * 3.0 # <<<<<<<<<<<<<< - * ay3 = ay * 3.0 - * bx2 = bx * 2.0 - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_ax, __pyx_float_3_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 432, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ax3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":433 - * # calc first derivative - * ax3 = ax * 3.0 - * ay3 = ay * 3.0 # <<<<<<<<<<<<<< - * bx2 = bx * 2.0 - * by2 = by * 2.0 - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_ay, __pyx_float_3_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 433, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ay3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":434 - * ax3 = ax * 3.0 - * ay3 = ay * 3.0 - * bx2 = bx * 2.0 # <<<<<<<<<<<<<< - * by2 = by * 2.0 - * xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1] - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_bx, __pyx_float_2_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 434, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_bx2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":435 - * ay3 = ay * 3.0 - * bx2 = bx * 2.0 - * by2 = by * 2.0 # <<<<<<<<<<<<<< - * xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1] - * yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1] - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_by, __pyx_float_2_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 435, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_by2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":436 - * bx2 = bx * 2.0 - * by2 = by * 2.0 - * xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1] # <<<<<<<<<<<<<< - * yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1] - * roots = xRoots + yRoots - */ - { /* enter inner scope */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_solveQuadratic); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_5, __pyx_v_ax3, __pyx_v_bx2, __pyx_v_cx}; - __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_5, __pyx_v_ax3, __pyx_v_bx2, __pyx_v_cx}; - __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - { - __pyx_t_2 = PyTuple_New(3+__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_INCREF(__pyx_v_ax3); - __Pyx_GIVEREF(__pyx_v_ax3); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_4, __pyx_v_ax3); - __Pyx_INCREF(__pyx_v_bx2); - __Pyx_GIVEREF(__pyx_v_bx2); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_4, __pyx_v_bx2); - __Pyx_INCREF(__pyx_v_cx); - __Pyx_GIVEREF(__pyx_v_cx); - PyTuple_SET_ITEM(__pyx_t_2, 2+__pyx_t_4, __pyx_v_cx); - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (likely(PyList_CheckExact(__pyx_t_6)) || PyTuple_CheckExact(__pyx_t_6)) { - __pyx_t_3 = __pyx_t_6; __Pyx_INCREF(__pyx_t_3); __pyx_t_11 = 0; - __pyx_t_12 = NULL; - } else { - __pyx_t_11 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_12 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 436, __pyx_L15_error) - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - for (;;) { - if (likely(!__pyx_t_12)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_11 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_6 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_11); __Pyx_INCREF(__pyx_t_6); __pyx_t_11++; if (unlikely(0 < 0)) __PYX_ERR(0, 436, __pyx_L15_error) - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_3, __pyx_t_11); __pyx_t_11++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - } else { - if (__pyx_t_11 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_11); __Pyx_INCREF(__pyx_t_6); __pyx_t_11++; if (unlikely(0 < 0)) __PYX_ERR(0, 436, __pyx_L15_error) - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_3, __pyx_t_11); __pyx_t_11++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - } - } else { - __pyx_t_6 = __pyx_t_12(__pyx_t_3); - if (unlikely(!__pyx_t_6)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 436, __pyx_L15_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_6); - } - __Pyx_XDECREF_SET(__pyx_8genexpr1__pyx_v_t, __pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyObject_RichCompare(__pyx_int_0, __pyx_8genexpr1__pyx_v_t, Py_LE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_6)) { - __Pyx_DECREF(__pyx_t_6); - __pyx_t_6 = PyObject_RichCompare(__pyx_8genexpr1__pyx_v_t, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 436, __pyx_L15_error) - } - __pyx_t_13 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_13 < 0)) __PYX_ERR(0, 436, __pyx_L15_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (__pyx_t_13) { - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_8genexpr1__pyx_v_t))) __PYX_ERR(0, 436, __pyx_L15_error) - } - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_t); __pyx_8genexpr1__pyx_v_t = 0; - goto __pyx_L19_exit_scope; - __pyx_L15_error:; - __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_t); __pyx_8genexpr1__pyx_v_t = 0; - goto __pyx_L1_error; - __pyx_L19_exit_scope:; - } /* exit inner scope */ - __pyx_v_xRoots = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":437 - * by2 = by * 2.0 - * xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1] - * yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1] # <<<<<<<<<<<<<< - * roots = xRoots + yRoots - * - */ - { /* enter inner scope */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_solveQuadratic); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_2 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[4] = {__pyx_t_2, __pyx_v_ay3, __pyx_v_by2, __pyx_v_cy}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[4] = {__pyx_t_2, __pyx_v_ay3, __pyx_v_by2, __pyx_v_cy}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_5 = PyTuple_New(3+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_ay3); - __Pyx_GIVEREF(__pyx_v_ay3); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_ay3); - __Pyx_INCREF(__pyx_v_by2); - __Pyx_GIVEREF(__pyx_v_by2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_by2); - __Pyx_INCREF(__pyx_v_cy); - __Pyx_GIVEREF(__pyx_v_cy); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_cy); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) { - __pyx_t_6 = __pyx_t_3; __Pyx_INCREF(__pyx_t_6); __pyx_t_11 = 0; - __pyx_t_12 = NULL; - } else { - __pyx_t_11 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_12 = Py_TYPE(__pyx_t_6)->tp_iternext; if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 437, __pyx_L22_error) - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - for (;;) { - if (likely(!__pyx_t_12)) { - if (likely(PyList_CheckExact(__pyx_t_6))) { - if (__pyx_t_11 >= PyList_GET_SIZE(__pyx_t_6)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_11); __Pyx_INCREF(__pyx_t_3); __pyx_t_11++; if (unlikely(0 < 0)) __PYX_ERR(0, 437, __pyx_L22_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_6, __pyx_t_11); __pyx_t_11++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - } else { - if (__pyx_t_11 >= PyTuple_GET_SIZE(__pyx_t_6)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_11); __Pyx_INCREF(__pyx_t_3); __pyx_t_11++; if (unlikely(0 < 0)) __PYX_ERR(0, 437, __pyx_L22_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_6, __pyx_t_11); __pyx_t_11++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - } - } else { - __pyx_t_3 = __pyx_t_12(__pyx_t_6); - if (unlikely(!__pyx_t_3)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 437, __pyx_L22_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_3); - } - __Pyx_XDECREF_SET(__pyx_8genexpr2__pyx_v_t, __pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_RichCompare(__pyx_int_0, __pyx_8genexpr2__pyx_v_t, Py_LE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_3)) { - __Pyx_DECREF(__pyx_t_3); - __pyx_t_3 = PyObject_RichCompare(__pyx_8genexpr2__pyx_v_t, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L22_error) - } - __pyx_t_13 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_13 < 0)) __PYX_ERR(0, 437, __pyx_L22_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_13) { - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_8genexpr2__pyx_v_t))) __PYX_ERR(0, 437, __pyx_L22_error) - } - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_t); __pyx_8genexpr2__pyx_v_t = 0; - goto __pyx_L26_exit_scope; - __pyx_L22_error:; - __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_t); __pyx_8genexpr2__pyx_v_t = 0; - goto __pyx_L1_error; - __pyx_L26_exit_scope:; - } /* exit inner scope */ - __pyx_v_yRoots = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":438 - * xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1] - * yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1] - * roots = xRoots + yRoots # <<<<<<<<<<<<<< - * - * points = [ - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_xRoots, __pyx_v_yRoots); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 438, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_roots = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":446 - * ) - * for t in roots - * ] + [pt1, pt4] # <<<<<<<<<<<<<< - * return calcBounds(points) - * - */ - { /* enter inner scope */ - - /* "fontTools/misc/bezierTools.py":440 - * roots = xRoots + yRoots - * - * points = [ # <<<<<<<<<<<<<< - * ( - * ax * t * t * t + bx * t * t + cx * t + dx, - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 440, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_1); - - /* "fontTools/misc/bezierTools.py":445 - * ay * t * t * t + by * t * t + cy * t + dy, - * ) - * for t in roots # <<<<<<<<<<<<<< - * ] + [pt1, pt4] - * return calcBounds(points) - */ - __pyx_t_6 = __pyx_v_roots; __Pyx_INCREF(__pyx_t_6); __pyx_t_11 = 0; - for (;;) { - if (__pyx_t_11 >= PyList_GET_SIZE(__pyx_t_6)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_11); __Pyx_INCREF(__pyx_t_3); __pyx_t_11++; if (unlikely(0 < 0)) __PYX_ERR(0, 445, __pyx_L29_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_6, __pyx_t_11); __pyx_t_11++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 445, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_8genexpr3__pyx_v_t, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":442 - * points = [ - * ( - * ax * t * t * t + bx * t * t + cx * t + dx, # <<<<<<<<<<<<<< - * ay * t * t * t + by * t * t + cy * t + dy, - * ) - */ - __pyx_t_3 = PyNumber_Multiply(__pyx_v_ax, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Multiply(__pyx_t_3, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_t_5, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Multiply(__pyx_v_bx, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_5, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_v_cx, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Add(__pyx_t_5, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_3, __pyx_v_dx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":443 - * ( - * ax * t * t * t + bx * t * t + cx * t + dx, - * ay * t * t * t + by * t * t + cy * t + dy, # <<<<<<<<<<<<<< - * ) - * for t in roots - */ - __pyx_t_3 = PyNumber_Multiply(__pyx_v_ay, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Multiply(__pyx_t_3, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_t_5, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Multiply(__pyx_v_by, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = PyNumber_Multiply(__pyx_t_5, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(__pyx_t_3, __pyx_t_7); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyNumber_Multiply(__pyx_v_cy, __pyx_8genexpr3__pyx_v_t); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PyNumber_Add(__pyx_t_5, __pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_v_dy); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 443, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":442 - * points = [ - * ( - * ax * t * t * t + bx * t * t + cx * t + dx, # <<<<<<<<<<<<<< - * ay * t * t * t + by * t * t + cy * t + dy, - * ) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 442, __pyx_L29_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_7); - __pyx_t_2 = 0; - __pyx_t_7 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_3))) __PYX_ERR(0, 440, __pyx_L29_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":445 - * ay * t * t * t + by * t * t + cy * t + dy, - * ) - * for t in roots # <<<<<<<<<<<<<< - * ] + [pt1, pt4] - * return calcBounds(points) - */ - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_t); __pyx_8genexpr3__pyx_v_t = 0; - goto __pyx_L32_exit_scope; - __pyx_L29_error:; - __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_t); __pyx_8genexpr3__pyx_v_t = 0; - goto __pyx_L1_error; - __pyx_L32_exit_scope:; - } /* exit inner scope */ - - /* "fontTools/misc/bezierTools.py":446 - * ) - * for t in roots - * ] + [pt1, pt4] # <<<<<<<<<<<<<< - * return calcBounds(points) - * - */ - __pyx_t_6 = PyList_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 446, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyList_SET_ITEM(__pyx_t_6, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_v_pt4); - PyList_SET_ITEM(__pyx_t_6, 1, __pyx_v_pt4); - __pyx_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 446, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_points = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":447 - * for t in roots - * ] + [pt1, pt4] - * return calcBounds(points) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_calcBounds); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - } - } - __pyx_t_3 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_6, __pyx_t_1, __pyx_v_points) : __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_v_points); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":412 - * - * - * def calcCubicBounds(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicBounds", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_dx); - __Pyx_XDECREF(__pyx_v_dy); - __Pyx_XDECREF(__pyx_v_ax3); - __Pyx_XDECREF(__pyx_v_ay3); - __Pyx_XDECREF(__pyx_v_bx2); - __Pyx_XDECREF(__pyx_v_by2); - __Pyx_XDECREF(__pyx_v_xRoots); - __Pyx_XDECREF(__pyx_v_yRoots); - __Pyx_XDECREF(__pyx_v_roots); - __Pyx_XDECREF(__pyx_v_points); - __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_t); - __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_t); - __Pyx_XDECREF(__pyx_8genexpr3__pyx_v_t); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":450 - * - * - * def splitLine(pt1, pt2, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a line at a given coordinate. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_25splitLine(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_24splitLine[] = "splitLine(pt1, pt2, where, isHorizontal)\nSplit a line at a given coordinate.\n\n Args:\n pt1: Start point of line as 2D tuple.\n pt2: End point of line as 2D tuple.\n where: Position at which to split the line.\n isHorizontal: Direction of the ray splitting the line. If true,\n ``where`` is interpreted as a Y coordinate; if false, then\n ``where`` is interpreted as an X coordinate.\n\n Returns:\n A list of two line segments (each line segment being two 2D tuples)\n if the line was successfully split, or a list containing the original\n line.\n\n Example::\n\n >>> printSegments(splitLine((0, 0), (100, 100), 50, True))\n ((0, 0), (50, 50))\n ((50, 50), (100, 100))\n >>> printSegments(splitLine((0, 0), (100, 100), 100, True))\n ((0, 0), (100, 100))\n >>> printSegments(splitLine((0, 0), (100, 100), 0, True))\n ((0, 0), (0, 0))\n ((0, 0), (100, 100))\n >>> printSegments(splitLine((0, 0), (100, 100), 0, False))\n ((0, 0), (0, 0))\n ((0, 0), (100, 100))\n >>> printSegments(splitLine((100, 0), (0, 0), 50, False))\n ((100, 0), (50, 0))\n ((50, 0), (0, 0))\n >>> printSegments(splitLine((0, 100), (0, 0), 50, True))\n ((0, 100), (0, 50))\n ((0, 50), (0, 0))\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_25splitLine = {"splitLine", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_25splitLine, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_24splitLine}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_25splitLine(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_where = 0; - PyObject *__pyx_v_isHorizontal = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitLine (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_where,&__pyx_n_s_isHorizontal,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitLine", 1, 4, 4, 1); __PYX_ERR(0, 450, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_where)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitLine", 1, 4, 4, 2); __PYX_ERR(0, 450, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_isHorizontal)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitLine", 1, 4, 4, 3); __PYX_ERR(0, 450, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "splitLine") < 0)) __PYX_ERR(0, 450, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_where = values[2]; - __pyx_v_isHorizontal = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitLine", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 450, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitLine", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_24splitLine(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_where, __pyx_v_isHorizontal); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_24splitLine(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_where, PyObject *__pyx_v_isHorizontal) { - PyObject *__pyx_v_pt1x = NULL; - PyObject *__pyx_v_pt1y = NULL; - PyObject *__pyx_v_pt2x = NULL; - PyObject *__pyx_v_pt2y = NULL; - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_a = NULL; - PyObject *__pyx_v_t = NULL; - PyObject *__pyx_v_midPt = 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)(PyObject *); - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitLine", 0); - - /* "fontTools/misc/bezierTools.py":486 - * ((0, 50), (0, 0)) - * """ - * pt1x, pt1y = pt1 # <<<<<<<<<<<<<< - * pt2x, pt2y = pt2 - * - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt1))) || (PyList_CheckExact(__pyx_v_pt1))) { - PyObject* sequence = __pyx_v_pt1; - 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(0, 486, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 486, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 486, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 486, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 486, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 486, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_pt1x = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_pt1y = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":487 - * """ - * pt1x, pt1y = pt1 - * pt2x, pt2y = pt2 # <<<<<<<<<<<<<< - * - * ax = pt2x - pt1x - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt2))) || (PyList_CheckExact(__pyx_v_pt2))) { - PyObject* sequence = __pyx_v_pt2; - 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(0, 487, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 487, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 487, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 487, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 487, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 487, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_pt2x = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_pt2y = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":489 - * pt2x, pt2y = pt2 - * - * ax = pt2x - pt1x # <<<<<<<<<<<<<< - * ay = pt2y - pt1y - * - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_pt2x, __pyx_v_pt1x); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 489, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ax = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":490 - * - * ax = pt2x - pt1x - * ay = pt2y - pt1y # <<<<<<<<<<<<<< - * - * bx = pt1x - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_pt2y, __pyx_v_pt1y); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 490, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ay = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":492 - * ay = pt2y - pt1y - * - * bx = pt1x # <<<<<<<<<<<<<< - * by = pt1y - * - */ - __Pyx_INCREF(__pyx_v_pt1x); - __pyx_v_bx = __pyx_v_pt1x; - - /* "fontTools/misc/bezierTools.py":493 - * - * bx = pt1x - * by = pt1y # <<<<<<<<<<<<<< - * - * a = (ax, ay)[isHorizontal] - */ - __Pyx_INCREF(__pyx_v_pt1y); - __pyx_v_by = __pyx_v_pt1y; - - /* "fontTools/misc/bezierTools.py":495 - * by = pt1y - * - * a = (ax, ay)[isHorizontal] # <<<<<<<<<<<<<< - * - * if a == 0: - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 495, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_ax); - __Pyx_GIVEREF(__pyx_v_ax); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_ax); - __Pyx_INCREF(__pyx_v_ay); - __Pyx_GIVEREF(__pyx_v_ay); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_ay); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 495, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_a = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":497 - * a = (ax, ay)[isHorizontal] - * - * if a == 0: # <<<<<<<<<<<<<< - * return [(pt1, pt2)] - * t = (where - (bx, by)[isHorizontal]) / a - */ - __pyx_t_2 = __Pyx_PyInt_EqObjC(__pyx_v_a, __pyx_int_0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 497, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 497, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":498 - * - * if a == 0: - * return [(pt1, pt2)] # <<<<<<<<<<<<<< - * t = (where - (bx, by)[isHorizontal]) / a - * if 0 <= t < 1: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_pt2); - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":497 - * a = (ax, ay)[isHorizontal] - * - * if a == 0: # <<<<<<<<<<<<<< - * return [(pt1, pt2)] - * t = (where - (bx, by)[isHorizontal]) / a - */ - } - - /* "fontTools/misc/bezierTools.py":499 - * if a == 0: - * return [(pt1, pt2)] - * t = (where - (bx, by)[isHorizontal]) / a # <<<<<<<<<<<<<< - * if 0 <= t < 1: - * midPt = ax * t + bx, ay * t + by - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 499, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_bx); - __Pyx_GIVEREF(__pyx_v_bx); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_bx); - __Pyx_INCREF(__pyx_v_by); - __Pyx_GIVEREF(__pyx_v_by); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_by); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 499, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_v_where, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 499, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_v_a); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 499, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_t = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":500 - * return [(pt1, pt2)] - * t = (where - (bx, by)[isHorizontal]) / a - * if 0 <= t < 1: # <<<<<<<<<<<<<< - * midPt = ax * t + bx, ay * t + by - * return [(pt1, midPt), (midPt, pt2)] - */ - __pyx_t_2 = PyObject_RichCompare(__pyx_int_0, __pyx_v_t, Py_LE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 500, __pyx_L1_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_2)) { - __Pyx_DECREF(__pyx_t_2); - __pyx_t_2 = PyObject_RichCompare(__pyx_v_t, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 500, __pyx_L1_error) - } - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 500, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":501 - * t = (where - (bx, by)[isHorizontal]) / a - * if 0 <= t < 1: - * midPt = ax * t + bx, ay * t + by # <<<<<<<<<<<<<< - * return [(pt1, midPt), (midPt, pt2)] - * else: - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_v_ax, __pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 501, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_bx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 501, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_v_ay, __pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 501, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_v_by); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 501, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 501, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_v_midPt = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":502 - * if 0 <= t < 1: - * midPt = ax * t + bx, ay * t + by - * return [(pt1, midPt), (midPt, pt2)] # <<<<<<<<<<<<<< - * else: - * return [(pt1, pt2)] - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 502, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_midPt); - __Pyx_GIVEREF(__pyx_v_midPt); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_midPt); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 502, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_midPt); - __Pyx_GIVEREF(__pyx_v_midPt); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_midPt); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_pt2); - __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 502, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":500 - * return [(pt1, pt2)] - * t = (where - (bx, by)[isHorizontal]) / a - * if 0 <= t < 1: # <<<<<<<<<<<<<< - * midPt = ax * t + bx, ay * t + by - * return [(pt1, midPt), (midPt, pt2)] - */ - } - - /* "fontTools/misc/bezierTools.py":504 - * return [(pt1, midPt), (midPt, pt2)] - * else: - * return [(pt1, pt2)] # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 504, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_pt2); - __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 504, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "fontTools/misc/bezierTools.py":450 - * - * - * def splitLine(pt1, pt2, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a line at a given coordinate. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitLine", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_pt1x); - __Pyx_XDECREF(__pyx_v_pt1y); - __Pyx_XDECREF(__pyx_v_pt2x); - __Pyx_XDECREF(__pyx_v_pt2y); - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_t); - __Pyx_XDECREF(__pyx_v_midPt); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":507 - * - * - * def splitQuadratic(pt1, pt2, pt3, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at a given coordinate. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_27splitQuadratic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_26splitQuadratic[] = "splitQuadratic(pt1, pt2, pt3, where, isHorizontal)\nSplit a quadratic Bezier curve at a given coordinate.\n\n Args:\n pt1,pt2,pt3: Control points of the Bezier as 2D tuples.\n where: Position at which to split the curve.\n isHorizontal: Direction of the ray splitting the curve. If true,\n ``where`` is interpreted as a Y coordinate; if false, then\n ``where`` is interpreted as an X coordinate.\n\n Returns:\n A list of two curve segments (each curve segment being three 2D tuples)\n if the curve was successfully split, or a list containing the original\n curve.\n\n Example::\n\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))\n ((0, 0), (50, 100), (100, 0))\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (75, 50), (100, 0))\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))\n ((0, 0), (12.5, 25), (25, 37.5))\n ((25, 37.5), (62.5, 75), (100, 0))\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))\n ((0, 0), (7.32233, 14.6447), (14.6447, 25))\n ((14.6447, 25), (50, 75), (85.3553, 25))\n ((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))\n >>> # XXX I'm not at all sure if the following behavior is desirable:\n >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (50, 50), (50, 50))\n ((50, 50), (75, 50), (100, 0))\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_27splitQuadratic = {"splitQuadratic", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_27splitQuadratic, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_26splitQuadratic}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_27splitQuadratic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_where = 0; - PyObject *__pyx_v_isHorizontal = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitQuadratic (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_where,&__pyx_n_s_isHorizontal,0}; - PyObject* values[5] = {0,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 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitQuadratic", 1, 5, 5, 1); __PYX_ERR(0, 507, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitQuadratic", 1, 5, 5, 2); __PYX_ERR(0, 507, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_where)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitQuadratic", 1, 5, 5, 3); __PYX_ERR(0, 507, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_isHorizontal)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitQuadratic", 1, 5, 5, 4); __PYX_ERR(0, 507, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "splitQuadratic") < 0)) __PYX_ERR(0, 507, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - 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); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_where = values[3]; - __pyx_v_isHorizontal = values[4]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitQuadratic", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 507, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitQuadratic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_26splitQuadratic(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_where, __pyx_v_isHorizontal); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_14splitQuadratic_2generator2(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "fontTools/misc/bezierTools.py":546 - * a[isHorizontal], b[isHorizontal], c[isHorizontal] - where - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) # <<<<<<<<<<<<<< - * if not solutions: - * return [(pt1, pt2, pt3)] - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_14splitQuadratic_genexpr(PyObject *__pyx_self) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("genexpr", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 546, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *) __pyx_self; - __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_4misc_11bezierTools_14splitQuadratic_2generator2, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_splitQuadratic_locals_genexpr, __pyx_n_s_fontTools_misc_bezierTools); if (unlikely(!gen)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitQuadratic.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_14splitQuadratic_2generator2(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *(*__pyx_t_3)(PyObject *); - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("genexpr", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 546, __pyx_L1_error) - __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_r); - if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions)) { __Pyx_RaiseClosureNameError("solutions"); __PYX_ERR(0, 546, __pyx_L1_error) } - if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions)) { - __pyx_t_1 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - __pyx_t_3 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 546, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_3)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 546, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 546, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_3(__pyx_t_1); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 546, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_t); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_t, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_RichCompare(__pyx_int_0, __pyx_cur_scope->__pyx_v_t, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 546, __pyx_L1_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_4)) { - __Pyx_DECREF(__pyx_t_4); - __pyx_t_4 = PyObject_RichCompare(__pyx_cur_scope->__pyx_v_t, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 546, __pyx_L1_error) - } - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { - if (unlikely(__Pyx_ListComp_Append(__pyx_r, (PyObject*)__pyx_cur_scope->__pyx_v_t))) __PYX_ERR(0, 546, __pyx_L1_error) - } - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":507 - * - * - * def splitQuadratic(pt1, pt2, pt3, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at a given coordinate. - * - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_26splitQuadratic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_where, PyObject *__pyx_v_isHorizontal) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *__pyx_cur_scope; - PyObject *__pyx_v_a = NULL; - PyObject *__pyx_v_b = NULL; - PyObject *__pyx_v_c = NULL; - PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_14splitQuadratic_2generator2 = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *(*__pyx_t_7)(PyObject *); - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - int __pyx_t_11; - int __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitQuadratic", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 507, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - - /* "fontTools/misc/bezierTools.py":542 - * ((50, 50), (75, 50), (100, 0)) - * """ - * a, b, c = calcQuadraticParameters(pt1, pt2, pt3) # <<<<<<<<<<<<<< - * solutions = solveQuadratic( - * a[isHorizontal], b[isHorizontal], c[isHorizontal] - where - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcQuadraticParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(3+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_pt3); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 542, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_3 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_3); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_6 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 542, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - index = 2; __pyx_t_3 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 3) < 0) __PYX_ERR(0, 542, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 542, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_a = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_b = __pyx_t_5; - __pyx_t_5 = 0; - __pyx_v_c = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":543 - * """ - * a, b, c = calcQuadraticParameters(pt1, pt2, pt3) - * solutions = solveQuadratic( # <<<<<<<<<<<<<< - * a[isHorizontal], b[isHorizontal], c[isHorizontal] - where - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_solveQuadratic); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 543, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "fontTools/misc/bezierTools.py":544 - * a, b, c = calcQuadraticParameters(pt1, pt2, pt3) - * solutions = solveQuadratic( - * a[isHorizontal], b[isHorizontal], c[isHorizontal] - where # <<<<<<<<<<<<<< - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) - */ - __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_a, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 544, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_b, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 544, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = __Pyx_PyObject_GetItem(__pyx_v_c, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 544, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = PyNumber_Subtract(__pyx_t_6, __pyx_v_where); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 544, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_6, __pyx_t_5, __pyx_t_2, __pyx_t_8}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 543, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_6, __pyx_t_5, __pyx_t_2, __pyx_t_8}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 543, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(3+__pyx_t_4); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 543, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_6) { - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_6); __pyx_t_6 = NULL; - } - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_4, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_4, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_9, 2+__pyx_t_4, __pyx_t_8); - __pyx_t_5 = 0; - __pyx_t_2 = 0; - __pyx_t_8 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 543, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_cur_scope->__pyx_v_solutions = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":546 - * a[isHorizontal], b[isHorizontal], c[isHorizontal] - where - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) # <<<<<<<<<<<<<< - * if not solutions: - * return [(pt1, pt2, pt3)] - */ - __pyx_t_3 = __pyx_pf_9fontTools_4misc_11bezierTools_14splitQuadratic_genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = __Pyx_Generator_Next(__pyx_t_3); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_1 = ((PyObject*)__pyx_t_9); - __pyx_t_9 = 0; - __pyx_t_10 = PyList_Sort(__pyx_t_1); if (unlikely(__pyx_t_10 == ((int)-1))) __PYX_ERR(0, 546, __pyx_L1_error) - __Pyx_GOTREF(__pyx_cur_scope->__pyx_v_solutions); - __Pyx_DECREF_SET(__pyx_cur_scope->__pyx_v_solutions, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":547 - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) - * if not solutions: # <<<<<<<<<<<<<< - * return [(pt1, pt2, pt3)] - * return _splitQuadraticAtT(a, b, c, *solutions) - */ - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_cur_scope->__pyx_v_solutions); if (unlikely(__pyx_t_11 < 0)) __PYX_ERR(0, 547, __pyx_L1_error) - __pyx_t_12 = ((!__pyx_t_11) != 0); - if (__pyx_t_12) { - - /* "fontTools/misc/bezierTools.py":548 - * solutions = sorted(t for t in solutions if 0 <= t < 1) - * if not solutions: - * return [(pt1, pt2, pt3)] # <<<<<<<<<<<<<< - * return _splitQuadraticAtT(a, b, c, *solutions) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 548, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_pt3); - __pyx_t_9 = PyList_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 548, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_9; - __pyx_t_9 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":547 - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) - * if not solutions: # <<<<<<<<<<<<<< - * return [(pt1, pt2, pt3)] - * return _splitQuadraticAtT(a, b, c, *solutions) - */ - } - - /* "fontTools/misc/bezierTools.py":549 - * if not solutions: - * return [(pt1, pt2, pt3)] - * return _splitQuadraticAtT(a, b, c, *solutions) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_n_s_splitQuadraticAtT); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_a); - __Pyx_GIVEREF(__pyx_v_a); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_a); - __Pyx_INCREF(__pyx_v_b); - __Pyx_GIVEREF(__pyx_v_b); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_b); - __Pyx_INCREF(__pyx_v_c); - __Pyx_GIVEREF(__pyx_v_c); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_c); - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_cur_scope->__pyx_v_solutions); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = PyNumber_Add(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_t_8, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":507 - * - * - * def splitQuadratic(pt1, pt2, pt3, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at a given coordinate. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitQuadratic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_b); - __Pyx_XDECREF(__pyx_v_c); - __Pyx_XDECREF(__pyx_gb_9fontTools_4misc_11bezierTools_14splitQuadratic_2generator2); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":552 - * - * - * def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at a given coordinate. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_29splitCubic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_28splitCubic[] = "splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal)\nSplit a cubic Bezier curve at a given coordinate.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n where: Position at which to split the curve.\n isHorizontal: Direction of the ray splitting the curve. If true,\n ``where`` is interpreted as a Y coordinate; if false, then\n ``where`` is interpreted as an X coordinate.\n\n Returns:\n A list of two curve segments (each curve segment being four 2D tuples)\n if the curve was successfully split, or a list containing the original\n curve.\n\n Example::\n\n >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))\n ((0, 0), (25, 100), (75, 100), (100, 0))\n >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))\n ((0, 0), (12.5, 50), (31.25, 75), (50, 75))\n ((50, 75), (68.75, 75), (87.5, 50), (100, 0))\n >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))\n ((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))\n ((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))\n ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_29splitCubic = {"splitCubic", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_29splitCubic, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_28splitCubic}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_29splitCubic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - PyObject *__pyx_v_where = 0; - PyObject *__pyx_v_isHorizontal = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitCubic (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,&__pyx_n_s_where,&__pyx_n_s_isHorizontal,0}; - PyObject* values[6] = {0,0,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 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubic", 1, 6, 6, 1); __PYX_ERR(0, 552, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubic", 1, 6, 6, 2); __PYX_ERR(0, 552, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubic", 1, 6, 6, 3); __PYX_ERR(0, 552, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_where)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubic", 1, 6, 6, 4); __PYX_ERR(0, 552, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 5: - if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_isHorizontal)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubic", 1, 6, 6, 5); __PYX_ERR(0, 552, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "splitCubic") < 0)) __PYX_ERR(0, 552, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { - 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); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - } - __pyx_v_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - __pyx_v_where = values[4]; - __pyx_v_isHorizontal = values[5]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitCubic", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 552, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_28splitCubic(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_where, __pyx_v_isHorizontal); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_10splitCubic_2generator3(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "fontTools/misc/bezierTools.py":583 - * a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) # <<<<<<<<<<<<<< - * if not solutions: - * return [(pt1, pt2, pt3, pt4)] - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_10splitCubic_genexpr(PyObject *__pyx_self) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("genexpr", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 583, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *) __pyx_self; - __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_4misc_11bezierTools_10splitCubic_2generator3, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_splitCubic_locals_genexpr, __pyx_n_s_fontTools_misc_bezierTools); if (unlikely(!gen)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubic.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_10splitCubic_2generator3(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *(*__pyx_t_3)(PyObject *); - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("genexpr", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 583, __pyx_L1_error) - __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_r); - if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions)) { __Pyx_RaiseClosureNameError("solutions"); __PYX_ERR(0, 583, __pyx_L1_error) } - if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions)) { - __pyx_t_1 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - __pyx_t_3 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_solutions); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 583, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_3)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 583, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 583, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_3(__pyx_t_1); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 583, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_t); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_t, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_RichCompare(__pyx_int_0, __pyx_cur_scope->__pyx_v_t, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 583, __pyx_L1_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_4)) { - __Pyx_DECREF(__pyx_t_4); - __pyx_t_4 = PyObject_RichCompare(__pyx_cur_scope->__pyx_v_t, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 583, __pyx_L1_error) - } - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { - if (unlikely(__Pyx_ListComp_Append(__pyx_r, (PyObject*)__pyx_cur_scope->__pyx_v_t))) __PYX_ERR(0, 583, __pyx_L1_error) - } - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":552 - * - * - * def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at a given coordinate. - * - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_28splitCubic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_where, PyObject *__pyx_v_isHorizontal) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *__pyx_cur_scope; - PyObject *__pyx_v_a = NULL; - PyObject *__pyx_v_b = NULL; - PyObject *__pyx_v_c = NULL; - PyObject *__pyx_v_d = NULL; - PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_10splitCubic_2generator3 = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - int __pyx_t_12; - int __pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitCubic", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 552, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - - /* "fontTools/misc/bezierTools.py":579 - * ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15)) - * """ - * a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4) # <<<<<<<<<<<<<< - * solutions = solveCubic( - * a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(4+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_pt3); - __Pyx_INCREF(__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_v_pt4); - PyTuple_SET_ITEM(__pyx_t_5, 3+__pyx_t_4, __pyx_v_pt4); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 579, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_3 = PyList_GET_ITEM(sequence, 2); - __pyx_t_6 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_5,&__pyx_t_3,&__pyx_t_6}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_5,&__pyx_t_3,&__pyx_t_6}; - __pyx_t_7 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_8(__pyx_t_7); if (unlikely(!item)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 4) < 0) __PYX_ERR(0, 579, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 579, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_a = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_b = __pyx_t_5; - __pyx_t_5 = 0; - __pyx_v_c = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_d = __pyx_t_6; - __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":580 - * """ - * a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4) - * solutions = solveCubic( # <<<<<<<<<<<<<< - * a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_solveCubic); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 580, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "fontTools/misc/bezierTools.py":581 - * a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4) - * solutions = solveCubic( - * a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where # <<<<<<<<<<<<<< - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) - */ - __pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_a, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_b, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_c, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_v_d, __pyx_v_isHorizontal); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PyNumber_Subtract(__pyx_t_7, __pyx_v_where); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[5] = {__pyx_t_7, __pyx_t_3, __pyx_t_5, __pyx_t_2, __pyx_t_9}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 580, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[5] = {__pyx_t_7, __pyx_t_3, __pyx_t_5, __pyx_t_2, __pyx_t_9}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 580, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(4+__pyx_t_4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 580, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_4, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_4, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_4, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_10, 3+__pyx_t_4, __pyx_t_9); - __pyx_t_3 = 0; - __pyx_t_5 = 0; - __pyx_t_2 = 0; - __pyx_t_9 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 580, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_cur_scope->__pyx_v_solutions = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":583 - * a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) # <<<<<<<<<<<<<< - * if not solutions: - * return [(pt1, pt2, pt3, pt4)] - */ - __pyx_t_6 = __pyx_pf_9fontTools_4misc_11bezierTools_10splitCubic_genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_10 = __Pyx_Generator_Next(__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_1 = ((PyObject*)__pyx_t_10); - __pyx_t_10 = 0; - __pyx_t_11 = PyList_Sort(__pyx_t_1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_cur_scope->__pyx_v_solutions); - __Pyx_DECREF_SET(__pyx_cur_scope->__pyx_v_solutions, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":584 - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) - * if not solutions: # <<<<<<<<<<<<<< - * return [(pt1, pt2, pt3, pt4)] - * return _splitCubicAtT(a, b, c, d, *solutions) - */ - __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_cur_scope->__pyx_v_solutions); if (unlikely(__pyx_t_12 < 0)) __PYX_ERR(0, 584, __pyx_L1_error) - __pyx_t_13 = ((!__pyx_t_12) != 0); - if (__pyx_t_13) { - - /* "fontTools/misc/bezierTools.py":585 - * solutions = sorted(t for t in solutions if 0 <= t < 1) - * if not solutions: - * return [(pt1, pt2, pt3, pt4)] # <<<<<<<<<<<<<< - * return _splitCubicAtT(a, b, c, d, *solutions) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 585, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_pt3); - __Pyx_INCREF(__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_v_pt4); - PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_v_pt4); - __pyx_t_10 = PyList_New(1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 585, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_10, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_10; - __pyx_t_10 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":584 - * ) - * solutions = sorted(t for t in solutions if 0 <= t < 1) - * if not solutions: # <<<<<<<<<<<<<< - * return [(pt1, pt2, pt3, pt4)] - * return _splitCubicAtT(a, b, c, d, *solutions) - */ - } - - /* "fontTools/misc/bezierTools.py":586 - * if not solutions: - * return [(pt1, pt2, pt3, pt4)] - * return _splitCubicAtT(a, b, c, d, *solutions) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_10, __pyx_n_s_splitCubicAtT); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 586, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 586, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_a); - __Pyx_GIVEREF(__pyx_v_a); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_a); - __Pyx_INCREF(__pyx_v_b); - __Pyx_GIVEREF(__pyx_v_b); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_b); - __Pyx_INCREF(__pyx_v_c); - __Pyx_GIVEREF(__pyx_v_c); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_c); - __Pyx_INCREF(__pyx_v_d); - __Pyx_GIVEREF(__pyx_v_d); - PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_v_d); - __pyx_t_6 = __Pyx_PySequence_Tuple(__pyx_cur_scope->__pyx_v_solutions); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 586, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_9 = PyNumber_Add(__pyx_t_1, __pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 586, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_10, __pyx_t_9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 586, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":552 - * - * - * def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at a given coordinate. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_b); - __Pyx_XDECREF(__pyx_v_c); - __Pyx_XDECREF(__pyx_v_d); - __Pyx_XDECREF(__pyx_gb_9fontTools_4misc_11bezierTools_10splitCubic_2generator3); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":589 - * - * - * def splitQuadraticAtT(pt1, pt2, pt3, *ts): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at one or more values of t. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_31splitQuadraticAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_30splitQuadraticAtT[] = "splitQuadraticAtT(pt1, pt2, pt3, *ts)\nSplit a quadratic Bezier curve at one or more values of t.\n\n Args:\n pt1,pt2,pt3: Control points of the Bezier as 2D tuples.\n *ts: Positions at which to split the curve.\n\n Returns:\n A list of curve segments (each curve segment being three 2D tuples).\n\n Examples::\n\n >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (75, 50), (100, 0))\n >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5, 0.75))\n ((0, 0), (25, 50), (50, 50))\n ((50, 50), (62.5, 50), (75, 37.5))\n ((75, 37.5), (87.5, 25), (100, 0))\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_31splitQuadraticAtT = {"splitQuadraticAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_31splitQuadraticAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_30splitQuadraticAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_31splitQuadraticAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_ts = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitQuadraticAtT (wrapper)", 0); - if (PyTuple_GET_SIZE(__pyx_args) > 3) { - __pyx_v_ts = PyTuple_GetSlice(__pyx_args, 3, PyTuple_GET_SIZE(__pyx_args)); - if (unlikely(!__pyx_v_ts)) { - __Pyx_RefNannyFinishContext(); - return NULL; - } - __Pyx_GOTREF(__pyx_v_ts); - } else { - __pyx_v_ts = __pyx_empty_tuple; __Pyx_INCREF(__pyx_empty_tuple); - } - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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) { - default: - 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; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitQuadraticAtT", 0, 3, 3, 1); __PYX_ERR(0, 589, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitQuadraticAtT", 0, 3, 3, 2); __PYX_ERR(0, 589, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - const Py_ssize_t used_pos_args = (pos_args < 3) ? pos_args : 3; - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, used_pos_args, "splitQuadraticAtT") < 0)) __PYX_ERR(0, 589, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitQuadraticAtT", 0, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 589, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_DECREF(__pyx_v_ts); __pyx_v_ts = 0; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitQuadraticAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_30splitQuadraticAtT(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_ts); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_30splitQuadraticAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_ts) { - PyObject *__pyx_v_a = NULL; - PyObject *__pyx_v_b = NULL; - PyObject *__pyx_v_c = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *(*__pyx_t_7)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitQuadraticAtT", 0); - - /* "fontTools/misc/bezierTools.py":609 - * ((75, 37.5), (87.5, 25), (100, 0)) - * """ - * a, b, c = calcQuadraticParameters(pt1, pt2, pt3) # <<<<<<<<<<<<<< - * return _splitQuadraticAtT(a, b, c, *ts) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcQuadraticParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 3+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(3+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_pt3); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 609, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_3 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_3); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_6 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 609, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - index = 2; __pyx_t_3 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 3) < 0) __PYX_ERR(0, 609, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 609, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_a = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_b = __pyx_t_5; - __pyx_t_5 = 0; - __pyx_v_c = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":610 - * """ - * a, b, c = calcQuadraticParameters(pt1, pt2, pt3) - * return _splitQuadraticAtT(a, b, c, *ts) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_splitQuadraticAtT); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 610, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 610, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_a); - __Pyx_GIVEREF(__pyx_v_a); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_a); - __Pyx_INCREF(__pyx_v_b); - __Pyx_GIVEREF(__pyx_v_b); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_b); - __Pyx_INCREF(__pyx_v_c); - __Pyx_GIVEREF(__pyx_v_c); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_c); - __pyx_t_5 = PyNumber_Add(__pyx_t_3, __pyx_v_ts); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 610, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 610, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":589 - * - * - * def splitQuadraticAtT(pt1, pt2, pt3, *ts): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at one or more values of t. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitQuadraticAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_b); - __Pyx_XDECREF(__pyx_v_c); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":613 - * - * - * def splitCubicAtT(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_33splitCubicAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_32splitCubicAtT[] = "splitCubicAtT(pt1, pt2, pt3, pt4, *ts)\nSplit a cubic Bezier curve at one or more values of t.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.\n *ts: Positions at which to split the curve.\n\n Returns:\n A list of curve segments (each curve segment being four 2D tuples).\n\n Examples::\n\n >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))\n ((0, 0), (12.5, 50), (31.25, 75), (50, 75))\n ((50, 75), (68.75, 75), (87.5, 50), (100, 0))\n >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5, 0.75))\n ((0, 0), (12.5, 50), (31.25, 75), (50, 75))\n ((50, 75), (59.375, 75), (68.75, 68.75), (77.3438, 56.25))\n ((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0))\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_33splitCubicAtT = {"splitCubicAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_33splitCubicAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_32splitCubicAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_33splitCubicAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - PyObject *__pyx_v_ts = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitCubicAtT (wrapper)", 0); - if (PyTuple_GET_SIZE(__pyx_args) > 4) { - __pyx_v_ts = PyTuple_GetSlice(__pyx_args, 4, PyTuple_GET_SIZE(__pyx_args)); - if (unlikely(!__pyx_v_ts)) { - __Pyx_RefNannyFinishContext(); - return NULL; - } - __Pyx_GOTREF(__pyx_v_ts); - } else { - __pyx_v_ts = __pyx_empty_tuple; __Pyx_INCREF(__pyx_empty_tuple); - } - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,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) { - default: - 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; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicAtT", 0, 4, 4, 1); __PYX_ERR(0, 613, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicAtT", 0, 4, 4, 2); __PYX_ERR(0, 613, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicAtT", 0, 4, 4, 3); __PYX_ERR(0, 613, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - const Py_ssize_t used_pos_args = (pos_args < 4) ? pos_args : 4; - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, used_pos_args, "splitCubicAtT") < 0)) __PYX_ERR(0, 613, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitCubicAtT", 0, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 613, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_DECREF(__pyx_v_ts); __pyx_v_ts = 0; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubicAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_32splitCubicAtT(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_ts); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_32splitCubicAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_ts) { - PyObject *__pyx_v_a = NULL; - PyObject *__pyx_v_b = NULL; - PyObject *__pyx_v_c = NULL; - PyObject *__pyx_v_d = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitCubicAtT", 0); - - /* "fontTools/misc/bezierTools.py":633 - * ((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0)) - * """ - * a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4) # <<<<<<<<<<<<<< - * return _splitCubicAtT(a, b, c, d, *ts) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[5] = {__pyx_t_3, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 4+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(4+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_5, 2+__pyx_t_4, __pyx_v_pt3); - __Pyx_INCREF(__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_v_pt4); - PyTuple_SET_ITEM(__pyx_t_5, 3+__pyx_t_4, __pyx_v_pt4); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 633, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_3 = PyList_GET_ITEM(sequence, 2); - __pyx_t_6 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_5,&__pyx_t_3,&__pyx_t_6}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_5,&__pyx_t_3,&__pyx_t_6}; - __pyx_t_7 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 633, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_8(__pyx_t_7); if (unlikely(!item)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 4) < 0) __PYX_ERR(0, 633, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 633, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_a = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_b = __pyx_t_5; - __pyx_t_5 = 0; - __pyx_v_c = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_d = __pyx_t_6; - __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":634 - * """ - * a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4) - * return _splitCubicAtT(a, b, c, d, *ts) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_splitCubicAtT); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 634, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 634, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_INCREF(__pyx_v_a); - __Pyx_GIVEREF(__pyx_v_a); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_a); - __Pyx_INCREF(__pyx_v_b); - __Pyx_GIVEREF(__pyx_v_b); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_v_b); - __Pyx_INCREF(__pyx_v_c); - __Pyx_GIVEREF(__pyx_v_c); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_v_c); - __Pyx_INCREF(__pyx_v_d); - __Pyx_GIVEREF(__pyx_v_d); - PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_v_d); - __pyx_t_3 = PyNumber_Add(__pyx_t_6, __pyx_v_ts); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 634, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 634, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":613 - * - * - * def splitCubicAtT(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubicAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_b); - __Pyx_XDECREF(__pyx_v_c); - __Pyx_XDECREF(__pyx_v_d); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_36generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "fontTools/misc/bezierTools.py":647 - * d=cython.complex, - * ) - * def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_35splitCubicAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_34splitCubicAtTC[] = "splitCubicAtTC(double complex pt1, double complex pt2, double complex pt3, double complex pt4, *ts)\nSplit a cubic Bezier curve at one or more values of t.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers..\n *ts: Positions at which to split the curve.\n\n Yields:\n Curve segments (each curve segment being four complex numbers).\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_35splitCubicAtTC = {"splitCubicAtTC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_35splitCubicAtTC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_34splitCubicAtTC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_35splitCubicAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - __pyx_t_double_complex __pyx_v_pt4; - PyObject *__pyx_v_ts = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitCubicAtTC (wrapper)", 0); - if (PyTuple_GET_SIZE(__pyx_args) > 4) { - __pyx_v_ts = PyTuple_GetSlice(__pyx_args, 4, PyTuple_GET_SIZE(__pyx_args)); - if (unlikely(!__pyx_v_ts)) { - __Pyx_RefNannyFinishContext(); - return NULL; - } - __Pyx_GOTREF(__pyx_v_ts); - } else { - __pyx_v_ts = __pyx_empty_tuple; __Pyx_INCREF(__pyx_empty_tuple); - } - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,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) { - default: - 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; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicAtTC", 0, 4, 4, 1); __PYX_ERR(0, 647, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicAtTC", 0, 4, 4, 2); __PYX_ERR(0, 647, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicAtTC", 0, 4, 4, 3); __PYX_ERR(0, 647, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - const Py_ssize_t used_pos_args = (pos_args < 4) ? pos_args : 4; - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, used_pos_args, "splitCubicAtTC") < 0)) __PYX_ERR(0, 647, __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_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 647, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 647, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 647, __pyx_L3_error) - __pyx_v_pt4 = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 647, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitCubicAtTC", 0, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 647, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_CLEAR(__pyx_v_ts); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubicAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_34splitCubicAtTC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_ts); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_34splitCubicAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, PyObject *__pyx_v_ts) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitCubicAtTC", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 647, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_v_pt1 = __pyx_v_pt1; - __pyx_cur_scope->__pyx_v_pt2 = __pyx_v_pt2; - __pyx_cur_scope->__pyx_v_pt3 = __pyx_v_pt3; - __pyx_cur_scope->__pyx_v_pt4 = __pyx_v_pt4; - __pyx_cur_scope->__pyx_v_ts = __pyx_v_ts; - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_ts); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_ts); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_4misc_11bezierTools_36generator, __pyx_codeobj_, (PyObject *) __pyx_cur_scope, __pyx_n_s_splitCubicAtTC, __pyx_n_s_splitCubicAtTC, __pyx_n_s_fontTools_misc_bezierTools); if (unlikely(!gen)) __PYX_ERR(0, 647, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubicAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_36generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - 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)(PyObject *); - __pyx_t_double_complex __pyx_t_8; - __pyx_t_double_complex __pyx_t_9; - __pyx_t_double_complex __pyx_t_10; - __pyx_t_double_complex __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitCubicAtTC", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - case 1: goto __pyx_L6_resume_from_yield_from; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 647, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":657 - * Curve segments (each curve segment being four complex numbers). - * """ - * a, b, c, d = calcCubicParametersC(pt1, pt2, pt3, pt4) # <<<<<<<<<<<<<< - * yield from _splitCubicAtTC(a, b, c, d, *ts) - * - */ - __pyx_t_1 = __pyx_f_9fontTools_4misc_11bezierTools_calcCubicParametersC(__pyx_cur_scope->__pyx_v_pt1, __pyx_cur_scope->__pyx_v_pt2, __pyx_cur_scope->__pyx_v_pt3, __pyx_cur_scope->__pyx_v_pt4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 657, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_3 = PyList_GET_ITEM(sequence, 1); - __pyx_t_4 = PyList_GET_ITEM(sequence, 2); - __pyx_t_5 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_3,&__pyx_t_4,&__pyx_t_5}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_3,&__pyx_t_4,&__pyx_t_5}; - __pyx_t_6 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_7(__pyx_t_6); if (unlikely(!item)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 4) < 0) __PYX_ERR(0, 657, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L5_unpacking_done; - __pyx_L4_unpacking_failed:; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 657, __pyx_L1_error) - __pyx_L5_unpacking_done:; - } - __pyx_t_8 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_2); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_10 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_4); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_11 = __Pyx_PyComplex_As___pyx_t_double_complex(__pyx_t_5); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 657, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_cur_scope->__pyx_v_a = __pyx_t_8; - __pyx_cur_scope->__pyx_v_b = __pyx_t_9; - __pyx_cur_scope->__pyx_v_c = __pyx_t_10; - __pyx_cur_scope->__pyx_v_d = __pyx_t_11; - - /* "fontTools/misc/bezierTools.py":658 - * """ - * a, b, c, d = calcCubicParametersC(pt1, pt2, pt3, pt4) - * yield from _splitCubicAtTC(a, b, c, d, *ts) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_splitCubicAtTC_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = __pyx_PyComplex_FromComplex(__pyx_cur_scope->__pyx_v_a); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_cur_scope->__pyx_v_b); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_cur_scope->__pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_cur_scope->__pyx_v_d); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_2); - __pyx_t_5 = 0; - __pyx_t_4 = 0; - __pyx_t_3 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_6, __pyx_cur_scope->__pyx_v_ts); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __Pyx_Generator_Yield_From(__pyx_generator, __pyx_t_6); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XGOTREF(__pyx_r); - if (likely(__pyx_r)) { - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - /* return from generator, yielding value */ - __pyx_generator->resume_label = 1; - return __pyx_r; - __pyx_L6_resume_from_yield_from:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 658, __pyx_L1_error) - } else { - PyObject* exc_type = __Pyx_PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || (exc_type != PyExc_GeneratorExit && __Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)))) PyErr_Clear(); - else __PYX_ERR(0, 658, __pyx_L1_error) - } - } - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* "fontTools/misc/bezierTools.py":647 - * d=cython.complex, - * ) - * def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - - /* function exit code */ - PyErr_SetNone(PyExc_StopIteration); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("splitCubicAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":675 - * t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.double - * ) - * def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at t. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_38splitCubicIntoTwoAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_37splitCubicIntoTwoAtTC[] = "splitCubicIntoTwoAtTC(double complex pt1, double complex pt2, double complex pt3, double complex pt4, double t)\nSplit a cubic Bezier curve at t.\n\n Args:\n pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.\n t: Position at which to split the curve.\n\n Returns:\n A tuple of two curve segments (each curve segment being four complex numbers).\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_38splitCubicIntoTwoAtTC = {"splitCubicIntoTwoAtTC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_38splitCubicIntoTwoAtTC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_37splitCubicIntoTwoAtTC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_38splitCubicIntoTwoAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - __pyx_t_double_complex __pyx_v_pt4; - double __pyx_v_t; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("splitCubicIntoTwoAtTC (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,&__pyx_n_s_t,0}; - PyObject* values[5] = {0,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 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicIntoTwoAtTC", 1, 5, 5, 1); __PYX_ERR(0, 675, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicIntoTwoAtTC", 1, 5, 5, 2); __PYX_ERR(0, 675, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicIntoTwoAtTC", 1, 5, 5, 3); __PYX_ERR(0, 675, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("splitCubicIntoTwoAtTC", 1, 5, 5, 4); __PYX_ERR(0, 675, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "splitCubicIntoTwoAtTC") < 0)) __PYX_ERR(0, 675, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - 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); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 675, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 675, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 675, __pyx_L3_error) - __pyx_v_pt4 = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 675, __pyx_L3_error) - __pyx_v_t = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_t == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 675, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("splitCubicIntoTwoAtTC", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 675, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubicIntoTwoAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_37splitCubicIntoTwoAtTC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_37splitCubicIntoTwoAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, double __pyx_v_t) { - double __pyx_v_t2; - double __pyx_v__1_t; - double __pyx_v__1_t_2; - double __pyx_v__2_t_1_t; - __pyx_t_double_complex __pyx_v_pointAtT; - __pyx_t_double_complex __pyx_v_off1; - __pyx_t_double_complex __pyx_v_off2; - 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("splitCubicIntoTwoAtTC", 0); - - /* "fontTools/misc/bezierTools.py":685 - * A tuple of two curve segments (each curve segment being four complex numbers). - * """ - * t2 = t * t # <<<<<<<<<<<<<< - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t - */ - __pyx_v_t2 = (__pyx_v_t * __pyx_v_t); - - /* "fontTools/misc/bezierTools.py":686 - * """ - * t2 = t * t - * _1_t = 1 - t # <<<<<<<<<<<<<< - * _1_t_2 = _1_t * _1_t - * _2_t_1_t = 2 * t * _1_t - */ - __pyx_v__1_t = (1.0 - __pyx_v_t); - - /* "fontTools/misc/bezierTools.py":687 - * t2 = t * t - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t # <<<<<<<<<<<<<< - * _2_t_1_t = 2 * t * _1_t - * pointAtT = ( - */ - __pyx_v__1_t_2 = (__pyx_v__1_t * __pyx_v__1_t); - - /* "fontTools/misc/bezierTools.py":688 - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t - * _2_t_1_t = 2 * t * _1_t # <<<<<<<<<<<<<< - * pointAtT = ( - * _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 - */ - __pyx_v__2_t_1_t = ((2.0 * __pyx_v_t) * __pyx_v__1_t); - - /* "fontTools/misc/bezierTools.py":690 - * _2_t_1_t = 2 * t * _1_t - * pointAtT = ( - * _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 # <<<<<<<<<<<<<< - * ) - * off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3 - */ - __pyx_v_pointAtT = __Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v__1_t_2 * __pyx_v__1_t), 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(3, 0), __Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v__1_t_2 * __pyx_v_t), 0), __pyx_v_pt2), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v__1_t * __pyx_v_t2), 0), __pyx_v_pt3)))), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v_t2 * __pyx_v_t), 0), __pyx_v_pt4)); - - /* "fontTools/misc/bezierTools.py":692 - * _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 - * ) - * off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3 # <<<<<<<<<<<<<< - * off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4 - * - */ - __pyx_v_off1 = __Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(__pyx_v__1_t_2, 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(__pyx_v__2_t_1_t, 0), __pyx_v_pt2)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(__pyx_v_t2, 0), __pyx_v_pt3)); - - /* "fontTools/misc/bezierTools.py":693 - * ) - * off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3 - * off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4 # <<<<<<<<<<<<<< - * - * pt2 = pt1 + (pt2 - pt1) * t - */ - __pyx_v_off2 = __Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(__pyx_v__1_t_2, 0), __pyx_v_pt2), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(__pyx_v__2_t_1_t, 0), __pyx_v_pt3)), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(__pyx_v_t2, 0), __pyx_v_pt4)); - - /* "fontTools/misc/bezierTools.py":695 - * off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4 - * - * pt2 = pt1 + (pt2 - pt1) * t # <<<<<<<<<<<<<< - * pt3 = pt4 + (pt3 - pt4) * _1_t - * - */ - __pyx_v_pt2 = __Pyx_c_sum_double(__pyx_v_pt1, __Pyx_c_prod_double(__Pyx_c_diff_double(__pyx_v_pt2, __pyx_v_pt1), __pyx_t_double_complex_from_parts(__pyx_v_t, 0))); - - /* "fontTools/misc/bezierTools.py":696 - * - * pt2 = pt1 + (pt2 - pt1) * t - * pt3 = pt4 + (pt3 - pt4) * _1_t # <<<<<<<<<<<<<< - * - * return ((pt1, pt2, off1, pointAtT), (pointAtT, off2, pt3, pt4)) - */ - __pyx_v_pt3 = __Pyx_c_sum_double(__pyx_v_pt4, __Pyx_c_prod_double(__Pyx_c_diff_double(__pyx_v_pt3, __pyx_v_pt4), __pyx_t_double_complex_from_parts(__pyx_v__1_t, 0))); - - /* "fontTools/misc/bezierTools.py":698 - * pt3 = pt4 + (pt3 - pt4) * _1_t - * - * return ((pt1, pt2, off1, pointAtT), (pointAtT, off2, pt3, pt4)) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_pt1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_v_pt2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_v_off1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_v_pointAtT); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); - __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_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_v_pointAtT); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_v_off2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_v_pt3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_pt4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_1); - __pyx_t_4 = 0; - __pyx_t_3 = 0; - __pyx_t_2 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":675 - * t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.double - * ) - * def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at t. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("fontTools.misc.bezierTools.splitCubicIntoTwoAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":701 - * - * - * def _splitQuadraticAtT(a, b, c, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * segments = [] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_40_splitQuadraticAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_39_splitQuadraticAtT[] = "_splitQuadraticAtT(a, b, c, *ts)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_40_splitQuadraticAtT = {"_splitQuadraticAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_40_splitQuadraticAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_39_splitQuadraticAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_40_splitQuadraticAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_c = 0; - PyObject *__pyx_v_ts = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_splitQuadraticAtT (wrapper)", 0); - if (PyTuple_GET_SIZE(__pyx_args) > 3) { - __pyx_v_ts = PyTuple_GetSlice(__pyx_args, 3, PyTuple_GET_SIZE(__pyx_args)); - if (unlikely(!__pyx_v_ts)) { - __Pyx_RefNannyFinishContext(); - return NULL; - } - __Pyx_GOTREF(__pyx_v_ts); - } else { - __pyx_v_ts = __pyx_empty_tuple; __Pyx_INCREF(__pyx_empty_tuple); - } - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,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) { - default: - 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; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitQuadraticAtT", 0, 3, 3, 1); __PYX_ERR(0, 701, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitQuadraticAtT", 0, 3, 3, 2); __PYX_ERR(0, 701, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - const Py_ssize_t used_pos_args = (pos_args < 3) ? pos_args : 3; - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, used_pos_args, "_splitQuadraticAtT") < 0)) __PYX_ERR(0, 701, __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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_c = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_splitQuadraticAtT", 0, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 701, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_DECREF(__pyx_v_ts); __pyx_v_ts = 0; - __Pyx_AddTraceback("fontTools.misc.bezierTools._splitQuadraticAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_39_splitQuadraticAtT(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c, __pyx_v_ts); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_39_splitQuadraticAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_ts) { - PyObject *__pyx_v_segments = NULL; - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_t1 = NULL; - PyObject *__pyx_v_t2 = NULL; - PyObject *__pyx_v_delta = NULL; - PyObject *__pyx_v_delta_2 = NULL; - PyObject *__pyx_v_a1x = NULL; - PyObject *__pyx_v_a1y = NULL; - PyObject *__pyx_v_b1x = NULL; - PyObject *__pyx_v_b1y = NULL; - PyObject *__pyx_v_t1_2 = NULL; - PyObject *__pyx_v_c1x = NULL; - PyObject *__pyx_v_c1y = NULL; - PyObject *__pyx_v_pt1 = NULL; - PyObject *__pyx_v_pt2 = NULL; - PyObject *__pyx_v_pt3 = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *(*__pyx_t_5)(PyObject *); - Py_ssize_t __pyx_t_6; - PyObject *(*__pyx_t_7)(PyObject *); - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_t_12; - PyObject *__pyx_t_13 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_splitQuadraticAtT", 0); - __Pyx_INCREF(__pyx_v_ts); - - /* "fontTools/misc/bezierTools.py":702 - * - * def _splitQuadraticAtT(a, b, c, *ts): - * ts = list(ts) # <<<<<<<<<<<<<< - * segments = [] - * ts.insert(0, 0.0) - */ - __pyx_t_1 = PySequence_List(__pyx_v_ts); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 702, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_ts, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":703 - * def _splitQuadraticAtT(a, b, c, *ts): - * ts = list(ts) - * segments = [] # <<<<<<<<<<<<<< - * ts.insert(0, 0.0) - * ts.append(1.0) - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 703, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_segments = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":704 - * ts = list(ts) - * segments = [] - * ts.insert(0, 0.0) # <<<<<<<<<<<<<< - * ts.append(1.0) - * ax, ay = a - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_ts, __pyx_n_s_insert); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 704, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 704, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":705 - * segments = [] - * ts.insert(0, 0.0) - * ts.append(1.0) # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - __pyx_t_3 = __Pyx_PyObject_Append(__pyx_v_ts, __pyx_float_1_0); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 705, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":706 - * ts.insert(0, 0.0) - * ts.append(1.0) - * ax, ay = a # <<<<<<<<<<<<<< - * bx, by = b - * cx, cy = c - */ - if ((likely(PyTuple_CheckExact(__pyx_v_a))) || (PyList_CheckExact(__pyx_v_a))) { - PyObject* sequence = __pyx_v_a; - 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(0, 706, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 706, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 706, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_a); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 706, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 706, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 706, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_ax = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_ay = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":707 - * ts.append(1.0) - * ax, ay = a - * bx, by = b # <<<<<<<<<<<<<< - * cx, cy = c - * for i in range(len(ts) - 1): - */ - if ((likely(PyTuple_CheckExact(__pyx_v_b))) || (PyList_CheckExact(__pyx_v_b))) { - PyObject* sequence = __pyx_v_b; - 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(0, 707, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 707, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 707, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_b); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 707, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 707, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 707, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_bx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_by = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":708 - * ax, ay = a - * bx, by = b - * cx, cy = c # <<<<<<<<<<<<<< - * for i in range(len(ts) - 1): - * t1 = ts[i] - */ - if ((likely(PyTuple_CheckExact(__pyx_v_c))) || (PyList_CheckExact(__pyx_v_c))) { - PyObject* sequence = __pyx_v_c; - 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(0, 708, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 708, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 708, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_c); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 708, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 708, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 708, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_cx = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_cy = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":709 - * bx, by = b - * cx, cy = c - * for i in range(len(ts) - 1): # <<<<<<<<<<<<<< - * t1 = ts[i] - * t2 = ts[i + 1] - */ - __pyx_t_6 = PyObject_Length(__pyx_v_ts); if (unlikely(__pyx_t_6 == ((Py_ssize_t)-1))) __PYX_ERR(0, 709, __pyx_L1_error) - __pyx_t_1 = PyInt_FromSsize_t((__pyx_t_6 - 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 709, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_range, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 709, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { - __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - } else { - __pyx_t_6 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 709, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 709, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - for (;;) { - if (likely(!__pyx_t_7)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_6); __Pyx_INCREF(__pyx_t_2); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 709, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 709, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - if (__pyx_t_6 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_6); __Pyx_INCREF(__pyx_t_2); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 709, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 709, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } - } else { - __pyx_t_2 = __pyx_t_7(__pyx_t_1); - if (unlikely(!__pyx_t_2)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 709, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_2); - } - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":710 - * cx, cy = c - * for i in range(len(ts) - 1): - * t1 = ts[i] # <<<<<<<<<<<<<< - * t2 = ts[i + 1] - * delta = t2 - t1 - */ - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_ts, __pyx_v_i); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 710, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF_SET(__pyx_v_t1, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":711 - * for i in range(len(ts) - 1): - * t1 = ts[i] - * t2 = ts[i + 1] # <<<<<<<<<<<<<< - * delta = t2 - t1 - * # calc new a, b and c - */ - __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_v_i, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 711, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_ts, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 711, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF_SET(__pyx_v_t2, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":712 - * t1 = ts[i] - * t2 = ts[i + 1] - * delta = t2 - t1 # <<<<<<<<<<<<<< - * # calc new a, b and c - * delta_2 = delta * delta - */ - __pyx_t_4 = PyNumber_Subtract(__pyx_v_t2, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 712, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_delta, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":714 - * delta = t2 - t1 - * # calc new a, b and c - * delta_2 = delta * delta # <<<<<<<<<<<<<< - * a1x = ax * delta_2 - * a1y = ay * delta_2 - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_delta, __pyx_v_delta); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 714, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_delta_2, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":715 - * # calc new a, b and c - * delta_2 = delta * delta - * a1x = ax * delta_2 # <<<<<<<<<<<<<< - * a1y = ay * delta_2 - * b1x = (2 * ax * t1 + bx) * delta - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_ax, __pyx_v_delta_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 715, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_a1x, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":716 - * delta_2 = delta * delta - * a1x = ax * delta_2 - * a1y = ay * delta_2 # <<<<<<<<<<<<<< - * b1x = (2 * ax * t1 + bx) * delta - * b1y = (2 * ay * t1 + by) * delta - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_ay, __pyx_v_delta_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 716, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_a1y, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":717 - * a1x = ax * delta_2 - * a1y = ay * delta_2 - * b1x = (2 * ax * t1 + bx) * delta # <<<<<<<<<<<<<< - * b1y = (2 * ay * t1 + by) * delta - * t1_2 = t1 * t1 - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_int_2, __pyx_v_ax); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 717, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_4, __pyx_v_t1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 717, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_v_bx); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 717, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_4, __pyx_v_delta); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 717, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_b1x, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":718 - * a1y = ay * delta_2 - * b1x = (2 * ax * t1 + bx) * delta - * b1y = (2 * ay * t1 + by) * delta # <<<<<<<<<<<<<< - * t1_2 = t1 * t1 - * c1x = ax * t1_2 + bx * t1 + cx - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_int_2, __pyx_v_ay); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 718, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_2, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 718, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_4, __pyx_v_by); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 718, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_t_2, __pyx_v_delta); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 718, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF_SET(__pyx_v_b1y, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":719 - * b1x = (2 * ax * t1 + bx) * delta - * b1y = (2 * ay * t1 + by) * delta - * t1_2 = t1 * t1 # <<<<<<<<<<<<<< - * c1x = ax * t1_2 + bx * t1 + cx - * c1y = ay * t1_2 + by * t1 + cy - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_t1, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 719, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_t1_2, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":720 - * b1y = (2 * ay * t1 + by) * delta - * t1_2 = t1 * t1 - * c1x = ax * t1_2 + bx * t1 + cx # <<<<<<<<<<<<<< - * c1y = ay * t1_2 + by * t1 + cy - * - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_ax, __pyx_v_t1_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 720, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyNumber_Multiply(__pyx_v_bx, __pyx_v_t1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 720, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_8 = PyNumber_Add(__pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 720, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_8, __pyx_v_cx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 720, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF_SET(__pyx_v_c1x, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":721 - * t1_2 = t1 * t1 - * c1x = ax * t1_2 + bx * t1 + cx - * c1y = ay * t1_2 + by * t1 + cy # <<<<<<<<<<<<<< - * - * pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y)) - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_v_ay, __pyx_v_t1_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 721, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_8 = PyNumber_Multiply(__pyx_v_by, __pyx_v_t1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 721, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_t_8); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 721, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_Add(__pyx_t_4, __pyx_v_cy); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 721, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_c1y, __pyx_t_8); - __pyx_t_8 = 0; - - /* "fontTools/misc/bezierTools.py":723 - * c1y = ay * t1_2 + by * t1 + cy - * - * pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y)) # <<<<<<<<<<<<<< - * segments.append((pt1, pt2, pt3)) - * return segments - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_calcQuadraticPoints); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_a1x); - __Pyx_GIVEREF(__pyx_v_a1x); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_a1x); - __Pyx_INCREF(__pyx_v_a1y); - __Pyx_GIVEREF(__pyx_v_a1y); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_a1y); - __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(__pyx_v_b1x); - __Pyx_GIVEREF(__pyx_v_b1x); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v_b1x); - __Pyx_INCREF(__pyx_v_b1y); - __Pyx_GIVEREF(__pyx_v_b1y); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_b1y); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_INCREF(__pyx_v_c1x); - __Pyx_GIVEREF(__pyx_v_c1x); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_v_c1x); - __Pyx_INCREF(__pyx_v_c1y); - __Pyx_GIVEREF(__pyx_v_c1y); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_v_c1y); - __pyx_t_11 = NULL; - __pyx_t_12 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_12 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_t_2, __pyx_t_9, __pyx_t_10}; - __pyx_t_8 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_12, 3+__pyx_t_12); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_t_2, __pyx_t_9, __pyx_t_10}; - __pyx_t_8 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_12, 3+__pyx_t_12); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - { - __pyx_t_13 = PyTuple_New(3+__pyx_t_12); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - if (__pyx_t_11) { - __Pyx_GIVEREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_t_11); __pyx_t_11 = NULL; - } - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_13, 0+__pyx_t_12, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_13, 1+__pyx_t_12, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_13, 2+__pyx_t_12, __pyx_t_10); - __pyx_t_2 = 0; - __pyx_t_9 = 0; - __pyx_t_10 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_13, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_8))) || (PyList_CheckExact(__pyx_t_8))) { - PyObject* sequence = __pyx_t_8; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 723, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_13 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_10 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_13 = PyList_GET_ITEM(sequence, 1); - __pyx_t_10 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_13); - __Pyx_INCREF(__pyx_t_10); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_13 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - __pyx_t_10 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - #endif - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_9 = PyObject_GetIter(__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 723, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_5 = Py_TYPE(__pyx_t_9)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_5(__pyx_t_9); if (unlikely(!__pyx_t_4)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_13 = __pyx_t_5(__pyx_t_9); if (unlikely(!__pyx_t_13)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_13); - index = 2; __pyx_t_10 = __pyx_t_5(__pyx_t_9); if (unlikely(!__pyx_t_10)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_10); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_9), 3) < 0) __PYX_ERR(0, 723, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L12_unpacking_done; - __pyx_L11_unpacking_failed:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 723, __pyx_L1_error) - __pyx_L12_unpacking_done:; - } - __Pyx_XDECREF_SET(__pyx_v_pt1, __pyx_t_4); - __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_pt2, __pyx_t_13); - __pyx_t_13 = 0; - __Pyx_XDECREF_SET(__pyx_v_pt3, __pyx_t_10); - __pyx_t_10 = 0; - - /* "fontTools/misc/bezierTools.py":724 - * - * pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y)) - * segments.append((pt1, pt2, pt3)) # <<<<<<<<<<<<<< - * return segments - * - */ - __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 724, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_v_pt3); - __pyx_t_3 = __Pyx_PyList_Append(__pyx_v_segments, __pyx_t_8); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 724, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/misc/bezierTools.py":709 - * bx, by = b - * cx, cy = c - * for i in range(len(ts) - 1): # <<<<<<<<<<<<<< - * t1 = ts[i] - * t2 = ts[i + 1] - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":725 - * pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y)) - * segments.append((pt1, pt2, pt3)) - * return segments # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_segments); - __pyx_r = __pyx_v_segments; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":701 - * - * - * def _splitQuadraticAtT(a, b, c, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * segments = [] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_AddTraceback("fontTools.misc.bezierTools._splitQuadraticAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_XDECREF(__pyx_v_segments); - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_t1); - __Pyx_XDECREF(__pyx_v_t2); - __Pyx_XDECREF(__pyx_v_delta); - __Pyx_XDECREF(__pyx_v_delta_2); - __Pyx_XDECREF(__pyx_v_a1x); - __Pyx_XDECREF(__pyx_v_a1y); - __Pyx_XDECREF(__pyx_v_b1x); - __Pyx_XDECREF(__pyx_v_b1y); - __Pyx_XDECREF(__pyx_v_t1_2); - __Pyx_XDECREF(__pyx_v_c1x); - __Pyx_XDECREF(__pyx_v_c1y); - __Pyx_XDECREF(__pyx_v_pt1); - __Pyx_XDECREF(__pyx_v_pt2); - __Pyx_XDECREF(__pyx_v_pt3); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":728 - * - * - * def _splitCubicAtT(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_42_splitCubicAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_41_splitCubicAtT[] = "_splitCubicAtT(a, b, c, d, *ts)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_42_splitCubicAtT = {"_splitCubicAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_42_splitCubicAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_41_splitCubicAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_42_splitCubicAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_c = 0; - PyObject *__pyx_v_d = 0; - PyObject *__pyx_v_ts = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_splitCubicAtT (wrapper)", 0); - if (PyTuple_GET_SIZE(__pyx_args) > 4) { - __pyx_v_ts = PyTuple_GetSlice(__pyx_args, 4, PyTuple_GET_SIZE(__pyx_args)); - if (unlikely(!__pyx_v_ts)) { - __Pyx_RefNannyFinishContext(); - return NULL; - } - __Pyx_GOTREF(__pyx_v_ts); - } else { - __pyx_v_ts = __pyx_empty_tuple; __Pyx_INCREF(__pyx_empty_tuple); - } - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,&__pyx_n_s_d,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) { - default: - 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; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitCubicAtT", 0, 4, 4, 1); __PYX_ERR(0, 728, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitCubicAtT", 0, 4, 4, 2); __PYX_ERR(0, 728, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitCubicAtT", 0, 4, 4, 3); __PYX_ERR(0, 728, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - const Py_ssize_t used_pos_args = (pos_args < 4) ? pos_args : 4; - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, used_pos_args, "_splitCubicAtT") < 0)) __PYX_ERR(0, 728, __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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_c = values[2]; - __pyx_v_d = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_splitCubicAtT", 0, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 728, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_DECREF(__pyx_v_ts); __pyx_v_ts = 0; - __Pyx_AddTraceback("fontTools.misc.bezierTools._splitCubicAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_41_splitCubicAtT(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c, __pyx_v_d, __pyx_v_ts); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_41_splitCubicAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_ts) { - PyObject *__pyx_v_segments = NULL; - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_dx = NULL; - PyObject *__pyx_v_dy = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_t1 = NULL; - PyObject *__pyx_v_t2 = NULL; - PyObject *__pyx_v_delta = NULL; - PyObject *__pyx_v_delta_2 = NULL; - PyObject *__pyx_v_delta_3 = NULL; - PyObject *__pyx_v_t1_2 = NULL; - PyObject *__pyx_v_t1_3 = NULL; - PyObject *__pyx_v_a1x = NULL; - PyObject *__pyx_v_a1y = NULL; - PyObject *__pyx_v_b1x = NULL; - PyObject *__pyx_v_b1y = NULL; - PyObject *__pyx_v_c1x = NULL; - PyObject *__pyx_v_c1y = NULL; - PyObject *__pyx_v_d1x = NULL; - PyObject *__pyx_v_d1y = NULL; - PyObject *__pyx_v_pt1 = NULL; - PyObject *__pyx_v_pt2 = NULL; - PyObject *__pyx_v_pt3 = NULL; - PyObject *__pyx_v_pt4 = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *(*__pyx_t_5)(PyObject *); - Py_ssize_t __pyx_t_6; - PyObject *(*__pyx_t_7)(PyObject *); - 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_t_13; - PyObject *__pyx_t_14 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_splitCubicAtT", 0); - __Pyx_INCREF(__pyx_v_ts); - - /* "fontTools/misc/bezierTools.py":729 - * - * def _splitCubicAtT(a, b, c, d, *ts): - * ts = list(ts) # <<<<<<<<<<<<<< - * ts.insert(0, 0.0) - * ts.append(1.0) - */ - __pyx_t_1 = PySequence_List(__pyx_v_ts); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 729, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_ts, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":730 - * def _splitCubicAtT(a, b, c, d, *ts): - * ts = list(ts) - * ts.insert(0, 0.0) # <<<<<<<<<<<<<< - * ts.append(1.0) - * segments = [] - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_ts, __pyx_n_s_insert); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 730, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 730, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":731 - * ts = list(ts) - * ts.insert(0, 0.0) - * ts.append(1.0) # <<<<<<<<<<<<<< - * segments = [] - * ax, ay = a - */ - __pyx_t_3 = __Pyx_PyObject_Append(__pyx_v_ts, __pyx_float_1_0); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 731, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":732 - * ts.insert(0, 0.0) - * ts.append(1.0) - * segments = [] # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 732, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_segments = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":733 - * ts.append(1.0) - * segments = [] - * ax, ay = a # <<<<<<<<<<<<<< - * bx, by = b - * cx, cy = c - */ - if ((likely(PyTuple_CheckExact(__pyx_v_a))) || (PyList_CheckExact(__pyx_v_a))) { - PyObject* sequence = __pyx_v_a; - 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(0, 733, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 733, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 733, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_a); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 733, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 733, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 733, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_ax = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_ay = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":734 - * segments = [] - * ax, ay = a - * bx, by = b # <<<<<<<<<<<<<< - * cx, cy = c - * dx, dy = d - */ - if ((likely(PyTuple_CheckExact(__pyx_v_b))) || (PyList_CheckExact(__pyx_v_b))) { - PyObject* sequence = __pyx_v_b; - 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(0, 734, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 734, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 734, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_b); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 734, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 734, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 734, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_bx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_by = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":735 - * ax, ay = a - * bx, by = b - * cx, cy = c # <<<<<<<<<<<<<< - * dx, dy = d - * for i in range(len(ts) - 1): - */ - if ((likely(PyTuple_CheckExact(__pyx_v_c))) || (PyList_CheckExact(__pyx_v_c))) { - PyObject* sequence = __pyx_v_c; - 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(0, 735, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 735, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 735, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_c); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 735, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 735, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 735, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_cx = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_cy = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":736 - * bx, by = b - * cx, cy = c - * dx, dy = d # <<<<<<<<<<<<<< - * for i in range(len(ts) - 1): - * t1 = ts[i] - */ - if ((likely(PyTuple_CheckExact(__pyx_v_d))) || (PyList_CheckExact(__pyx_v_d))) { - PyObject* sequence = __pyx_v_d; - 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(0, 736, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 736, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 736, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_v_d); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 736, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 736, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 736, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_v_dx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_dy = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":737 - * cx, cy = c - * dx, dy = d - * for i in range(len(ts) - 1): # <<<<<<<<<<<<<< - * t1 = ts[i] - * t2 = ts[i + 1] - */ - __pyx_t_6 = PyObject_Length(__pyx_v_ts); if (unlikely(__pyx_t_6 == ((Py_ssize_t)-1))) __PYX_ERR(0, 737, __pyx_L1_error) - __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6 - 1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 737, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_range, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 737, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { - __pyx_t_2 = __pyx_t_1; __Pyx_INCREF(__pyx_t_2); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - } else { - __pyx_t_6 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 737, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 737, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (;;) { - if (likely(!__pyx_t_7)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_6); __Pyx_INCREF(__pyx_t_1); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 737, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 737, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - if (__pyx_t_6 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_6); __Pyx_INCREF(__pyx_t_1); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 737, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 737, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } - } else { - __pyx_t_1 = __pyx_t_7(__pyx_t_2); - if (unlikely(!__pyx_t_1)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 737, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_1); - } - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":738 - * dx, dy = d - * for i in range(len(ts) - 1): - * t1 = ts[i] # <<<<<<<<<<<<<< - * t2 = ts[i + 1] - * delta = t2 - t1 - */ - __pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_ts, __pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 738, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XDECREF_SET(__pyx_v_t1, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":739 - * for i in range(len(ts) - 1): - * t1 = ts[i] - * t2 = ts[i + 1] # <<<<<<<<<<<<<< - * delta = t2 - t1 - * - */ - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_v_i, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 739, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_ts, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 739, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_t2, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":740 - * t1 = ts[i] - * t2 = ts[i + 1] - * delta = t2 - t1 # <<<<<<<<<<<<<< - * - * delta_2 = delta * delta - */ - __pyx_t_4 = PyNumber_Subtract(__pyx_v_t2, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 740, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_delta, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":742 - * delta = t2 - t1 - * - * delta_2 = delta * delta # <<<<<<<<<<<<<< - * delta_3 = delta * delta_2 - * t1_2 = t1 * t1 - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_delta, __pyx_v_delta); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 742, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_delta_2, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":743 - * - * delta_2 = delta * delta - * delta_3 = delta * delta_2 # <<<<<<<<<<<<<< - * t1_2 = t1 * t1 - * t1_3 = t1 * t1_2 - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_delta, __pyx_v_delta_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 743, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_delta_3, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":744 - * delta_2 = delta * delta - * delta_3 = delta * delta_2 - * t1_2 = t1 * t1 # <<<<<<<<<<<<<< - * t1_3 = t1 * t1_2 - * - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_t1, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 744, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_t1_2, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":745 - * delta_3 = delta * delta_2 - * t1_2 = t1 * t1 - * t1_3 = t1 * t1_2 # <<<<<<<<<<<<<< - * - * # calc new a, b, c and d - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_t1, __pyx_v_t1_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 745, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_t1_3, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":748 - * - * # calc new a, b, c and d - * a1x = ax * delta_3 # <<<<<<<<<<<<<< - * a1y = ay * delta_3 - * b1x = (3 * ax * t1 + bx) * delta_2 - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_ax, __pyx_v_delta_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 748, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_a1x, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":749 - * # calc new a, b, c and d - * a1x = ax * delta_3 - * a1y = ay * delta_3 # <<<<<<<<<<<<<< - * b1x = (3 * ax * t1 + bx) * delta_2 - * b1y = (3 * ay * t1 + by) * delta_2 - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_ay, __pyx_v_delta_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 749, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_a1y, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":750 - * a1x = ax * delta_3 - * a1y = ay * delta_3 - * b1x = (3 * ax * t1 + bx) * delta_2 # <<<<<<<<<<<<<< - * b1y = (3 * ay * t1 + by) * delta_2 - * c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_int_3, __pyx_v_ax); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 750, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_v_t1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 750, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_1, __pyx_v_bx); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 750, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_v_delta_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 750, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_b1x, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":751 - * a1y = ay * delta_3 - * b1x = (3 * ax * t1 + bx) * delta_2 - * b1y = (3 * ay * t1 + by) * delta_2 # <<<<<<<<<<<<<< - * c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta - * c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_int_3, __pyx_v_ay); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 751, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 751, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_4, __pyx_v_by); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 751, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_delta_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 751, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_b1y, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":752 - * b1x = (3 * ax * t1 + bx) * delta_2 - * b1y = (3 * ay * t1 + by) * delta_2 - * c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta # <<<<<<<<<<<<<< - * c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta - * d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_int_2, __pyx_v_bx); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_v_t1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_1, __pyx_v_cx); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_int_3, __pyx_v_ax); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = PyNumber_Multiply(__pyx_t_1, __pyx_v_t1_2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_4, __pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_Multiply(__pyx_t_1, __pyx_v_delta); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 752, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_c1x, __pyx_t_8); - __pyx_t_8 = 0; - - /* "fontTools/misc/bezierTools.py":753 - * b1y = (3 * ay * t1 + by) * delta_2 - * c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta - * c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta # <<<<<<<<<<<<<< - * d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx - * d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy - */ - __pyx_t_8 = PyNumber_Multiply(__pyx_int_2, __pyx_v_by); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_8, __pyx_v_t1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_Add(__pyx_t_1, __pyx_v_cy); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_int_3, __pyx_v_ay); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_t1_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_8, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_delta); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 753, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_c1y, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":754 - * c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta - * c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta - * d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx # <<<<<<<<<<<<<< - * d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy - * pt1, pt2, pt3, pt4 = calcCubicPoints( - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v_ax, __pyx_v_t1_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 754, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyNumber_Multiply(__pyx_v_bx, __pyx_v_t1_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 754, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = PyNumber_Add(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 754, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_v_cx, __pyx_v_t1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 754, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Add(__pyx_t_8, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 754, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_4, __pyx_v_dx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 754, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_d1x, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":755 - * c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta - * d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx - * d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy # <<<<<<<<<<<<<< - * pt1, pt2, pt3, pt4 = calcCubicPoints( - * (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y) - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_ay, __pyx_v_t1_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 755, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Multiply(__pyx_v_by, __pyx_v_t1_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 755, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Add(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 755, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_v_cy, __pyx_v_t1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 755, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyNumber_Add(__pyx_t_8, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 755, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_1, __pyx_v_dy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 755, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_d1y, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":756 - * d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx - * d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy - * pt1, pt2, pt3, pt4 = calcCubicPoints( # <<<<<<<<<<<<<< - * (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y) - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_calcCubicPoints); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - - /* "fontTools/misc/bezierTools.py":757 - * d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy - * pt1, pt2, pt3, pt4 = calcCubicPoints( - * (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y) # <<<<<<<<<<<<<< - * ) - * segments.append((pt1, pt2, pt3, pt4)) - */ - __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 757, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_v_a1x); - __Pyx_GIVEREF(__pyx_v_a1x); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_a1x); - __Pyx_INCREF(__pyx_v_a1y); - __Pyx_GIVEREF(__pyx_v_a1y); - PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_v_a1y); - __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 757, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(__pyx_v_b1x); - __Pyx_GIVEREF(__pyx_v_b1x); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v_b1x); - __Pyx_INCREF(__pyx_v_b1y); - __Pyx_GIVEREF(__pyx_v_b1y); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_b1y); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 757, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_INCREF(__pyx_v_c1x); - __Pyx_GIVEREF(__pyx_v_c1x); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_v_c1x); - __Pyx_INCREF(__pyx_v_c1y); - __Pyx_GIVEREF(__pyx_v_c1y); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_v_c1y); - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 757, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_INCREF(__pyx_v_d1x); - __Pyx_GIVEREF(__pyx_v_d1x); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_v_d1x); - __Pyx_INCREF(__pyx_v_d1y); - __Pyx_GIVEREF(__pyx_v_d1y); - PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_v_d1y); - __pyx_t_12 = NULL; - __pyx_t_13 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_12 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_12)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_12); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - __pyx_t_13 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[5] = {__pyx_t_12, __pyx_t_8, __pyx_t_9, __pyx_t_10, __pyx_t_11}; - __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_13, 4+__pyx_t_13); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[5] = {__pyx_t_12, __pyx_t_8, __pyx_t_9, __pyx_t_10, __pyx_t_11}; - __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_13, 4+__pyx_t_13); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else - #endif - { - __pyx_t_14 = PyTuple_New(4+__pyx_t_13); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_14); - if (__pyx_t_12) { - __Pyx_GIVEREF(__pyx_t_12); PyTuple_SET_ITEM(__pyx_t_14, 0, __pyx_t_12); __pyx_t_12 = NULL; - } - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_14, 0+__pyx_t_13, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_14, 1+__pyx_t_13, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_14, 2+__pyx_t_13, __pyx_t_10); - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_14, 3+__pyx_t_13, __pyx_t_11); - __pyx_t_8 = 0; - __pyx_t_9 = 0; - __pyx_t_10 = 0; - __pyx_t_11 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_14, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { - PyObject* sequence = __pyx_t_4; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 756, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_14 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_11 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_10 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_14 = PyList_GET_ITEM(sequence, 1); - __pyx_t_11 = PyList_GET_ITEM(sequence, 2); - __pyx_t_10 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_14); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(__pyx_t_10); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_1,&__pyx_t_14,&__pyx_t_11,&__pyx_t_10}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_1,&__pyx_t_14,&__pyx_t_11,&__pyx_t_10}; - __pyx_t_9 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 756, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = Py_TYPE(__pyx_t_9)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_5(__pyx_t_9); if (unlikely(!item)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_9), 4) < 0) __PYX_ERR(0, 756, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L14_unpacking_done; - __pyx_L13_unpacking_failed:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 756, __pyx_L1_error) - __pyx_L14_unpacking_done:; - } - - /* "fontTools/misc/bezierTools.py":756 - * d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx - * d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy - * pt1, pt2, pt3, pt4 = calcCubicPoints( # <<<<<<<<<<<<<< - * (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y) - * ) - */ - __Pyx_XDECREF_SET(__pyx_v_pt1, __pyx_t_1); - __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_pt2, __pyx_t_14); - __pyx_t_14 = 0; - __Pyx_XDECREF_SET(__pyx_v_pt3, __pyx_t_11); - __pyx_t_11 = 0; - __Pyx_XDECREF_SET(__pyx_v_pt4, __pyx_t_10); - __pyx_t_10 = 0; - - /* "fontTools/misc/bezierTools.py":759 - * (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y) - * ) - * segments.append((pt1, pt2, pt3, pt4)) # <<<<<<<<<<<<<< - * return segments - * - */ - __pyx_t_4 = PyTuple_New(4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 759, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_pt1); - __Pyx_INCREF(__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_pt2); - __Pyx_INCREF(__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_pt3); - __Pyx_INCREF(__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_v_pt4); - PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_v_pt4); - __pyx_t_3 = __Pyx_PyList_Append(__pyx_v_segments, __pyx_t_4); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 759, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":737 - * cx, cy = c - * dx, dy = d - * for i in range(len(ts) - 1): # <<<<<<<<<<<<<< - * t1 = ts[i] - * t2 = ts[i + 1] - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":760 - * ) - * segments.append((pt1, pt2, pt3, pt4)) - * return segments # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_segments); - __pyx_r = __pyx_v_segments; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":728 - * - * - * def _splitCubicAtT(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_XDECREF(__pyx_t_14); - __Pyx_AddTraceback("fontTools.misc.bezierTools._splitCubicAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_XDECREF(__pyx_v_segments); - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_dx); - __Pyx_XDECREF(__pyx_v_dy); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_t1); - __Pyx_XDECREF(__pyx_v_t2); - __Pyx_XDECREF(__pyx_v_delta); - __Pyx_XDECREF(__pyx_v_delta_2); - __Pyx_XDECREF(__pyx_v_delta_3); - __Pyx_XDECREF(__pyx_v_t1_2); - __Pyx_XDECREF(__pyx_v_t1_3); - __Pyx_XDECREF(__pyx_v_a1x); - __Pyx_XDECREF(__pyx_v_a1y); - __Pyx_XDECREF(__pyx_v_b1x); - __Pyx_XDECREF(__pyx_v_b1y); - __Pyx_XDECREF(__pyx_v_c1x); - __Pyx_XDECREF(__pyx_v_c1y); - __Pyx_XDECREF(__pyx_v_d1x); - __Pyx_XDECREF(__pyx_v_d1y); - __Pyx_XDECREF(__pyx_v_pt1); - __Pyx_XDECREF(__pyx_v_pt2); - __Pyx_XDECREF(__pyx_v_pt3); - __Pyx_XDECREF(__pyx_v_pt4); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_45generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "fontTools/misc/bezierTools.py":778 - * d1=cython.complex, - * ) - * def _splitCubicAtTC(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_44_splitCubicAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_43_splitCubicAtTC[] = "_splitCubicAtTC(double complex a, double complex b, double complex c, double complex d, *ts)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_44_splitCubicAtTC = {"_splitCubicAtTC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_44_splitCubicAtTC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_43_splitCubicAtTC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_44_splitCubicAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_a; - __pyx_t_double_complex __pyx_v_b; - __pyx_t_double_complex __pyx_v_c; - __pyx_t_double_complex __pyx_v_d; - PyObject *__pyx_v_ts = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_splitCubicAtTC (wrapper)", 0); - if (PyTuple_GET_SIZE(__pyx_args) > 4) { - __pyx_v_ts = PyTuple_GetSlice(__pyx_args, 4, PyTuple_GET_SIZE(__pyx_args)); - if (unlikely(!__pyx_v_ts)) { - __Pyx_RefNannyFinishContext(); - return NULL; - } - __Pyx_GOTREF(__pyx_v_ts); - } else { - __pyx_v_ts = __pyx_empty_tuple; __Pyx_INCREF(__pyx_empty_tuple); - } - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,&__pyx_n_s_d,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) { - default: - 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; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitCubicAtTC", 0, 4, 4, 1); __PYX_ERR(0, 778, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitCubicAtTC", 0, 4, 4, 2); __PYX_ERR(0, 778, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_splitCubicAtTC", 0, 4, 4, 3); __PYX_ERR(0, 778, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - const Py_ssize_t used_pos_args = (pos_args < 4) ? pos_args : 4; - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, used_pos_args, "_splitCubicAtTC") < 0)) __PYX_ERR(0, 778, __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_a = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 778, __pyx_L3_error) - __pyx_v_b = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 778, __pyx_L3_error) - __pyx_v_c = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 778, __pyx_L3_error) - __pyx_v_d = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 778, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_splitCubicAtTC", 0, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 778, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_CLEAR(__pyx_v_ts); - __Pyx_AddTraceback("fontTools.misc.bezierTools._splitCubicAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_43_splitCubicAtTC(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c, __pyx_v_d, __pyx_v_ts); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_43_splitCubicAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_a, __pyx_t_double_complex __pyx_v_b, __pyx_t_double_complex __pyx_v_c, __pyx_t_double_complex __pyx_v_d, PyObject *__pyx_v_ts) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_splitCubicAtTC", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 778, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_v_a = __pyx_v_a; - __pyx_cur_scope->__pyx_v_b = __pyx_v_b; - __pyx_cur_scope->__pyx_v_c = __pyx_v_c; - __pyx_cur_scope->__pyx_v_d = __pyx_v_d; - __pyx_cur_scope->__pyx_v_ts = __pyx_v_ts; - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_ts); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_ts); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_4misc_11bezierTools_45generator1, __pyx_codeobj__3, (PyObject *) __pyx_cur_scope, __pyx_n_s_splitCubicAtTC_2, __pyx_n_s_splitCubicAtTC_2, __pyx_n_s_fontTools_misc_bezierTools); if (unlikely(!gen)) __PYX_ERR(0, 778, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._splitCubicAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_45generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - PyObject *(*__pyx_t_5)(PyObject *); - double __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)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_splitCubicAtTC", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - case 1: goto __pyx_L8_resume_from_yield; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 778, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":779 - * ) - * def _splitCubicAtTC(a, b, c, d, *ts): - * ts = list(ts) # <<<<<<<<<<<<<< - * ts.insert(0, 0.0) - * ts.append(1.0) - */ - __pyx_t_1 = PySequence_List(__pyx_cur_scope->__pyx_v_ts); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 779, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_cur_scope->__pyx_v_ts); - __Pyx_DECREF_SET(__pyx_cur_scope->__pyx_v_ts, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":780 - * def _splitCubicAtTC(a, b, c, d, *ts): - * ts = list(ts) - * ts.insert(0, 0.0) # <<<<<<<<<<<<<< - * ts.append(1.0) - * for i in range(len(ts) - 1): - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_cur_scope->__pyx_v_ts, __pyx_n_s_insert); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 780, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 780, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":781 - * ts = list(ts) - * ts.insert(0, 0.0) - * ts.append(1.0) # <<<<<<<<<<<<<< - * for i in range(len(ts) - 1): - * t1 = ts[i] - */ - __pyx_t_3 = __Pyx_PyObject_Append(__pyx_cur_scope->__pyx_v_ts, __pyx_float_1_0); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 781, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":782 - * ts.insert(0, 0.0) - * ts.append(1.0) - * for i in range(len(ts) - 1): # <<<<<<<<<<<<<< - * t1 = ts[i] - * t2 = ts[i + 1] - */ - __pyx_t_4 = PyObject_Length(__pyx_cur_scope->__pyx_v_ts); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 782, __pyx_L1_error) - __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_4 - 1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_range, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { - __pyx_t_2 = __pyx_t_1; __Pyx_INCREF(__pyx_t_2); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - } else { - __pyx_t_4 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 782, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (;;) { - if (likely(!__pyx_t_5)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_4 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_4); __Pyx_INCREF(__pyx_t_1); __pyx_t_4++; if (unlikely(0 < 0)) __PYX_ERR(0, 782, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - if (__pyx_t_4 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_4); __Pyx_INCREF(__pyx_t_1); __pyx_t_4++; if (unlikely(0 < 0)) __PYX_ERR(0, 782, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_2, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } - } else { - __pyx_t_1 = __pyx_t_5(__pyx_t_2); - if (unlikely(!__pyx_t_1)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 782, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_1); - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_i); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_i, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":783 - * ts.append(1.0) - * for i in range(len(ts) - 1): - * t1 = ts[i] # <<<<<<<<<<<<<< - * t2 = ts[i + 1] - * delta = t2 - t1 - */ - __pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_cur_scope->__pyx_v_ts, __pyx_cur_scope->__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 783, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 783, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_cur_scope->__pyx_v_t1 = __pyx_t_6; - - /* "fontTools/misc/bezierTools.py":784 - * for i in range(len(ts) - 1): - * t1 = ts[i] - * t2 = ts[i + 1] # <<<<<<<<<<<<<< - * delta = t2 - t1 - * - */ - __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_cur_scope->__pyx_v_i, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 784, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_cur_scope->__pyx_v_ts, __pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 784, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 784, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_cur_scope->__pyx_v_t2 = __pyx_t_6; - - /* "fontTools/misc/bezierTools.py":785 - * t1 = ts[i] - * t2 = ts[i + 1] - * delta = t2 - t1 # <<<<<<<<<<<<<< - * - * delta_2 = delta * delta - */ - __pyx_cur_scope->__pyx_v_delta = (__pyx_cur_scope->__pyx_v_t2 - __pyx_cur_scope->__pyx_v_t1); - - /* "fontTools/misc/bezierTools.py":787 - * delta = t2 - t1 - * - * delta_2 = delta * delta # <<<<<<<<<<<<<< - * delta_3 = delta * delta_2 - * t1_2 = t1 * t1 - */ - __pyx_cur_scope->__pyx_v_delta_2 = (__pyx_cur_scope->__pyx_v_delta * __pyx_cur_scope->__pyx_v_delta); - - /* "fontTools/misc/bezierTools.py":788 - * - * delta_2 = delta * delta - * delta_3 = delta * delta_2 # <<<<<<<<<<<<<< - * t1_2 = t1 * t1 - * t1_3 = t1 * t1_2 - */ - __pyx_cur_scope->__pyx_v_delta_3 = (__pyx_cur_scope->__pyx_v_delta * __pyx_cur_scope->__pyx_v_delta_2); - - /* "fontTools/misc/bezierTools.py":789 - * delta_2 = delta * delta - * delta_3 = delta * delta_2 - * t1_2 = t1 * t1 # <<<<<<<<<<<<<< - * t1_3 = t1 * t1_2 - * - */ - __pyx_cur_scope->__pyx_v_t1_2 = (__pyx_cur_scope->__pyx_v_t1 * __pyx_cur_scope->__pyx_v_t1); - - /* "fontTools/misc/bezierTools.py":790 - * delta_3 = delta * delta_2 - * t1_2 = t1 * t1 - * t1_3 = t1 * t1_2 # <<<<<<<<<<<<<< - * - * # calc new a, b, c and d - */ - __pyx_cur_scope->__pyx_v_t1_3 = (__pyx_cur_scope->__pyx_v_t1 * __pyx_cur_scope->__pyx_v_t1_2); - - /* "fontTools/misc/bezierTools.py":793 - * - * # calc new a, b, c and d - * a1 = a * delta_3 # <<<<<<<<<<<<<< - * b1 = (3 * a * t1 + b) * delta_2 - * c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta - */ - __pyx_cur_scope->__pyx_v_a1 = __Pyx_c_prod_double(__pyx_cur_scope->__pyx_v_a, __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_delta_3, 0)); - - /* "fontTools/misc/bezierTools.py":794 - * # calc new a, b, c and d - * a1 = a * delta_3 - * b1 = (3 * a * t1 + b) * delta_2 # <<<<<<<<<<<<<< - * c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta - * d1 = a * t1_3 + b * t1_2 + c * t1 + d - */ - __pyx_cur_scope->__pyx_v_b1 = __Pyx_c_prod_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(3, 0), __pyx_cur_scope->__pyx_v_a), __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_t1, 0)), __pyx_cur_scope->__pyx_v_b), __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_delta_2, 0)); - - /* "fontTools/misc/bezierTools.py":795 - * a1 = a * delta_3 - * b1 = (3 * a * t1 + b) * delta_2 - * c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta # <<<<<<<<<<<<<< - * d1 = a * t1_3 + b * t1_2 + c * t1 + d - * pt1, pt2, pt3, pt4 = calcCubicPointsC(a1, b1, c1, d1) - */ - __pyx_cur_scope->__pyx_v_c1 = __Pyx_c_prod_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(2, 0), __pyx_cur_scope->__pyx_v_b), __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_t1, 0)), __pyx_cur_scope->__pyx_v_c), __Pyx_c_prod_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts(3, 0), __pyx_cur_scope->__pyx_v_a), __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_t1_2, 0))), __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_delta, 0)); - - /* "fontTools/misc/bezierTools.py":796 - * b1 = (3 * a * t1 + b) * delta_2 - * c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta - * d1 = a * t1_3 + b * t1_2 + c * t1 + d # <<<<<<<<<<<<<< - * pt1, pt2, pt3, pt4 = calcCubicPointsC(a1, b1, c1, d1) - * yield (pt1, pt2, pt3, pt4) - */ - __pyx_cur_scope->__pyx_v_d1 = __Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_cur_scope->__pyx_v_a, __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_t1_3, 0)), __Pyx_c_prod_double(__pyx_cur_scope->__pyx_v_b, __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_t1_2, 0))), __Pyx_c_prod_double(__pyx_cur_scope->__pyx_v_c, __pyx_t_double_complex_from_parts(__pyx_cur_scope->__pyx_v_t1, 0))), __pyx_cur_scope->__pyx_v_d); - - /* "fontTools/misc/bezierTools.py":797 - * c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta - * d1 = a * t1_3 + b * t1_2 + c * t1 + d - * pt1, pt2, pt3, pt4 = calcCubicPointsC(a1, b1, c1, d1) # <<<<<<<<<<<<<< - * yield (pt1, pt2, pt3, pt4) - * - */ - __pyx_t_7 = __pyx_f_9fontTools_4misc_11bezierTools_calcCubicPointsC(__pyx_cur_scope->__pyx_v_a1, __pyx_cur_scope->__pyx_v_b1, __pyx_cur_scope->__pyx_v_c1, __pyx_cur_scope->__pyx_v_d1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 797, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if ((likely(PyTuple_CheckExact(__pyx_t_7))) || (PyList_CheckExact(__pyx_t_7))) { - PyObject* sequence = __pyx_t_7; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 797, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_8 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_10 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_8 = PyList_GET_ITEM(sequence, 1); - __pyx_t_9 = PyList_GET_ITEM(sequence, 2); - __pyx_t_10 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(__pyx_t_10); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_1,&__pyx_t_8,&__pyx_t_9,&__pyx_t_10}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 797, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_1,&__pyx_t_8,&__pyx_t_9,&__pyx_t_10}; - __pyx_t_11 = PyObject_GetIter(__pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 797, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_12 = Py_TYPE(__pyx_t_11)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_12(__pyx_t_11); if (unlikely(!item)) goto __pyx_L6_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_11), 4) < 0) __PYX_ERR(0, 797, __pyx_L1_error) - __pyx_t_12 = NULL; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L7_unpacking_done; - __pyx_L6_unpacking_failed:; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_12 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 797, __pyx_L1_error) - __pyx_L7_unpacking_done:; - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_pt1); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_pt1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_pt2); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_pt2, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_pt3); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_pt3, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_9 = 0; - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_pt4); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_pt4, __pyx_t_10); - __Pyx_GIVEREF(__pyx_t_10); - __pyx_t_10 = 0; - - /* "fontTools/misc/bezierTools.py":798 - * d1 = a * t1_3 + b * t1_2 + c * t1 + d - * pt1, pt2, pt3, pt4 = calcCubicPointsC(a1, b1, c1, d1) - * yield (pt1, pt2, pt3, pt4) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_7 = PyTuple_New(4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 798, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_pt1); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_pt1); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_cur_scope->__pyx_v_pt1); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_pt2); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_pt2); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_cur_scope->__pyx_v_pt2); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_pt3); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_pt3); - PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_cur_scope->__pyx_v_pt3); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_pt4); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_pt4); - PyTuple_SET_ITEM(__pyx_t_7, 3, __pyx_cur_scope->__pyx_v_pt4); - __pyx_r = __pyx_t_7; - __pyx_t_7 = 0; - __Pyx_XGIVEREF(__pyx_t_2); - __pyx_cur_scope->__pyx_t_0 = __pyx_t_2; - __pyx_cur_scope->__pyx_t_1 = __pyx_t_4; - __pyx_cur_scope->__pyx_t_2 = __pyx_t_5; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - /* return from generator, yielding value */ - __pyx_generator->resume_label = 1; - return __pyx_r; - __pyx_L8_resume_from_yield:; - __pyx_t_2 = __pyx_cur_scope->__pyx_t_0; - __pyx_cur_scope->__pyx_t_0 = 0; - __Pyx_XGOTREF(__pyx_t_2); - __pyx_t_4 = __pyx_cur_scope->__pyx_t_1; - __pyx_t_5 = __pyx_cur_scope->__pyx_t_2; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 798, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":782 - * ts.insert(0, 0.0) - * ts.append(1.0) - * for i in range(len(ts) - 1): # <<<<<<<<<<<<<< - * t1 = ts[i] - * t2 = ts[i + 1] - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* "fontTools/misc/bezierTools.py":778 - * d1=cython.complex, - * ) - * def _splitCubicAtTC(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - - /* function exit code */ - PyErr_SetNone(PyExc_StopIteration); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("_splitCubicAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":808 - * - * - * def solveQuadratic(a, b, c, sqrt=sqrt): # <<<<<<<<<<<<<< - * """Solve a quadratic equation. - * - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_94__defaults__(CYTHON_UNUSED PyObject *__pyx_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("__defaults__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self)->__pyx_arg_sqrt); - __Pyx_GIVEREF(__Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self)->__pyx_arg_sqrt); - PyTuple_SET_ITEM(__pyx_t_1, 0, __Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self)->__pyx_arg_sqrt); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_2, 1, Py_None); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("fontTools.misc.bezierTools.__defaults__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_47solveQuadratic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_46solveQuadratic[] = "solveQuadratic(a, b, c, sqrt=sqrt)\nSolve a quadratic equation.\n\n Solves *a*x*x + b*x + c = 0* where a, b and c are real.\n\n Args:\n a: coefficient of *x\302\262*\n b: coefficient of *x*\n c: constant term\n\n Returns:\n A list of roots. Note that the returned list is neither guaranteed to\n be sorted nor to contain unique values!\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_47solveQuadratic = {"solveQuadratic", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_47solveQuadratic, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_46solveQuadratic}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_47solveQuadratic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_c = 0; - PyObject *__pyx_v_sqrt = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("solveQuadratic (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,&__pyx_n_s_sqrt,0}; - PyObject* values[4] = {0,0,0,0}; - __pyx_defaults *__pyx_dynamic_args = __Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self); - values[3] = __pyx_dynamic_args->__pyx_arg_sqrt; - 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_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("solveQuadratic", 0, 3, 4, 1); __PYX_ERR(0, 808, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("solveQuadratic", 0, 3, 4, 2); __PYX_ERR(0, 808, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_sqrt); - if (value) { values[3] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "solveQuadratic") < 0)) __PYX_ERR(0, 808, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - 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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_c = values[2]; - __pyx_v_sqrt = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("solveQuadratic", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 808, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.solveQuadratic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_46solveQuadratic(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c, __pyx_v_sqrt); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_46solveQuadratic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_sqrt) { - PyObject *__pyx_v_roots = NULL; - PyObject *__pyx_v_DD = NULL; - PyObject *__pyx_v_rDD = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("solveQuadratic", 0); - - /* "fontTools/misc/bezierTools.py":822 - * be sorted nor to contain unique values! - * """ - * if abs(a) < epsilon: # <<<<<<<<<<<<<< - * if abs(b) < epsilon: - * # We have a non-equation; therefore, we have no valid solution - */ - __pyx_t_1 = __Pyx_PyNumber_Absolute(__pyx_v_a); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 822, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 822, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 822, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 822, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":823 - * """ - * if abs(a) < epsilon: - * if abs(b) < epsilon: # <<<<<<<<<<<<<< - * # We have a non-equation; therefore, we have no valid solution - * roots = [] - */ - __pyx_t_3 = __Pyx_PyNumber_Absolute(__pyx_v_b); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 823, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 823, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 823, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 823, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":825 - * if abs(b) < epsilon: - * # We have a non-equation; therefore, we have no valid solution - * roots = [] # <<<<<<<<<<<<<< - * else: - * # We have a linear equation with 1 root. - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 825, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_roots = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":823 - * """ - * if abs(a) < epsilon: - * if abs(b) < epsilon: # <<<<<<<<<<<<<< - * # We have a non-equation; therefore, we have no valid solution - * roots = [] - */ - goto __pyx_L4; - } - - /* "fontTools/misc/bezierTools.py":828 - * else: - * # We have a linear equation with 1 root. - * roots = [-c / b] # <<<<<<<<<<<<<< - * else: - * # We have a true quadratic equation. Apply the quadratic formula to find two roots. - */ - /*else*/ { - __pyx_t_1 = PyNumber_Negative(__pyx_v_c); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 828, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_v_b); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 828, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 828, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_v_roots = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - } - __pyx_L4:; - - /* "fontTools/misc/bezierTools.py":822 - * be sorted nor to contain unique values! - * """ - * if abs(a) < epsilon: # <<<<<<<<<<<<<< - * if abs(b) < epsilon: - * # We have a non-equation; therefore, we have no valid solution - */ - goto __pyx_L3; - } - - /* "fontTools/misc/bezierTools.py":831 - * else: - * # We have a true quadratic equation. Apply the quadratic formula to find two roots. - * DD = b * b - 4.0 * a * c # <<<<<<<<<<<<<< - * if DD >= 0.0: - * rDD = sqrt(DD) - */ - /*else*/ { - __pyx_t_1 = PyNumber_Multiply(__pyx_v_b, __pyx_v_b); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 831, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_float_4_0, __pyx_v_a); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 831, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_2, __pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 831, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Subtract(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 831, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_DD = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":832 - * # We have a true quadratic equation. Apply the quadratic formula to find two roots. - * DD = b * b - 4.0 * a * c - * if DD >= 0.0: # <<<<<<<<<<<<<< - * rDD = sqrt(DD) - * roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a] - */ - __pyx_t_2 = PyObject_RichCompare(__pyx_v_DD, __pyx_float_0_0, Py_GE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 832, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 832, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":833 - * DD = b * b - 4.0 * a * c - * if DD >= 0.0: - * rDD = sqrt(DD) # <<<<<<<<<<<<<< - * roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a] - * else: - */ - __Pyx_INCREF(__pyx_v_sqrt); - __pyx_t_3 = __pyx_v_sqrt; __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_2 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_1, __pyx_v_DD) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_DD); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 833, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_rDD = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":834 - * if DD >= 0.0: - * rDD = sqrt(DD) - * roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a] # <<<<<<<<<<<<<< - * else: - * # complex roots, ignore - */ - __pyx_t_2 = PyNumber_Negative(__pyx_v_b); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_v_rDD); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_3, __pyx_float_2_0, 2.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Negative(__pyx_v_b); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_rDD); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_1, __pyx_float_2_0, 2.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_v_a); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyList_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_v_roots = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":832 - * # We have a true quadratic equation. Apply the quadratic formula to find two roots. - * DD = b * b - 4.0 * a * c - * if DD >= 0.0: # <<<<<<<<<<<<<< - * rDD = sqrt(DD) - * roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a] - */ - goto __pyx_L5; - } - - /* "fontTools/misc/bezierTools.py":837 - * else: - * # complex roots, ignore - * roots = [] # <<<<<<<<<<<<<< - * return roots - * - */ - /*else*/ { - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 837, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_roots = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - } - __pyx_L5:; - } - __pyx_L3:; - - /* "fontTools/misc/bezierTools.py":838 - * # complex roots, ignore - * roots = [] - * return roots # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_roots); - __pyx_r = __pyx_v_roots; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":808 - * - * - * def solveQuadratic(a, b, c, sqrt=sqrt): # <<<<<<<<<<<<<< - * """Solve a quadratic equation. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.misc.bezierTools.solveQuadratic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_roots); - __Pyx_XDECREF(__pyx_v_DD); - __Pyx_XDECREF(__pyx_v_rDD); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":841 - * - * - * def solveCubic(a, b, c, d): # <<<<<<<<<<<<<< - * """Solve a cubic equation. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_49solveCubic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_48solveCubic[] = "solveCubic(a, b, c, d)\nSolve a cubic equation.\n\n Solves *a*x*x*x + b*x*x + c*x + d = 0* where a, b, c and d are real.\n\n Args:\n a: coefficient of *x\302\263*\n b: coefficient of *x\302\262*\n c: coefficient of *x*\n d: constant term\n\n Returns:\n A list of roots. Note that the returned list is neither guaranteed to\n be sorted nor to contain unique values!\n\n Examples::\n\n >>> solveCubic(1, 1, -6, 0)\n [-3.0, -0.0, 2.0]\n >>> solveCubic(-10.0, -9.0, 48.0, -29.0)\n [-2.9, 1.0, 1.0]\n >>> solveCubic(-9.875, -9.0, 47.625, -28.75)\n [-2.911392, 1.0, 1.0]\n >>> solveCubic(1.0, -4.5, 6.75, -3.375)\n [1.5, 1.5, 1.5]\n >>> solveCubic(-12.0, 18.0, -9.0, 1.50023651123)\n [0.5, 0.5, 0.5]\n >>> solveCubic(\n ... 9.0, 0.0, 0.0, -7.62939453125e-05\n ... ) == [-0.0, -0.0, -0.0]\n True\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_49solveCubic = {"solveCubic", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_49solveCubic, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_48solveCubic}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_49solveCubic(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_c = 0; - PyObject *__pyx_v_d = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("solveCubic (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,&__pyx_n_s_d,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_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("solveCubic", 1, 4, 4, 1); __PYX_ERR(0, 841, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("solveCubic", 1, 4, 4, 2); __PYX_ERR(0, 841, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("solveCubic", 1, 4, 4, 3); __PYX_ERR(0, 841, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "solveCubic") < 0)) __PYX_ERR(0, 841, __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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_c = values[2]; - __pyx_v_d = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("solveCubic", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 841, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.solveCubic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_48solveCubic(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c, __pyx_v_d); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_48solveCubic(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_v_a1 = NULL; - PyObject *__pyx_v_a2 = NULL; - PyObject *__pyx_v_a3 = NULL; - PyObject *__pyx_v_Q = NULL; - PyObject *__pyx_v_R = NULL; - PyObject *__pyx_v_R2 = NULL; - PyObject *__pyx_v_Q3 = NULL; - PyObject *__pyx_v_R2_Q3 = NULL; - PyObject *__pyx_v_x = NULL; - PyObject *__pyx_v_theta = NULL; - PyObject *__pyx_v_rQ2 = NULL; - PyObject *__pyx_v_a1_3 = NULL; - PyObject *__pyx_v_x0 = NULL; - PyObject *__pyx_v_x1 = NULL; - PyObject *__pyx_v_x2 = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - double __pyx_t_8; - double __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("solveCubic", 0); - __Pyx_INCREF(__pyx_v_a); - - /* "fontTools/misc/bezierTools.py":879 - * # found at: http://www.strangecreations.com/library/snippets/Cubic.C - * # - * if abs(a) < epsilon: # <<<<<<<<<<<<<< - * # don't just test for zero; for very small values of 'a' solveCubic() - * # returns unreliable results, so we fall back to quad. - */ - __pyx_t_1 = __Pyx_PyNumber_Absolute(__pyx_v_a); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 879, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 879, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 879, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 879, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":882 - * # don't just test for zero; for very small values of 'a' solveCubic() - * # returns unreliable results, so we fall back to quad. - * return solveQuadratic(b, c, d) # <<<<<<<<<<<<<< - * a = float(a) - * a1 = b / a - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_solveQuadratic); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 882, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = NULL; - __pyx_t_5 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_5 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_1, __pyx_v_b, __pyx_v_c, __pyx_v_d}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_5, 3+__pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 882, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_1, __pyx_v_b, __pyx_v_c, __pyx_v_d}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_5, 3+__pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 882, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_6 = PyTuple_New(3+__pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 882, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_INCREF(__pyx_v_b); - __Pyx_GIVEREF(__pyx_v_b); - PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, __pyx_v_b); - __Pyx_INCREF(__pyx_v_c); - __Pyx_GIVEREF(__pyx_v_c); - PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_v_c); - __Pyx_INCREF(__pyx_v_d); - __Pyx_GIVEREF(__pyx_v_d); - PyTuple_SET_ITEM(__pyx_t_6, 2+__pyx_t_5, __pyx_v_d); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 882, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":879 - * # found at: http://www.strangecreations.com/library/snippets/Cubic.C - * # - * if abs(a) < epsilon: # <<<<<<<<<<<<<< - * # don't just test for zero; for very small values of 'a' solveCubic() - * # returns unreliable results, so we fall back to quad. - */ - } - - /* "fontTools/misc/bezierTools.py":883 - * # returns unreliable results, so we fall back to quad. - * return solveQuadratic(b, c, d) - * a = float(a) # <<<<<<<<<<<<<< - * a1 = b / a - * a2 = c / a - */ - __pyx_t_3 = __Pyx_PyNumber_Float(__pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 883, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_a, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":884 - * return solveQuadratic(b, c, d) - * a = float(a) - * a1 = b / a # <<<<<<<<<<<<<< - * a2 = c / a - * a3 = d / a - */ - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_v_b, __pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 884, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_a1 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":885 - * a = float(a) - * a1 = b / a - * a2 = c / a # <<<<<<<<<<<<<< - * a3 = d / a - * - */ - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_v_c, __pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 885, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_a2 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":886 - * a1 = b / a - * a2 = c / a - * a3 = d / a # <<<<<<<<<<<<<< - * - * Q = (a1 * a1 - 3.0 * a2) / 9.0 - */ - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_v_d, __pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 886, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_a3 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":888 - * a3 = d / a - * - * Q = (a1 * a1 - 3.0 * a2) / 9.0 # <<<<<<<<<<<<<< - * R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0 - * - */ - __pyx_t_3 = PyNumber_Multiply(__pyx_v_a1, __pyx_v_a1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 888, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Multiply(__pyx_float_3_0, __pyx_v_a2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 888, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyNumber_Subtract(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 888, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_6, __pyx_float_9_0, 9.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 888, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_Q = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":889 - * - * Q = (a1 * a1 - 3.0 * a2) / 9.0 - * R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0 # <<<<<<<<<<<<<< - * - * R2 = R * R - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_float_2_0, __pyx_v_a1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyNumber_Multiply(__pyx_t_2, __pyx_v_a1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_6, __pyx_v_a1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Multiply(__pyx_float_9_0, __pyx_v_a1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_6, __pyx_v_a2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Subtract(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_float_27_0, __pyx_v_a3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Add(__pyx_t_6, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_2, __pyx_float_54_0, 54.0, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_R = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":891 - * R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0 - * - * R2 = R * R # <<<<<<<<<<<<<< - * Q3 = Q * Q * Q - * R2 = 0 if R2 < epsilon else R2 - */ - __pyx_t_3 = PyNumber_Multiply(__pyx_v_R, __pyx_v_R); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 891, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_R2 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":892 - * - * R2 = R * R - * Q3 = Q * Q * Q # <<<<<<<<<<<<<< - * R2 = 0 if R2 < epsilon else R2 - * Q3 = 0 if abs(Q3) < epsilon else Q3 - */ - __pyx_t_3 = PyNumber_Multiply(__pyx_v_Q, __pyx_v_Q); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 892, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, __pyx_v_Q); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 892, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_Q3 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":893 - * R2 = R * R - * Q3 = Q * Q * Q - * R2 = 0 if R2 < epsilon else R2 # <<<<<<<<<<<<<< - * Q3 = 0 if abs(Q3) < epsilon else Q3 - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 893, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_RichCompare(__pyx_v_R2, __pyx_t_3, Py_LT); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 893, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 893, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (__pyx_t_4) { - __Pyx_INCREF(__pyx_int_0); - __pyx_t_2 = __pyx_int_0; - } else { - __Pyx_INCREF(__pyx_v_R2); - __pyx_t_2 = __pyx_v_R2; - } - __Pyx_DECREF_SET(__pyx_v_R2, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":894 - * Q3 = Q * Q * Q - * R2 = 0 if R2 < epsilon else R2 - * Q3 = 0 if abs(Q3) < epsilon else Q3 # <<<<<<<<<<<<<< - * - * R2_Q3 = R2 - Q3 - */ - __pyx_t_6 = __Pyx_PyNumber_Absolute(__pyx_v_Q3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 894, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 894, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_6, __pyx_t_3, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 894, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 894, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_4) { - __Pyx_INCREF(__pyx_int_0); - __pyx_t_2 = __pyx_int_0; - } else { - __Pyx_INCREF(__pyx_v_Q3); - __pyx_t_2 = __pyx_v_Q3; - } - __Pyx_DECREF_SET(__pyx_v_Q3, __pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":896 - * Q3 = 0 if abs(Q3) < epsilon else Q3 - * - * R2_Q3 = R2 - Q3 # <<<<<<<<<<<<<< - * - * if R2 == 0.0 and Q3 == 0.0: - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_R2, __pyx_v_Q3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 896, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_R2_Q3 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":898 - * R2_Q3 = R2 - Q3 - * - * if R2 == 0.0 and Q3 == 0.0: # <<<<<<<<<<<<<< - * x = round(-a1 / 3.0, epsilonDigits) - * return [x, x, x] - */ - __pyx_t_2 = __Pyx_PyFloat_EqObjC(__pyx_v_R2, __pyx_float_0_0, 0.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 898, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 898, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_7) { - } else { - __pyx_t_4 = __pyx_t_7; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_2 = __Pyx_PyFloat_EqObjC(__pyx_v_Q3, __pyx_float_0_0, 0.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 898, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 898, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = __pyx_t_7; - __pyx_L5_bool_binop_done:; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":899 - * - * if R2 == 0.0 and Q3 == 0.0: - * x = round(-a1 / 3.0, epsilonDigits) # <<<<<<<<<<<<<< - * return [x, x, x] - * elif R2_Q3 <= epsilon * 0.5: - */ - __pyx_t_2 = PyNumber_Negative(__pyx_v_a1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 899, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_2, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 899, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 899, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 899, __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_PyObject_Call(__pyx_builtin_round, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 899, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_x = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":900 - * if R2 == 0.0 and Q3 == 0.0: - * x = round(-a1 / 3.0, epsilonDigits) - * return [x, x, x] # <<<<<<<<<<<<<< - * elif R2_Q3 <= epsilon * 0.5: - * # The epsilon * .5 above ensures that Q3 is not zero. - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 900, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_v_x); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_v_x); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyList_SET_ITEM(__pyx_t_2, 2, __pyx_v_x); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":898 - * R2_Q3 = R2 - Q3 - * - * if R2 == 0.0 and Q3 == 0.0: # <<<<<<<<<<<<<< - * x = round(-a1 / 3.0, epsilonDigits) - * return [x, x, x] - */ - } - - /* "fontTools/misc/bezierTools.py":901 - * x = round(-a1 / 3.0, epsilonDigits) - * return [x, x, x] - * elif R2_Q3 <= epsilon * 0.5: # <<<<<<<<<<<<<< - * # The epsilon * .5 above ensures that Q3 is not zero. - * theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0)) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 901, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_2, __pyx_float_0_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 901, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_RichCompare(__pyx_v_R2_Q3, __pyx_t_3, Py_LE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 901, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 901, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":903 - * elif R2_Q3 <= epsilon * 0.5: - * # The epsilon * .5 above ensures that Q3 is not zero. - * theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0)) # <<<<<<<<<<<<<< - * rQ2 = -2.0 * sqrt(Q) - * a1_3 = a1 / 3.0 - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_acos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = -1.0; - __pyx_t_9 = 1.0; - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_10 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - } - } - __pyx_t_1 = (__pyx_t_10) ? __Pyx_PyObject_Call2Args(__pyx_t_6, __pyx_t_10, __pyx_v_Q3) : __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_v_Q3); - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyNumber_Divide(__pyx_v_R, __pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_10 = PyFloat_FromDouble(__pyx_t_9); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_11 = PyObject_RichCompare(__pyx_t_10, __pyx_t_6, Py_LT); __Pyx_XGOTREF(__pyx_t_11); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_11); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (__pyx_t_4) { - __pyx_t_11 = PyFloat_FromDouble(__pyx_t_9); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_1 = __pyx_t_11; - __pyx_t_11 = 0; - } else { - __Pyx_INCREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_INCREF(__pyx_t_1); - __pyx_t_6 = __pyx_t_1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_11 = PyFloat_FromDouble(__pyx_t_8); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_10 = PyObject_RichCompare(__pyx_t_11, __pyx_t_6, Py_GT); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (__pyx_t_4) { - __pyx_t_10 = PyFloat_FromDouble(__pyx_t_8); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_1 = __pyx_t_10; - __pyx_t_10 = 0; - } else { - __Pyx_INCREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_2 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_6, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 903, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_theta = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":904 - * # The epsilon * .5 above ensures that Q3 is not zero. - * theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0)) - * rQ2 = -2.0 * sqrt(Q) # <<<<<<<<<<<<<< - * a1_3 = a1 / 3.0 - * x0 = rQ2 * cos(theta / 3.0) - a1_3 - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 904, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_2 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_1, __pyx_v_Q) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_Q); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 904, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_float_neg_2_0, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 904, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_rQ2 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":905 - * theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0)) - * rQ2 = -2.0 * sqrt(Q) - * a1_3 = a1 / 3.0 # <<<<<<<<<<<<<< - * x0 = rQ2 * cos(theta / 3.0) - a1_3 - * x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3 - */ - __pyx_t_3 = __Pyx_PyFloat_TrueDivideObjC(__pyx_v_a1, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 905, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_a1_3 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":906 - * rQ2 = -2.0 * sqrt(Q) - * a1_3 = a1 / 3.0 - * x0 = rQ2 * cos(theta / 3.0) - a1_3 # <<<<<<<<<<<<<< - * x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3 - * x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3 - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_cos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 906, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyFloat_TrueDivideObjC(__pyx_v_theta, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 906, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_6, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 906, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_v_rQ2, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 906, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_2, __pyx_v_a1_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 906, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x0 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":907 - * a1_3 = a1 / 3.0 - * x0 = rQ2 * cos(theta / 3.0) - a1_3 - * x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3 # <<<<<<<<<<<<<< - * x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3 - * x0, x1, x2 = sorted([x0, x1, x2]) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_cos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_pi); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = PyNumber_Multiply(__pyx_float_2_0, __pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_v_theta, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_1, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_1, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_6); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_v_rQ2, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_2, __pyx_v_a1_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 907, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x1 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":908 - * x0 = rQ2 * cos(theta / 3.0) - a1_3 - * x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3 - * x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3 # <<<<<<<<<<<<<< - * x0, x1, x2 = sorted([x0, x1, x2]) - * # Merge roots that are close-enough - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_cos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_pi); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyNumber_Multiply(__pyx_float_4_0, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Add(__pyx_v_theta, __pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_6, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_6, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_v_rQ2, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_2, __pyx_v_a1_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 908, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x2 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":909 - * x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3 - * x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3 - * x0, x1, x2 = sorted([x0, x1, x2]) # <<<<<<<<<<<<<< - * # Merge roots that are close-enough - * if x1 - x0 < epsilon and x2 - x1 < epsilon: - */ - __pyx_t_2 = PyList_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 909, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_x0); - __Pyx_GIVEREF(__pyx_v_x0); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_v_x0); - __Pyx_INCREF(__pyx_v_x1); - __Pyx_GIVEREF(__pyx_v_x1); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_v_x1); - __Pyx_INCREF(__pyx_v_x2); - __Pyx_GIVEREF(__pyx_v_x2); - PyList_SET_ITEM(__pyx_t_2, 2, __pyx_v_x2); - __pyx_t_3 = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_12 = PyList_Sort(__pyx_t_3); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 909, __pyx_L1_error) - if (likely(__pyx_t_3 != Py_None)) { - PyObject* sequence = __pyx_t_3; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 909, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - __pyx_t_6 = PyList_GET_ITEM(sequence, 2); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_6); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 909, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 909, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 909, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(0, 909, __pyx_L1_error) - } - __Pyx_DECREF_SET(__pyx_v_x0, __pyx_t_2); - __pyx_t_2 = 0; - __Pyx_DECREF_SET(__pyx_v_x1, __pyx_t_1); - __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_x2, __pyx_t_6); - __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":911 - * x0, x1, x2 = sorted([x0, x1, x2]) - * # Merge roots that are close-enough - * if x1 - x0 < epsilon and x2 - x1 < epsilon: # <<<<<<<<<<<<<< - * x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits) - * elif x1 - x0 < epsilon: - */ - __pyx_t_3 = PyNumber_Subtract(__pyx_v_x1, __pyx_v_x0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_6, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_7) { - } else { - __pyx_t_4 = __pyx_t_7; - goto __pyx_L8_bool_binop_done; - } - __pyx_t_1 = PyNumber_Subtract(__pyx_v_x2, __pyx_v_x1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_6, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 911, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = __pyx_t_7; - __pyx_L8_bool_binop_done:; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":912 - * # Merge roots that are close-enough - * if x1 - x0 < epsilon and x2 - x1 < epsilon: - * x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits) # <<<<<<<<<<<<<< - * elif x1 - x0 < epsilon: - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) - */ - __pyx_t_3 = PyNumber_Add(__pyx_v_x0, __pyx_v_x1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 912, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyNumber_Add(__pyx_t_3, __pyx_v_x2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 912, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_6, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 912, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 912, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 912, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_6); - __pyx_t_3 = 0; - __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_1, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 912, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_INCREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_x0, __pyx_t_6); - __Pyx_INCREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_x1, __pyx_t_6); - __Pyx_INCREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_x2, __pyx_t_6); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":911 - * x0, x1, x2 = sorted([x0, x1, x2]) - * # Merge roots that are close-enough - * if x1 - x0 < epsilon and x2 - x1 < epsilon: # <<<<<<<<<<<<<< - * x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits) - * elif x1 - x0 < epsilon: - */ - goto __pyx_L7; - } - - /* "fontTools/misc/bezierTools.py":913 - * if x1 - x0 < epsilon and x2 - x1 < epsilon: - * x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits) - * elif x1 - x0 < epsilon: # <<<<<<<<<<<<<< - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) - * x2 = round(x2, epsilonDigits) - */ - __pyx_t_6 = PyNumber_Subtract(__pyx_v_x1, __pyx_v_x0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 913, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 913, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_6, __pyx_t_1, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 913, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 913, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":914 - * x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits) - * elif x1 - x0 < epsilon: - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) # <<<<<<<<<<<<<< - * x2 = round(x2, epsilonDigits) - * elif x2 - x1 < epsilon: - */ - __pyx_t_3 = PyNumber_Add(__pyx_v_x0, __pyx_v_x1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 914, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_3, __pyx_float_2_0, 2.0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 914, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 914, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 914, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 914, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_x0, __pyx_t_3); - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_x1, __pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":915 - * elif x1 - x0 < epsilon: - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) - * x2 = round(x2, epsilonDigits) # <<<<<<<<<<<<<< - * elif x2 - x1 < epsilon: - * x0 = round(x0, epsilonDigits) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 915, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 915, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_INCREF(__pyx_v_x2); - __Pyx_GIVEREF(__pyx_v_x2); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_x2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 915, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF_SET(__pyx_v_x2, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":913 - * if x1 - x0 < epsilon and x2 - x1 < epsilon: - * x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits) - * elif x1 - x0 < epsilon: # <<<<<<<<<<<<<< - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) - * x2 = round(x2, epsilonDigits) - */ - goto __pyx_L7; - } - - /* "fontTools/misc/bezierTools.py":916 - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) - * x2 = round(x2, epsilonDigits) - * elif x2 - x1 < epsilon: # <<<<<<<<<<<<<< - * x0 = round(x0, epsilonDigits) - * x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits) - */ - __pyx_t_3 = PyNumber_Subtract(__pyx_v_x2, __pyx_v_x1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 916, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 916, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_6, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 916, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 916, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":917 - * x2 = round(x2, epsilonDigits) - * elif x2 - x1 < epsilon: - * x0 = round(x0, epsilonDigits) # <<<<<<<<<<<<<< - * x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits) - * else: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 917, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 917, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_INCREF(__pyx_v_x0); - __Pyx_GIVEREF(__pyx_v_x0); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_x0); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 917, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF_SET(__pyx_v_x0, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":918 - * elif x2 - x1 < epsilon: - * x0 = round(x0, epsilonDigits) - * x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits) # <<<<<<<<<<<<<< - * else: - * x0 = round(x0, epsilonDigits) - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_x1, __pyx_v_x2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 918, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_1, __pyx_float_2_0, 2.0, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 918, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 918, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 918, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __pyx_t_6 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 918, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_INCREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_x1, __pyx_t_1); - __Pyx_INCREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_x2, __pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":916 - * x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits) - * x2 = round(x2, epsilonDigits) - * elif x2 - x1 < epsilon: # <<<<<<<<<<<<<< - * x0 = round(x0, epsilonDigits) - * x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits) - */ - goto __pyx_L7; - } - - /* "fontTools/misc/bezierTools.py":920 - * x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits) - * else: - * x0 = round(x0, epsilonDigits) # <<<<<<<<<<<<<< - * x1 = round(x1, epsilonDigits) - * x2 = round(x2, epsilonDigits) - */ - /*else*/ { - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 920, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 920, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x0); - __Pyx_GIVEREF(__pyx_v_x0); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x0); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 920, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_x0, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":921 - * else: - * x0 = round(x0, epsilonDigits) - * x1 = round(x1, epsilonDigits) # <<<<<<<<<<<<<< - * x2 = round(x2, epsilonDigits) - * return [x0, x1, x2] - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 921, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 921, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x1); - __Pyx_GIVEREF(__pyx_v_x1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 921, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_x1, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":922 - * x0 = round(x0, epsilonDigits) - * x1 = round(x1, epsilonDigits) - * x2 = round(x2, epsilonDigits) # <<<<<<<<<<<<<< - * return [x0, x1, x2] - * else: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 922, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 922, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x2); - __Pyx_GIVEREF(__pyx_v_x2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 922, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_x2, __pyx_t_1); - __pyx_t_1 = 0; - } - __pyx_L7:; - - /* "fontTools/misc/bezierTools.py":923 - * x1 = round(x1, epsilonDigits) - * x2 = round(x2, epsilonDigits) - * return [x0, x1, x2] # <<<<<<<<<<<<<< - * else: - * x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 923, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_x0); - __Pyx_GIVEREF(__pyx_v_x0); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_v_x0); - __Pyx_INCREF(__pyx_v_x1); - __Pyx_GIVEREF(__pyx_v_x1); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_v_x1); - __Pyx_INCREF(__pyx_v_x2); - __Pyx_GIVEREF(__pyx_v_x2); - PyList_SET_ITEM(__pyx_t_1, 2, __pyx_v_x2); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":901 - * x = round(-a1 / 3.0, epsilonDigits) - * return [x, x, x] - * elif R2_Q3 <= epsilon * 0.5: # <<<<<<<<<<<<<< - * # The epsilon * .5 above ensures that Q3 is not zero. - * theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0)) - */ - } - - /* "fontTools/misc/bezierTools.py":925 - * return [x0, x1, x2] - * else: - * x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0) # <<<<<<<<<<<<<< - * x = x + Q / x - * if R >= 0.0: - */ - /*else*/ { - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 925, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_6, __pyx_v_R2_Q3) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_R2_Q3); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 925, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyNumber_Absolute(__pyx_v_R); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 925, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyNumber_Add(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 925, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble((1.0 / 3.0)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 925, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyNumber_Power2(__pyx_t_6, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 925, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_x = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":926 - * else: - * x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0) - * x = x + Q / x # <<<<<<<<<<<<<< - * if R >= 0.0: - * x = -x - */ - __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_v_Q, __pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 926, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyNumber_Add(__pyx_v_x, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 926, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_x, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":927 - * x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0) - * x = x + Q / x - * if R >= 0.0: # <<<<<<<<<<<<<< - * x = -x - * x = round(x - a1 / 3.0, epsilonDigits) - */ - __pyx_t_3 = PyObject_RichCompare(__pyx_v_R, __pyx_float_0_0, Py_GE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 927, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 927, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":928 - * x = x + Q / x - * if R >= 0.0: - * x = -x # <<<<<<<<<<<<<< - * x = round(x - a1 / 3.0, epsilonDigits) - * return [x] - */ - __pyx_t_3 = PyNumber_Negative(__pyx_v_x); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_x, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":927 - * x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0) - * x = x + Q / x - * if R >= 0.0: # <<<<<<<<<<<<<< - * x = -x - * x = round(x - a1 / 3.0, epsilonDigits) - */ - } - - /* "fontTools/misc/bezierTools.py":929 - * if R >= 0.0: - * x = -x - * x = round(x - a1 / 3.0, epsilonDigits) # <<<<<<<<<<<<<< - * return [x] - * - */ - __pyx_t_3 = __Pyx_PyFloat_TrueDivideObjC(__pyx_v_a1, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 929, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyNumber_Subtract(__pyx_v_x, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 929, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilonDigits); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 929, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 929, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_round, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 929, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF_SET(__pyx_v_x, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":930 - * x = -x - * x = round(x - a1 / 3.0, epsilonDigits) - * return [x] # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 930, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyList_SET_ITEM(__pyx_t_3, 0, __pyx_v_x); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "fontTools/misc/bezierTools.py":841 - * - * - * def solveCubic(a, b, c, d): # <<<<<<<<<<<<<< - * """Solve a cubic equation. - * - */ - - /* 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_6); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("fontTools.misc.bezierTools.solveCubic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_a1); - __Pyx_XDECREF(__pyx_v_a2); - __Pyx_XDECREF(__pyx_v_a3); - __Pyx_XDECREF(__pyx_v_Q); - __Pyx_XDECREF(__pyx_v_R); - __Pyx_XDECREF(__pyx_v_R2); - __Pyx_XDECREF(__pyx_v_Q3); - __Pyx_XDECREF(__pyx_v_R2_Q3); - __Pyx_XDECREF(__pyx_v_x); - __Pyx_XDECREF(__pyx_v_theta); - __Pyx_XDECREF(__pyx_v_rQ2); - __Pyx_XDECREF(__pyx_v_a1_3); - __Pyx_XDECREF(__pyx_v_x0); - __Pyx_XDECREF(__pyx_v_x1); - __Pyx_XDECREF(__pyx_v_x2); - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":938 - * - * - * def calcQuadraticParameters(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_51calcQuadraticParameters(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_50calcQuadraticParameters[] = "calcQuadraticParameters(pt1, pt2, pt3)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_51calcQuadraticParameters = {"calcQuadraticParameters", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_51calcQuadraticParameters, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_50calcQuadraticParameters}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_51calcQuadraticParameters(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcQuadraticParameters (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticParameters", 1, 3, 3, 1); __PYX_ERR(0, 938, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticParameters", 1, 3, 3, 2); __PYX_ERR(0, 938, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcQuadraticParameters") < 0)) __PYX_ERR(0, 938, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcQuadraticParameters", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 938, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticParameters", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_50calcQuadraticParameters(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_50calcQuadraticParameters(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3) { - PyObject *__pyx_v_x2 = NULL; - PyObject *__pyx_v_y2 = NULL; - PyObject *__pyx_v_x3 = NULL; - PyObject *__pyx_v_y3 = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = 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)(PyObject *); - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcQuadraticParameters", 0); - - /* "fontTools/misc/bezierTools.py":939 - * - * def calcQuadraticParameters(pt1, pt2, pt3): - * x2, y2 = pt2 # <<<<<<<<<<<<<< - * x3, y3 = pt3 - * cx, cy = pt1 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt2))) || (PyList_CheckExact(__pyx_v_pt2))) { - PyObject* sequence = __pyx_v_pt2; - 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(0, 939, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 939, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 939, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 939, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 939, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 939, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_x2 = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_y2 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":940 - * def calcQuadraticParameters(pt1, pt2, pt3): - * x2, y2 = pt2 - * x3, y3 = pt3 # <<<<<<<<<<<<<< - * cx, cy = pt1 - * bx = (x2 - cx) * 2.0 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt3))) || (PyList_CheckExact(__pyx_v_pt3))) { - PyObject* sequence = __pyx_v_pt3; - 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(0, 940, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 940, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 940, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 940, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 940, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 940, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_x3 = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_y3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":941 - * x2, y2 = pt2 - * x3, y3 = pt3 - * cx, cy = pt1 # <<<<<<<<<<<<<< - * bx = (x2 - cx) * 2.0 - * by = (y2 - cy) * 2.0 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt1))) || (PyList_CheckExact(__pyx_v_pt1))) { - PyObject* sequence = __pyx_v_pt1; - 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(0, 941, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 941, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 941, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 941, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 941, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 941, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_cx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_cy = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":942 - * x3, y3 = pt3 - * cx, cy = pt1 - * bx = (x2 - cx) * 2.0 # <<<<<<<<<<<<<< - * by = (y2 - cy) * 2.0 - * ax = x3 - cx - bx - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_x2, __pyx_v_cx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 942, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_2, __pyx_float_2_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 942, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_bx = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":943 - * cx, cy = pt1 - * bx = (x2 - cx) * 2.0 - * by = (y2 - cy) * 2.0 # <<<<<<<<<<<<<< - * ax = x3 - cx - bx - * ay = y3 - cy - by - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_y2, __pyx_v_cy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 943, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_float_2_0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 943, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_by = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":944 - * bx = (x2 - cx) * 2.0 - * by = (y2 - cy) * 2.0 - * ax = x3 - cx - bx # <<<<<<<<<<<<<< - * ay = y3 - cy - by - * return (ax, ay), (bx, by), (cx, cy) - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_x3, __pyx_v_cx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 944, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_bx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 944, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_ax = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":945 - * by = (y2 - cy) * 2.0 - * ax = x3 - cx - bx - * ay = y3 - cy - by # <<<<<<<<<<<<<< - * return (ax, ay), (bx, by), (cx, cy) - * - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_y3, __pyx_v_cy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 945, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Subtract(__pyx_t_1, __pyx_v_by); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 945, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_ay = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":946 - * ax = x3 - cx - bx - * ay = y3 - cy - by - * return (ax, ay), (bx, by), (cx, cy) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 946, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_ax); - __Pyx_GIVEREF(__pyx_v_ax); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_ax); - __Pyx_INCREF(__pyx_v_ay); - __Pyx_GIVEREF(__pyx_v_ay); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_ay); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 946, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_bx); - __Pyx_GIVEREF(__pyx_v_bx); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_bx); - __Pyx_INCREF(__pyx_v_by); - __Pyx_GIVEREF(__pyx_v_by); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_by); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 946, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_cx); - __Pyx_GIVEREF(__pyx_v_cx); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_cx); - __Pyx_INCREF(__pyx_v_cy); - __Pyx_GIVEREF(__pyx_v_cy); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_cy); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 946, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":938 - * - * - * def calcQuadraticParameters(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - - /* 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_5); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticParameters", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_x2); - __Pyx_XDECREF(__pyx_v_y2); - __Pyx_XDECREF(__pyx_v_x3); - __Pyx_XDECREF(__pyx_v_y3); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":949 - * - * - * def calcCubicParameters(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_53calcCubicParameters(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_52calcCubicParameters[] = "calcCubicParameters(pt1, pt2, pt3, pt4)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_53calcCubicParameters = {"calcCubicParameters", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_53calcCubicParameters, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_52calcCubicParameters}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_53calcCubicParameters(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcCubicParameters (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicParameters", 1, 4, 4, 1); __PYX_ERR(0, 949, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicParameters", 1, 4, 4, 2); __PYX_ERR(0, 949, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicParameters", 1, 4, 4, 3); __PYX_ERR(0, 949, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcCubicParameters") < 0)) __PYX_ERR(0, 949, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcCubicParameters", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 949, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicParameters", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_52calcCubicParameters(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_52calcCubicParameters(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4) { - PyObject *__pyx_v_x2 = NULL; - PyObject *__pyx_v_y2 = NULL; - PyObject *__pyx_v_x3 = NULL; - PyObject *__pyx_v_y3 = NULL; - PyObject *__pyx_v_x4 = NULL; - PyObject *__pyx_v_y4 = NULL; - PyObject *__pyx_v_dx = NULL; - PyObject *__pyx_v_dy = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = 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)(PyObject *); - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicParameters", 0); - - /* "fontTools/misc/bezierTools.py":950 - * - * def calcCubicParameters(pt1, pt2, pt3, pt4): - * x2, y2 = pt2 # <<<<<<<<<<<<<< - * x3, y3 = pt3 - * x4, y4 = pt4 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt2))) || (PyList_CheckExact(__pyx_v_pt2))) { - PyObject* sequence = __pyx_v_pt2; - 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(0, 950, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 950, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 950, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 950, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 950, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 950, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_x2 = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_y2 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":951 - * def calcCubicParameters(pt1, pt2, pt3, pt4): - * x2, y2 = pt2 - * x3, y3 = pt3 # <<<<<<<<<<<<<< - * x4, y4 = pt4 - * dx, dy = pt1 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt3))) || (PyList_CheckExact(__pyx_v_pt3))) { - PyObject* sequence = __pyx_v_pt3; - 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(0, 951, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 951, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 951, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 951, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 951, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 951, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_x3 = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_y3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":952 - * x2, y2 = pt2 - * x3, y3 = pt3 - * x4, y4 = pt4 # <<<<<<<<<<<<<< - * dx, dy = pt1 - * cx = (x2 - dx) * 3.0 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt4))) || (PyList_CheckExact(__pyx_v_pt4))) { - PyObject* sequence = __pyx_v_pt4; - 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(0, 952, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 952, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 952, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 952, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 952, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 952, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_x4 = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_y4 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":953 - * x3, y3 = pt3 - * x4, y4 = pt4 - * dx, dy = pt1 # <<<<<<<<<<<<<< - * cx = (x2 - dx) * 3.0 - * cy = (y2 - dy) * 3.0 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt1))) || (PyList_CheckExact(__pyx_v_pt1))) { - PyObject* sequence = __pyx_v_pt1; - 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(0, 953, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 953, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 953, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 953, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 953, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 953, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_v_dx = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_dy = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":954 - * x4, y4 = pt4 - * dx, dy = pt1 - * cx = (x2 - dx) * 3.0 # <<<<<<<<<<<<<< - * cy = (y2 - dy) * 3.0 - * bx = (x3 - x2) * 3.0 - cx - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_x2, __pyx_v_dx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 954, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_float_3_0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 954, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_cx = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":955 - * dx, dy = pt1 - * cx = (x2 - dx) * 3.0 - * cy = (y2 - dy) * 3.0 # <<<<<<<<<<<<<< - * bx = (x3 - x2) * 3.0 - cx - * by = (y3 - y2) * 3.0 - cy - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_y2, __pyx_v_dy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 955, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_2, __pyx_float_3_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 955, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_cy = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":956 - * cx = (x2 - dx) * 3.0 - * cy = (y2 - dy) * 3.0 - * bx = (x3 - x2) * 3.0 - cx # <<<<<<<<<<<<<< - * by = (y3 - y2) * 3.0 - cy - * ax = x4 - dx - cx - bx - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_x3, __pyx_v_x2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 956, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_float_3_0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 956, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_cx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 956, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_bx = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":957 - * cy = (y2 - dy) * 3.0 - * bx = (x3 - x2) * 3.0 - cx - * by = (y3 - y2) * 3.0 - cy # <<<<<<<<<<<<<< - * ax = x4 - dx - cx - bx - * ay = y4 - dy - cy - by - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_y3, __pyx_v_y2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 957, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_float_3_0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 957, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_cy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 957, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_by = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":958 - * bx = (x3 - x2) * 3.0 - cx - * by = (y3 - y2) * 3.0 - cy - * ax = x4 - dx - cx - bx # <<<<<<<<<<<<<< - * ay = y4 - dy - cy - by - * return (ax, ay), (bx, by), (cx, cy), (dx, dy) - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_x4, __pyx_v_dx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 958, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Subtract(__pyx_t_1, __pyx_v_cx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 958, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_bx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 958, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_ax = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":959 - * by = (y3 - y2) * 3.0 - cy - * ax = x4 - dx - cx - bx - * ay = y4 - dy - cy - by # <<<<<<<<<<<<<< - * return (ax, ay), (bx, by), (cx, cy), (dx, dy) - * - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_y4, __pyx_v_dy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 959, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Subtract(__pyx_t_1, __pyx_v_cy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 959, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_t_2, __pyx_v_by); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 959, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_ay = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":960 - * ax = x4 - dx - cx - bx - * ay = y4 - dy - cy - by - * return (ax, ay), (bx, by), (cx, cy), (dx, dy) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 960, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_ax); - __Pyx_GIVEREF(__pyx_v_ax); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_ax); - __Pyx_INCREF(__pyx_v_ay); - __Pyx_GIVEREF(__pyx_v_ay); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_ay); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 960, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_bx); - __Pyx_GIVEREF(__pyx_v_bx); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_bx); - __Pyx_INCREF(__pyx_v_by); - __Pyx_GIVEREF(__pyx_v_by); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_by); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 960, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_cx); - __Pyx_GIVEREF(__pyx_v_cx); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_cx); - __Pyx_INCREF(__pyx_v_cy); - __Pyx_GIVEREF(__pyx_v_cy); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_cy); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 960, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_dx); - __Pyx_GIVEREF(__pyx_v_dx); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_dx); - __Pyx_INCREF(__pyx_v_dy); - __Pyx_GIVEREF(__pyx_v_dy); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_v_dy); - __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 960, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_5 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":949 - * - * - * def calcCubicParameters(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicParameters", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_x2); - __Pyx_XDECREF(__pyx_v_y2); - __Pyx_XDECREF(__pyx_v_x3); - __Pyx_XDECREF(__pyx_v_y3); - __Pyx_XDECREF(__pyx_v_x4); - __Pyx_XDECREF(__pyx_v_y4); - __Pyx_XDECREF(__pyx_v_dx); - __Pyx_XDECREF(__pyx_v_dy); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":974 - * c=cython.complex, - * ) - * def calcCubicParametersC(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * c = (pt2 - pt1) * 3.0 - * b = (pt3 - pt2) * 3.0 - c - */ - -static CYTHON_INLINE PyObject *__pyx_f_9fontTools_4misc_11bezierTools_calcCubicParametersC(__pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4) { - __pyx_t_double_complex __pyx_v_a; - __pyx_t_double_complex __pyx_v_b; - __pyx_t_double_complex __pyx_v_c; - 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicParametersC", 0); - - /* "fontTools/misc/bezierTools.py":975 - * ) - * def calcCubicParametersC(pt1, pt2, pt3, pt4): - * c = (pt2 - pt1) * 3.0 # <<<<<<<<<<<<<< - * b = (pt3 - pt2) * 3.0 - c - * a = pt4 - pt1 - c - b - */ - __pyx_v_c = __Pyx_c_prod_double(__Pyx_c_diff_double(__pyx_v_pt2, __pyx_v_pt1), __pyx_t_double_complex_from_parts(3.0, 0)); - - /* "fontTools/misc/bezierTools.py":976 - * def calcCubicParametersC(pt1, pt2, pt3, pt4): - * c = (pt2 - pt1) * 3.0 - * b = (pt3 - pt2) * 3.0 - c # <<<<<<<<<<<<<< - * a = pt4 - pt1 - c - b - * return (a, b, c, pt1) - */ - __pyx_v_b = __Pyx_c_diff_double(__Pyx_c_prod_double(__Pyx_c_diff_double(__pyx_v_pt3, __pyx_v_pt2), __pyx_t_double_complex_from_parts(3.0, 0)), __pyx_v_c); - - /* "fontTools/misc/bezierTools.py":977 - * c = (pt2 - pt1) * 3.0 - * b = (pt3 - pt2) * 3.0 - c - * a = pt4 - pt1 - c - b # <<<<<<<<<<<<<< - * return (a, b, c, pt1) - * - */ - __pyx_v_a = __Pyx_c_diff_double(__Pyx_c_diff_double(__Pyx_c_diff_double(__pyx_v_pt4, __pyx_v_pt1), __pyx_v_c), __pyx_v_b); - - /* "fontTools/misc/bezierTools.py":978 - * b = (pt3 - pt2) * 3.0 - c - * a = pt4 - pt1 - c - b - * return (a, b, c, pt1) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_a); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 978, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_v_b); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 978, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 978, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_v_pt1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 978, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 978, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); - __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_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":974 - * c=cython.complex, - * ) - * def calcCubicParametersC(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * c = (pt2 - pt1) * 3.0 - * b = (pt3 - pt2) * 3.0 - c - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicParametersC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":981 - * - * - * def calcQuadraticPoints(a, b, c): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_55calcQuadraticPoints(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_54calcQuadraticPoints[] = "calcQuadraticPoints(a, b, c)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_55calcQuadraticPoints = {"calcQuadraticPoints", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_55calcQuadraticPoints, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_54calcQuadraticPoints}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_55calcQuadraticPoints(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_c = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcQuadraticPoints (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,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_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticPoints", 1, 3, 3, 1); __PYX_ERR(0, 981, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcQuadraticPoints", 1, 3, 3, 2); __PYX_ERR(0, 981, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcQuadraticPoints") < 0)) __PYX_ERR(0, 981, __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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_c = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcQuadraticPoints", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 981, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticPoints", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_54calcQuadraticPoints(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_54calcQuadraticPoints(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_x1 = NULL; - PyObject *__pyx_v_y1 = NULL; - PyObject *__pyx_v_x2 = NULL; - PyObject *__pyx_v_y2 = NULL; - PyObject *__pyx_v_x3 = NULL; - PyObject *__pyx_v_y3 = 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)(PyObject *); - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcQuadraticPoints", 0); - - /* "fontTools/misc/bezierTools.py":982 - * - * def calcQuadraticPoints(a, b, c): - * ax, ay = a # <<<<<<<<<<<<<< - * bx, by = b - * cx, cy = c - */ - if ((likely(PyTuple_CheckExact(__pyx_v_a))) || (PyList_CheckExact(__pyx_v_a))) { - PyObject* sequence = __pyx_v_a; - 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(0, 982, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 982, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 982, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 982, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 982, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 982, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_ax = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_ay = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":983 - * def calcQuadraticPoints(a, b, c): - * ax, ay = a - * bx, by = b # <<<<<<<<<<<<<< - * cx, cy = c - * x1 = cx - */ - if ((likely(PyTuple_CheckExact(__pyx_v_b))) || (PyList_CheckExact(__pyx_v_b))) { - PyObject* sequence = __pyx_v_b; - 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(0, 983, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_b); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 983, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 983, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_bx = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_by = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":984 - * ax, ay = a - * bx, by = b - * cx, cy = c # <<<<<<<<<<<<<< - * x1 = cx - * y1 = cy - */ - if ((likely(PyTuple_CheckExact(__pyx_v_c))) || (PyList_CheckExact(__pyx_v_c))) { - PyObject* sequence = __pyx_v_c; - 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(0, 984, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 984, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 984, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 984, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 984, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 984, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_cx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_cy = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":985 - * bx, by = b - * cx, cy = c - * x1 = cx # <<<<<<<<<<<<<< - * y1 = cy - * x2 = (bx * 0.5) + cx - */ - __Pyx_INCREF(__pyx_v_cx); - __pyx_v_x1 = __pyx_v_cx; - - /* "fontTools/misc/bezierTools.py":986 - * cx, cy = c - * x1 = cx - * y1 = cy # <<<<<<<<<<<<<< - * x2 = (bx * 0.5) + cx - * y2 = (by * 0.5) + cy - */ - __Pyx_INCREF(__pyx_v_cy); - __pyx_v_y1 = __pyx_v_cy; - - /* "fontTools/misc/bezierTools.py":987 - * x1 = cx - * y1 = cy - * x2 = (bx * 0.5) + cx # <<<<<<<<<<<<<< - * y2 = (by * 0.5) + cy - * x3 = ax + bx + cx - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_v_bx, __pyx_float_0_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 987, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_cx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 987, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":988 - * y1 = cy - * x2 = (bx * 0.5) + cx - * y2 = (by * 0.5) + cy # <<<<<<<<<<<<<< - * x3 = ax + bx + cx - * y3 = ay + by + cy - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_by, __pyx_float_0_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 988, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_cy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 988, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_y2 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":989 - * x2 = (bx * 0.5) + cx - * y2 = (by * 0.5) + cy - * x3 = ax + bx + cx # <<<<<<<<<<<<<< - * y3 = ay + by + cy - * return (x1, y1), (x2, y2), (x3, y3) - */ - __pyx_t_2 = PyNumber_Add(__pyx_v_ax, __pyx_v_bx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 989, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_cx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 989, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":990 - * y2 = (by * 0.5) + cy - * x3 = ax + bx + cx - * y3 = ay + by + cy # <<<<<<<<<<<<<< - * return (x1, y1), (x2, y2), (x3, y3) - * - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_ay, __pyx_v_by); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 990, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_cy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 990, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_y3 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":991 - * x3 = ax + bx + cx - * y3 = ay + by + cy - * return (x1, y1), (x2, y2), (x3, y3) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 991, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_x1); - __Pyx_GIVEREF(__pyx_v_x1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_x1); - __Pyx_INCREF(__pyx_v_y1); - __Pyx_GIVEREF(__pyx_v_y1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_y1); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 991, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_x2); - __Pyx_GIVEREF(__pyx_v_x2); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_x2); - __Pyx_INCREF(__pyx_v_y2); - __Pyx_GIVEREF(__pyx_v_y2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_y2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 991, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x3); - __Pyx_GIVEREF(__pyx_v_x3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x3); - __Pyx_INCREF(__pyx_v_y3); - __Pyx_GIVEREF(__pyx_v_y3); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_y3); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 991, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":981 - * - * - * def calcQuadraticPoints(a, b, c): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - - /* 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_5); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcQuadraticPoints", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_x1); - __Pyx_XDECREF(__pyx_v_y1); - __Pyx_XDECREF(__pyx_v_x2); - __Pyx_XDECREF(__pyx_v_y2); - __Pyx_XDECREF(__pyx_v_x3); - __Pyx_XDECREF(__pyx_v_y3); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":994 - * - * - * def calcCubicPoints(a, b, c, d): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_57calcCubicPoints(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_56calcCubicPoints[] = "calcCubicPoints(a, b, c, d)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_57calcCubicPoints = {"calcCubicPoints", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_57calcCubicPoints, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_56calcCubicPoints}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_57calcCubicPoints(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_c = 0; - PyObject *__pyx_v_d = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calcCubicPoints (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_c,&__pyx_n_s_d,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_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicPoints", 1, 4, 4, 1); __PYX_ERR(0, 994, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicPoints", 1, 4, 4, 2); __PYX_ERR(0, 994, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("calcCubicPoints", 1, 4, 4, 3); __PYX_ERR(0, 994, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calcCubicPoints") < 0)) __PYX_ERR(0, 994, __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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_c = values[2]; - __pyx_v_d = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("calcCubicPoints", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 994, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicPoints", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_56calcCubicPoints(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_c, __pyx_v_d); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_56calcCubicPoints(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_v_ax = NULL; - PyObject *__pyx_v_ay = NULL; - PyObject *__pyx_v_bx = NULL; - PyObject *__pyx_v_by = NULL; - PyObject *__pyx_v_cx = NULL; - PyObject *__pyx_v_cy = NULL; - PyObject *__pyx_v_dx = NULL; - PyObject *__pyx_v_dy = NULL; - PyObject *__pyx_v_x1 = NULL; - PyObject *__pyx_v_y1 = NULL; - PyObject *__pyx_v_x2 = NULL; - PyObject *__pyx_v_y2 = NULL; - PyObject *__pyx_v_x3 = NULL; - PyObject *__pyx_v_y3 = NULL; - PyObject *__pyx_v_x4 = NULL; - PyObject *__pyx_v_y4 = 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)(PyObject *); - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicPoints", 0); - - /* "fontTools/misc/bezierTools.py":995 - * - * def calcCubicPoints(a, b, c, d): - * ax, ay = a # <<<<<<<<<<<<<< - * bx, by = b - * cx, cy = c - */ - if ((likely(PyTuple_CheckExact(__pyx_v_a))) || (PyList_CheckExact(__pyx_v_a))) { - PyObject* sequence = __pyx_v_a; - 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(0, 995, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 995, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 995, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_a); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 995, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 995, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 995, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_ax = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_ay = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":996 - * def calcCubicPoints(a, b, c, d): - * ax, ay = a - * bx, by = b # <<<<<<<<<<<<<< - * cx, cy = c - * dx, dy = d - */ - if ((likely(PyTuple_CheckExact(__pyx_v_b))) || (PyList_CheckExact(__pyx_v_b))) { - PyObject* sequence = __pyx_v_b; - 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(0, 996, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 996, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 996, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_b); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 996, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 996, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 996, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_bx = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_by = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":997 - * ax, ay = a - * bx, by = b - * cx, cy = c # <<<<<<<<<<<<<< - * dx, dy = d - * x1 = dx - */ - if ((likely(PyTuple_CheckExact(__pyx_v_c))) || (PyList_CheckExact(__pyx_v_c))) { - PyObject* sequence = __pyx_v_c; - 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(0, 997, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 997, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 997, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 997, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 997, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 997, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_cx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_cy = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":998 - * bx, by = b - * cx, cy = c - * dx, dy = d # <<<<<<<<<<<<<< - * x1 = dx - * y1 = dy - */ - if ((likely(PyTuple_CheckExact(__pyx_v_d))) || (PyList_CheckExact(__pyx_v_d))) { - PyObject* sequence = __pyx_v_d; - 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(0, 998, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 998, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 998, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_d); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 998, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 998, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 998, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_v_dx = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_dy = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":999 - * cx, cy = c - * dx, dy = d - * x1 = dx # <<<<<<<<<<<<<< - * y1 = dy - * x2 = (cx / 3.0) + dx - */ - __Pyx_INCREF(__pyx_v_dx); - __pyx_v_x1 = __pyx_v_dx; - - /* "fontTools/misc/bezierTools.py":1000 - * dx, dy = d - * x1 = dx - * y1 = dy # <<<<<<<<<<<<<< - * x2 = (cx / 3.0) + dx - * y2 = (cy / 3.0) + dy - */ - __Pyx_INCREF(__pyx_v_dy); - __pyx_v_y1 = __pyx_v_dy; - - /* "fontTools/misc/bezierTools.py":1001 - * x1 = dx - * y1 = dy - * x2 = (cx / 3.0) + dx # <<<<<<<<<<<<<< - * y2 = (cy / 3.0) + dy - * x3 = (bx + cx) / 3.0 + x2 - */ - __pyx_t_1 = __Pyx_PyFloat_TrueDivideObjC(__pyx_v_cx, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1001, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_dx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1001, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_x2 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1002 - * y1 = dy - * x2 = (cx / 3.0) + dx - * y2 = (cy / 3.0) + dy # <<<<<<<<<<<<<< - * x3 = (bx + cx) / 3.0 + x2 - * y3 = (by + cy) / 3.0 + y2 - */ - __pyx_t_2 = __Pyx_PyFloat_TrueDivideObjC(__pyx_v_cy, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1002, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_dy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1002, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_y2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1003 - * x2 = (cx / 3.0) + dx - * y2 = (cy / 3.0) + dy - * x3 = (bx + cx) / 3.0 + x2 # <<<<<<<<<<<<<< - * y3 = (by + cy) / 3.0 + y2 - * x4 = ax + dx + cx + bx - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_bx, __pyx_v_cx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1003, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_1, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1003, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_x2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1003, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1004 - * y2 = (cy / 3.0) + dy - * x3 = (bx + cx) / 3.0 + x2 - * y3 = (by + cy) / 3.0 + y2 # <<<<<<<<<<<<<< - * x4 = ax + dx + cx + bx - * y4 = ay + dy + cy + by - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_by, __pyx_v_cy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1004, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyFloat_TrueDivideObjC(__pyx_t_1, __pyx_float_3_0, 3.0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1004, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_y2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1004, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_y3 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1005 - * x3 = (bx + cx) / 3.0 + x2 - * y3 = (by + cy) / 3.0 + y2 - * x4 = ax + dx + cx + bx # <<<<<<<<<<<<<< - * y4 = ay + dy + cy + by - * return (x1, y1), (x2, y2), (x3, y3), (x4, y4) - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_ax, __pyx_v_dx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1005, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_cx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1005, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_bx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1005, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x4 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1006 - * y3 = (by + cy) / 3.0 + y2 - * x4 = ax + dx + cx + bx - * y4 = ay + dy + cy + by # <<<<<<<<<<<<<< - * return (x1, y1), (x2, y2), (x3, y3), (x4, y4) - * - */ - __pyx_t_1 = PyNumber_Add(__pyx_v_ay, __pyx_v_dy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1006, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_cy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1006, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_v_by); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1006, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_y4 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1007 - * x4 = ax + dx + cx + bx - * y4 = ay + dy + cy + by - * return (x1, y1), (x2, y2), (x3, y3), (x4, y4) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1007, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_x1); - __Pyx_GIVEREF(__pyx_v_x1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_x1); - __Pyx_INCREF(__pyx_v_y1); - __Pyx_GIVEREF(__pyx_v_y1); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_y1); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1007, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_x2); - __Pyx_GIVEREF(__pyx_v_x2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_x2); - __Pyx_INCREF(__pyx_v_y2); - __Pyx_GIVEREF(__pyx_v_y2); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_y2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1007, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x3); - __Pyx_GIVEREF(__pyx_v_x3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x3); - __Pyx_INCREF(__pyx_v_y3); - __Pyx_GIVEREF(__pyx_v_y3); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_y3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1007, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_x4); - __Pyx_GIVEREF(__pyx_v_x4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_x4); - __Pyx_INCREF(__pyx_v_y4); - __Pyx_GIVEREF(__pyx_v_y4); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_v_y4); - __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1007, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_5 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":994 - * - * - * def calcCubicPoints(a, b, c, d): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicPoints", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ax); - __Pyx_XDECREF(__pyx_v_ay); - __Pyx_XDECREF(__pyx_v_bx); - __Pyx_XDECREF(__pyx_v_by); - __Pyx_XDECREF(__pyx_v_cx); - __Pyx_XDECREF(__pyx_v_cy); - __Pyx_XDECREF(__pyx_v_dx); - __Pyx_XDECREF(__pyx_v_dy); - __Pyx_XDECREF(__pyx_v_x1); - __Pyx_XDECREF(__pyx_v_y1); - __Pyx_XDECREF(__pyx_v_x2); - __Pyx_XDECREF(__pyx_v_y2); - __Pyx_XDECREF(__pyx_v_x3); - __Pyx_XDECREF(__pyx_v_y3); - __Pyx_XDECREF(__pyx_v_x4); - __Pyx_XDECREF(__pyx_v_y4); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1021 - * p4=cython.complex, - * ) - * def calcCubicPointsC(a, b, c, d): # <<<<<<<<<<<<<< - * p2 = c * (1 / 3) + d - * p3 = (b + c) * (1 / 3) + p2 - */ - -static CYTHON_INLINE PyObject *__pyx_f_9fontTools_4misc_11bezierTools_calcCubicPointsC(__pyx_t_double_complex __pyx_v_a, __pyx_t_double_complex __pyx_v_b, __pyx_t_double_complex __pyx_v_c, __pyx_t_double_complex __pyx_v_d) { - __pyx_t_double_complex __pyx_v_p2; - __pyx_t_double_complex __pyx_v_p3; - __pyx_t_double_complex __pyx_v_p4; - 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("calcCubicPointsC", 0); - - /* "fontTools/misc/bezierTools.py":1022 - * ) - * def calcCubicPointsC(a, b, c, d): - * p2 = c * (1 / 3) + d # <<<<<<<<<<<<<< - * p3 = (b + c) * (1 / 3) + p2 - * p4 = a + b + c + d - */ - __pyx_v_p2 = __Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_v_c, __pyx_t_double_complex_from_parts((1.0 / 3.0), 0)), __pyx_v_d); - - /* "fontTools/misc/bezierTools.py":1023 - * def calcCubicPointsC(a, b, c, d): - * p2 = c * (1 / 3) + d - * p3 = (b + c) * (1 / 3) + p2 # <<<<<<<<<<<<<< - * p4 = a + b + c + d - * return (d, p2, p3, p4) - */ - __pyx_v_p3 = __Pyx_c_sum_double(__Pyx_c_prod_double(__Pyx_c_sum_double(__pyx_v_b, __pyx_v_c), __pyx_t_double_complex_from_parts((1.0 / 3.0), 0)), __pyx_v_p2); - - /* "fontTools/misc/bezierTools.py":1024 - * p2 = c * (1 / 3) + d - * p3 = (b + c) * (1 / 3) + p2 - * p4 = a + b + c + d # <<<<<<<<<<<<<< - * return (d, p2, p3, p4) - * - */ - __pyx_v_p4 = __Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_sum_double(__pyx_v_a, __pyx_v_b), __pyx_v_c), __pyx_v_d); - - /* "fontTools/misc/bezierTools.py":1025 - * p3 = (b + c) * (1 / 3) + p2 - * p4 = a + b + c + d - * return (d, p2, p3, p4) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_d); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1025, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_v_p2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1025, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_PyComplex_FromComplex(__pyx_v_p3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1025, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_v_p4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1025, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1025, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); - __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_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1021 - * p4=cython.complex, - * ) - * def calcCubicPointsC(a, b, c, d): # <<<<<<<<<<<<<< - * p2 = c * (1 / 3) + d - * p3 = (b + c) * (1 / 3) + p2 - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("fontTools.misc.bezierTools.calcCubicPointsC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1033 - * - * - * def linePointAtT(pt1, pt2, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a line. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_59linePointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_58linePointAtT[] = "linePointAtT(pt1, pt2, t)\nFinds the point at time `t` on a line.\n\n Args:\n pt1, pt2: Coordinates of the line as 2D tuples.\n t: The time along the line.\n\n Returns:\n A 2D tuple with the coordinates of the point.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_59linePointAtT = {"linePointAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_59linePointAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_58linePointAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_59linePointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_t = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("linePointAtT (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_t,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("linePointAtT", 1, 3, 3, 1); __PYX_ERR(0, 1033, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("linePointAtT", 1, 3, 3, 2); __PYX_ERR(0, 1033, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "linePointAtT") < 0)) __PYX_ERR(0, 1033, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_t = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("linePointAtT", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1033, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.linePointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_58linePointAtT(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_58linePointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_t) { - 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("linePointAtT", 0); - - /* "fontTools/misc/bezierTools.py":1043 - * A 2D tuple with the coordinates of the point. - * """ - * return ((pt1[0] * (1 - t) + pt2[0] * t), (pt1[1] * (1 - t) + pt2[1] * t)) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_pt1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1043, __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(0, 1043, __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_t_2 = __Pyx_GetItemInt(__pyx_v_pt2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_2, __pyx_v_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_pt1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_pt2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, __pyx_v_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1033 - * - * - * def linePointAtT(pt1, pt2, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a line. - * - */ - - /* 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("fontTools.misc.bezierTools.linePointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1046 - * - * - * def quadraticPointAtT(pt1, pt2, pt3, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a quadratic curve. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_61quadraticPointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_60quadraticPointAtT[] = "quadraticPointAtT(pt1, pt2, pt3, t)\nFinds the point at time `t` on a quadratic curve.\n\n Args:\n pt1, pt2, pt3: Coordinates of the curve as 2D tuples.\n t: The time along the curve.\n\n Returns:\n A 2D tuple with the coordinates of the point.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_61quadraticPointAtT = {"quadraticPointAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_61quadraticPointAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_60quadraticPointAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_61quadraticPointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_t = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("quadraticPointAtT (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_t,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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("quadraticPointAtT", 1, 4, 4, 1); __PYX_ERR(0, 1046, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("quadraticPointAtT", 1, 4, 4, 2); __PYX_ERR(0, 1046, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("quadraticPointAtT", 1, 4, 4, 3); __PYX_ERR(0, 1046, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "quadraticPointAtT") < 0)) __PYX_ERR(0, 1046, __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_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_t = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("quadraticPointAtT", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1046, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.quadraticPointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_60quadraticPointAtT(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_60quadraticPointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_t) { - PyObject *__pyx_v_x = NULL; - PyObject *__pyx_v_y = 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("quadraticPointAtT", 0); - - /* "fontTools/misc/bezierTools.py":1056 - * A 2D tuple with the coordinates of the point. - * """ - * x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0] # <<<<<<<<<<<<<< - * y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1] - * return (x, y) - */ - __pyx_t_1 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1056, __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(0, 1056, __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_t_2 = __Pyx_GetItemInt(__pyx_v_pt1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_int_2, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, __pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_pt2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1056, __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_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_v_t, __pyx_v_t); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_pt3, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1056, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_x = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1057 - * """ - * x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0] - * y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1] # <<<<<<<<<<<<<< - * return (x, y) - * - */ - __pyx_t_1 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1057, __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(0, 1057, __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_t_2 = __Pyx_GetItemInt(__pyx_v_pt1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_int_2, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, __pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_pt2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1057, __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_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Multiply(__pyx_v_t, __pyx_v_t); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_pt3, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1057, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_y = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1058 - * x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0] - * y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1] - * return (x, y) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1058, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_x); - __Pyx_INCREF(__pyx_v_y); - __Pyx_GIVEREF(__pyx_v_y); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_y); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1046 - * - * - * def quadraticPointAtT(pt1, pt2, pt3, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a quadratic curve. - * - */ - - /* 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("fontTools.misc.bezierTools.quadraticPointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_x); - __Pyx_XDECREF(__pyx_v_y); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1061 - * - * - * def cubicPointAtT(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_63cubicPointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_62cubicPointAtT[] = "cubicPointAtT(pt1, pt2, pt3, pt4, t)\nFinds the point at time `t` on a cubic curve.\n\n Args:\n pt1, pt2, pt3, pt4: Coordinates of the curve as 2D tuples.\n t: The time along the curve.\n\n Returns:\n A 2D tuple with the coordinates of the point.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_63cubicPointAtT = {"cubicPointAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_63cubicPointAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_62cubicPointAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_63cubicPointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_pt1 = 0; - PyObject *__pyx_v_pt2 = 0; - PyObject *__pyx_v_pt3 = 0; - PyObject *__pyx_v_pt4 = 0; - PyObject *__pyx_v_t = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("cubicPointAtT (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,&__pyx_n_s_t,0}; - PyObject* values[5] = {0,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 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtT", 1, 5, 5, 1); __PYX_ERR(0, 1061, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtT", 1, 5, 5, 2); __PYX_ERR(0, 1061, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtT", 1, 5, 5, 3); __PYX_ERR(0, 1061, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtT", 1, 5, 5, 4); __PYX_ERR(0, 1061, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cubicPointAtT") < 0)) __PYX_ERR(0, 1061, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - 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); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_pt1 = values[0]; - __pyx_v_pt2 = values[1]; - __pyx_v_pt3 = values[2]; - __pyx_v_pt4 = values[3]; - __pyx_v_t = values[4]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("cubicPointAtT", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1061, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.cubicPointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_62cubicPointAtT(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_62cubicPointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pt1, PyObject *__pyx_v_pt2, PyObject *__pyx_v_pt3, PyObject *__pyx_v_pt4, PyObject *__pyx_v_t) { - PyObject *__pyx_v_t2 = NULL; - PyObject *__pyx_v__1_t = NULL; - PyObject *__pyx_v__1_t_2 = NULL; - PyObject *__pyx_v_x = NULL; - PyObject *__pyx_v_y = 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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cubicPointAtT", 0); - - /* "fontTools/misc/bezierTools.py":1071 - * A 2D tuple with the coordinates of the point. - * """ - * t2 = t * t # <<<<<<<<<<<<<< - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_t, __pyx_v_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1071, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_t2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1072 - * """ - * t2 = t * t - * _1_t = 1 - t # <<<<<<<<<<<<<< - * _1_t_2 = _1_t * _1_t - * x = ( - */ - __pyx_t_1 = __Pyx_PyInt_SubtractCObj(__pyx_int_1, __pyx_v_t, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1072, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__1_t = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1073 - * t2 = t * t - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t # <<<<<<<<<<<<<< - * x = ( - * _1_t_2 * _1_t * pt1[0] - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v__1_t, __pyx_v__1_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1073, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__1_t_2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1075 - * _1_t_2 = _1_t * _1_t - * x = ( - * _1_t_2 * _1_t * pt1[0] # <<<<<<<<<<<<<< - * + 3 * (_1_t_2 * t * pt2[0] + _1_t * t2 * pt3[0]) - * + t2 * t * pt4[0] - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v__1_t_2, __pyx_v__1_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1075, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_pt1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1075, __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(0, 1075, __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; - - /* "fontTools/misc/bezierTools.py":1076 - * x = ( - * _1_t_2 * _1_t * pt1[0] - * + 3 * (_1_t_2 * t * pt2[0] + _1_t * t2 * pt3[0]) # <<<<<<<<<<<<<< - * + t2 * t * pt4[0] - * ) - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_v__1_t_2, __pyx_v_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_pt2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_v__1_t, __pyx_v_t2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_pt3, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Multiply(__pyx_int_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1076, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - - /* "fontTools/misc/bezierTools.py":1077 - * _1_t_2 * _1_t * pt1[0] - * + 3 * (_1_t_2 * t * pt2[0] + _1_t * t2 * pt3[0]) - * + t2 * t * pt4[0] # <<<<<<<<<<<<<< - * ) - * y = ( - */ - __pyx_t_5 = PyNumber_Multiply(__pyx_v_t2, __pyx_v_t); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1077, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_pt4, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1077, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1077, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1077, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_x = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1080 - * ) - * y = ( - * _1_t_2 * _1_t * pt1[1] # <<<<<<<<<<<<<< - * + 3 * (_1_t_2 * t * pt2[1] + _1_t * t2 * pt3[1]) - * + t2 * t * pt4[1] - */ - __pyx_t_3 = PyNumber_Multiply(__pyx_v__1_t_2, __pyx_v__1_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1080, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_pt1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1080, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1080, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1081 - * y = ( - * _1_t_2 * _1_t * pt1[1] - * + 3 * (_1_t_2 * t * pt2[1] + _1_t * t2 * pt3[1]) # <<<<<<<<<<<<<< - * + t2 * t * pt4[1] - * ) - */ - __pyx_t_4 = PyNumber_Multiply(__pyx_v__1_t_2, __pyx_v_t); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_pt2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Multiply(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_v__1_t, __pyx_v_t2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_pt3, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_5, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_int_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1081, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1082 - * _1_t_2 * _1_t * pt1[1] - * + 3 * (_1_t_2 * t * pt2[1] + _1_t * t2 * pt3[1]) - * + t2 * t * pt4[1] # <<<<<<<<<<<<<< - * ) - * return (x, y) - */ - __pyx_t_1 = PyNumber_Multiply(__pyx_v_t2, __pyx_v_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1082, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_pt4, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1082, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1082, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1082, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_y = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1084 - * + t2 * t * pt4[1] - * ) - * return (x, y) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1084, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_x); - __Pyx_INCREF(__pyx_v_y); - __Pyx_GIVEREF(__pyx_v_y); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_y); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1061 - * - * - * def cubicPointAtT(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("fontTools.misc.bezierTools.cubicPointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_t2); - __Pyx_XDECREF(__pyx_v__1_t); - __Pyx_XDECREF(__pyx_v__1_t_2); - __Pyx_XDECREF(__pyx_v_x); - __Pyx_XDECREF(__pyx_v_y); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1096 - * ) - * @cython.locals(t2=cython.double, _1_t=cython.double, _1_t_2=cython.double) - * def cubicPointAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_65cubicPointAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_64cubicPointAtTC[] = "cubicPointAtTC(double complex pt1, double complex pt2, double complex pt3, double complex pt4, double t)\nFinds the point at time `t` on a cubic curve.\n\n Args:\n pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers.\n t: The time along the curve.\n\n Returns:\n A complex number with the coordinates of the point.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_65cubicPointAtTC = {"cubicPointAtTC", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_65cubicPointAtTC, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_64cubicPointAtTC}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_65cubicPointAtTC(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __pyx_t_double_complex __pyx_v_pt1; - __pyx_t_double_complex __pyx_v_pt2; - __pyx_t_double_complex __pyx_v_pt3; - __pyx_t_double_complex __pyx_v_pt4; - double __pyx_v_t; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("cubicPointAtTC (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pt1,&__pyx_n_s_pt2,&__pyx_n_s_pt3,&__pyx_n_s_pt4,&__pyx_n_s_t,0}; - PyObject* values[5] = {0,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 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_pt1)) != 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_pt2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtTC", 1, 5, 5, 1); __PYX_ERR(0, 1096, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt3)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtTC", 1, 5, 5, 2); __PYX_ERR(0, 1096, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt4)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtTC", 1, 5, 5, 3); __PYX_ERR(0, 1096, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cubicPointAtTC", 1, 5, 5, 4); __PYX_ERR(0, 1096, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cubicPointAtTC") < 0)) __PYX_ERR(0, 1096, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - 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); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_pt1 = __Pyx_PyComplex_As___pyx_t_double_complex(values[0]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1096, __pyx_L3_error) - __pyx_v_pt2 = __Pyx_PyComplex_As___pyx_t_double_complex(values[1]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1096, __pyx_L3_error) - __pyx_v_pt3 = __Pyx_PyComplex_As___pyx_t_double_complex(values[2]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1096, __pyx_L3_error) - __pyx_v_pt4 = __Pyx_PyComplex_As___pyx_t_double_complex(values[3]); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1096, __pyx_L3_error) - __pyx_v_t = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_t == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 1096, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("cubicPointAtTC", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1096, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.cubicPointAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_64cubicPointAtTC(__pyx_self, __pyx_v_pt1, __pyx_v_pt2, __pyx_v_pt3, __pyx_v_pt4, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_64cubicPointAtTC(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_double_complex __pyx_v_pt1, __pyx_t_double_complex __pyx_v_pt2, __pyx_t_double_complex __pyx_v_pt3, __pyx_t_double_complex __pyx_v_pt4, double __pyx_v_t) { - double __pyx_v_t2; - double __pyx_v__1_t; - double __pyx_v__1_t_2; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __pyx_t_double_complex __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cubicPointAtTC", 0); - - /* "fontTools/misc/bezierTools.py":1106 - * A complex number with the coordinates of the point. - * """ - * t2 = t * t # <<<<<<<<<<<<<< - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t - */ - __pyx_v_t2 = (__pyx_v_t * __pyx_v_t); - - /* "fontTools/misc/bezierTools.py":1107 - * """ - * t2 = t * t - * _1_t = 1 - t # <<<<<<<<<<<<<< - * _1_t_2 = _1_t * _1_t - * return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 - */ - __pyx_v__1_t = (1.0 - __pyx_v_t); - - /* "fontTools/misc/bezierTools.py":1108 - * t2 = t * t - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t # <<<<<<<<<<<<<< - * return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 - * - */ - __pyx_v__1_t_2 = (__pyx_v__1_t * __pyx_v__1_t); - - /* "fontTools/misc/bezierTools.py":1109 - * _1_t = 1 - t - * _1_t_2 = _1_t * _1_t - * return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4 # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_c_sum_double(__Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v__1_t_2 * __pyx_v__1_t), 0), __pyx_v_pt1), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(3, 0), __Pyx_c_sum_double(__Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v__1_t_2 * __pyx_v_t), 0), __pyx_v_pt2), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v__1_t * __pyx_v_t2), 0), __pyx_v_pt3)))), __Pyx_c_prod_double(__pyx_t_double_complex_from_parts((__pyx_v_t2 * __pyx_v_t), 0), __pyx_v_pt4)); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1109, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1096 - * ) - * @cython.locals(t2=cython.double, _1_t=cython.double, _1_t_2=cython.double) - * def cubicPointAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("fontTools.misc.bezierTools.cubicPointAtTC", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1112 - * - * - * def segmentPointAtT(seg, t): # <<<<<<<<<<<<<< - * if len(seg) == 2: - * return linePointAtT(*seg, t) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_67segmentPointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_66segmentPointAtT[] = "segmentPointAtT(seg, t)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_67segmentPointAtT = {"segmentPointAtT", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_67segmentPointAtT, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_66segmentPointAtT}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_67segmentPointAtT(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_seg = 0; - PyObject *__pyx_v_t = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("segmentPointAtT (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_seg,&__pyx_n_s_t,0}; - PyObject* values[2] = {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 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_seg)) != 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_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("segmentPointAtT", 1, 2, 2, 1); __PYX_ERR(0, 1112, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "segmentPointAtT") < 0)) __PYX_ERR(0, 1112, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_seg = values[0]; - __pyx_v_t = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("segmentPointAtT", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1112, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.segmentPointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_66segmentPointAtT(__pyx_self, __pyx_v_seg, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_66segmentPointAtT(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_seg, PyObject *__pyx_v_t) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __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; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("segmentPointAtT", 0); - - /* "fontTools/misc/bezierTools.py":1113 - * - * def segmentPointAtT(seg, t): - * if len(seg) == 2: # <<<<<<<<<<<<<< - * return linePointAtT(*seg, t) - * elif len(seg) == 3: - */ - __pyx_t_1 = PyObject_Length(__pyx_v_seg); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1113, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 2) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1114 - * def segmentPointAtT(seg, t): - * if len(seg) == 2: - * return linePointAtT(*seg, t) # <<<<<<<<<<<<<< - * elif len(seg) == 3: - * return quadraticPointAtT(*seg, t) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_linePointAtT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1114, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_seg); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1114, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1114, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_t); - __pyx_t_6 = PyNumber_Add(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1114, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1114, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1113 - * - * def segmentPointAtT(seg, t): - * if len(seg) == 2: # <<<<<<<<<<<<<< - * return linePointAtT(*seg, t) - * elif len(seg) == 3: - */ - } - - /* "fontTools/misc/bezierTools.py":1115 - * if len(seg) == 2: - * return linePointAtT(*seg, t) - * elif len(seg) == 3: # <<<<<<<<<<<<<< - * return quadraticPointAtT(*seg, t) - * elif len(seg) == 4: - */ - __pyx_t_1 = PyObject_Length(__pyx_v_seg); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1115, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 3) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1116 - * return linePointAtT(*seg, t) - * elif len(seg) == 3: - * return quadraticPointAtT(*seg, t) # <<<<<<<<<<<<<< - * elif len(seg) == 4: - * return cubicPointAtT(*seg, t) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_quadraticPointAtT); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PySequence_Tuple(__pyx_v_seg); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_t); - __pyx_t_4 = PyNumber_Add(__pyx_t_6, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1115 - * if len(seg) == 2: - * return linePointAtT(*seg, t) - * elif len(seg) == 3: # <<<<<<<<<<<<<< - * return quadraticPointAtT(*seg, t) - * elif len(seg) == 4: - */ - } - - /* "fontTools/misc/bezierTools.py":1117 - * elif len(seg) == 3: - * return quadraticPointAtT(*seg, t) - * elif len(seg) == 4: # <<<<<<<<<<<<<< - * return cubicPointAtT(*seg, t) - * raise ValueError("Unknown curve degree") - */ - __pyx_t_1 = PyObject_Length(__pyx_v_seg); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1117, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 4) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1118 - * return quadraticPointAtT(*seg, t) - * elif len(seg) == 4: - * return cubicPointAtT(*seg, t) # <<<<<<<<<<<<<< - * raise ValueError("Unknown curve degree") - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_cubicPointAtT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_seg); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_t); - __pyx_t_6 = PyNumber_Add(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1117 - * elif len(seg) == 3: - * return quadraticPointAtT(*seg, t) - * elif len(seg) == 4: # <<<<<<<<<<<<<< - * return cubicPointAtT(*seg, t) - * raise ValueError("Unknown curve degree") - */ - } - - /* "fontTools/misc/bezierTools.py":1119 - * elif len(seg) == 4: - * return cubicPointAtT(*seg, t) - * raise ValueError("Unknown curve degree") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1119, __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(0, 1119, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1112 - * - * - * def segmentPointAtT(seg, t): # <<<<<<<<<<<<<< - * if len(seg) == 2: - * return linePointAtT(*seg, t) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("fontTools.misc.bezierTools.segmentPointAtT", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1127 - * - * - * def _line_t_of_pt(s, e, pt): # <<<<<<<<<<<<<< - * sx, sy = s - * ex, ey = e - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_69_line_t_of_pt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_68_line_t_of_pt[] = "_line_t_of_pt(s, e, pt)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_69_line_t_of_pt = {"_line_t_of_pt", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_69_line_t_of_pt, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_68_line_t_of_pt}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_69_line_t_of_pt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_s = 0; - PyObject *__pyx_v_e = 0; - PyObject *__pyx_v_pt = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_line_t_of_pt (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_s,&__pyx_n_s_e,&__pyx_n_s_pt,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_s)) != 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_e)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_line_t_of_pt", 1, 3, 3, 1); __PYX_ERR(0, 1127, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pt)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_line_t_of_pt", 1, 3, 3, 2); __PYX_ERR(0, 1127, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_line_t_of_pt") < 0)) __PYX_ERR(0, 1127, __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_s = values[0]; - __pyx_v_e = values[1]; - __pyx_v_pt = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_line_t_of_pt", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1127, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._line_t_of_pt", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_68_line_t_of_pt(__pyx_self, __pyx_v_s, __pyx_v_e, __pyx_v_pt); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_68_line_t_of_pt(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_s, PyObject *__pyx_v_e, PyObject *__pyx_v_pt) { - PyObject *__pyx_v_sx = NULL; - PyObject *__pyx_v_sy = NULL; - PyObject *__pyx_v_ex = NULL; - PyObject *__pyx_v_ey = NULL; - PyObject *__pyx_v_px = NULL; - PyObject *__pyx_v_py = 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)(PyObject *); - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_line_t_of_pt", 0); - - /* "fontTools/misc/bezierTools.py":1128 - * - * def _line_t_of_pt(s, e, pt): - * sx, sy = s # <<<<<<<<<<<<<< - * ex, ey = e - * px, py = pt - */ - if ((likely(PyTuple_CheckExact(__pyx_v_s))) || (PyList_CheckExact(__pyx_v_s))) { - PyObject* sequence = __pyx_v_s; - 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(0, 1128, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1128, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1128, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_s); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1128, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1128, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1128, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_sx = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_sy = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1129 - * def _line_t_of_pt(s, e, pt): - * sx, sy = s - * ex, ey = e # <<<<<<<<<<<<<< - * px, py = pt - * if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon: - */ - if ((likely(PyTuple_CheckExact(__pyx_v_e))) || (PyList_CheckExact(__pyx_v_e))) { - PyObject* sequence = __pyx_v_e; - 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(0, 1129, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1129, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1129, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_e); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1129, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1129, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1129, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_ex = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_ey = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1130 - * sx, sy = s - * ex, ey = e - * px, py = pt # <<<<<<<<<<<<<< - * if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon: - * # Line is a point! - */ - if ((likely(PyTuple_CheckExact(__pyx_v_pt))) || (PyList_CheckExact(__pyx_v_pt))) { - PyObject* sequence = __pyx_v_pt; - 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(0, 1130, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_pt); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1130, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1130, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_px = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_py = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1131 - * ex, ey = e - * px, py = pt - * if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon: # <<<<<<<<<<<<<< - * # Line is a point! - * return -1 - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_sx, __pyx_v_ex); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyNumber_Absolute(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L10_bool_binop_done; - } - __pyx_t_3 = PyNumber_Subtract(__pyx_v_sy, __pyx_v_ey); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyNumber_Absolute(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_epsilon); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_2, __pyx_t_3, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 1131, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_t_6; - __pyx_L10_bool_binop_done:; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1133 - * if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon: - * # Line is a point! - * return -1 # <<<<<<<<<<<<<< - * # Use the largest - * if abs(sx - ex) > abs(sy - ey): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_int_neg_1); - __pyx_r = __pyx_int_neg_1; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1131 - * ex, ey = e - * px, py = pt - * if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon: # <<<<<<<<<<<<<< - * # Line is a point! - * return -1 - */ - } - - /* "fontTools/misc/bezierTools.py":1135 - * return -1 - * # Use the largest - * if abs(sx - ex) > abs(sy - ey): # <<<<<<<<<<<<<< - * return (px - sx) / (ex - sx) - * else: - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_sx, __pyx_v_ex); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyNumber_Absolute(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_v_sy, __pyx_v_ey); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyNumber_Absolute(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_GT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1135, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1135, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1136 - * # Use the largest - * if abs(sx - ex) > abs(sy - ey): - * return (px - sx) / (ex - sx) # <<<<<<<<<<<<<< - * else: - * return (py - sy) / (ey - sy) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyNumber_Subtract(__pyx_v_px, __pyx_v_sx); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Subtract(__pyx_v_ex, __pyx_v_sx); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1136, __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; - - /* "fontTools/misc/bezierTools.py":1135 - * return -1 - * # Use the largest - * if abs(sx - ex) > abs(sy - ey): # <<<<<<<<<<<<<< - * return (px - sx) / (ex - sx) - * else: - */ - } - - /* "fontTools/misc/bezierTools.py":1138 - * return (px - sx) / (ex - sx) - * else: - * return (py - sy) / (ey - sy) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyNumber_Subtract(__pyx_v_py, __pyx_v_sy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Subtract(__pyx_v_ey, __pyx_v_sy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - } - - /* "fontTools/misc/bezierTools.py":1127 - * - * - * def _line_t_of_pt(s, e, pt): # <<<<<<<<<<<<<< - * sx, sy = s - * ex, ey = e - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.misc.bezierTools._line_t_of_pt", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_sx); - __Pyx_XDECREF(__pyx_v_sy); - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_XDECREF(__pyx_v_ey); - __Pyx_XDECREF(__pyx_v_px); - __Pyx_XDECREF(__pyx_v_py); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1141 - * - * - * def _both_points_are_on_same_side_of_origin(a, b, origin): # <<<<<<<<<<<<<< - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_71_both_points_are_on_same_side_of_origin(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_70_both_points_are_on_same_side_of_origin[] = "_both_points_are_on_same_side_of_origin(a, b, origin)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_71_both_points_are_on_same_side_of_origin = {"_both_points_are_on_same_side_of_origin", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_71_both_points_are_on_same_side_of_origin, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_70_both_points_are_on_same_side_of_origin}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_71_both_points_are_on_same_side_of_origin(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_origin = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_both_points_are_on_same_side_of_origin (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_origin,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_a)) != 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_b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_both_points_are_on_same_side_of_origin", 1, 3, 3, 1); __PYX_ERR(0, 1141, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_origin)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_both_points_are_on_same_side_of_origin", 1, 3, 3, 2); __PYX_ERR(0, 1141, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_both_points_are_on_same_side_of_origin") < 0)) __PYX_ERR(0, 1141, __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_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_origin = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_both_points_are_on_same_side_of_origin", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1141, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._both_points_are_on_same_side_of_origin", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_70_both_points_are_on_same_side_of_origin(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_origin); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_70_both_points_are_on_same_side_of_origin(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_origin) { - PyObject *__pyx_v_xDiff = NULL; - PyObject *__pyx_v_yDiff = 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; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_both_points_are_on_same_side_of_origin", 0); - - /* "fontTools/misc/bezierTools.py":1142 - * - * def _both_points_are_on_same_side_of_origin(a, b, origin): - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) # <<<<<<<<<<<<<< - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) - * return not (xDiff <= 0.0 and yDiff <= 0.0) - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_a, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_origin, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1142, __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_t_2 = __Pyx_GetItemInt(__pyx_v_b, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_origin, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Subtract(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_xDiff = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1143 - * def _both_points_are_on_same_side_of_origin(a, b, origin): - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) # <<<<<<<<<<<<<< - * return not (xDiff <= 0.0 and yDiff <= 0.0) - * - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_a, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_origin, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_b, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_origin, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Subtract(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_yDiff = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1144 - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) - * return not (xDiff <= 0.0 and yDiff <= 0.0) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_RichCompare(__pyx_v_xDiff, __pyx_float_0_0, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1144, __pyx_L1_error) - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 1144, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L3_bool_binop_done; - } - __pyx_t_1 = PyObject_RichCompare(__pyx_v_yDiff, __pyx_float_0_0, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1144, __pyx_L1_error) - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 1144, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_t_6; - __pyx_L3_bool_binop_done:; - __pyx_t_1 = __Pyx_PyBool_FromLong((!__pyx_t_5)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1144, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1141 - * - * - * def _both_points_are_on_same_side_of_origin(a, b, origin): # <<<<<<<<<<<<<< - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) - */ - - /* 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("fontTools.misc.bezierTools._both_points_are_on_same_side_of_origin", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_xDiff); - __Pyx_XDECREF(__pyx_v_yDiff); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1147 - * - * - * def lineLineIntersections(s1, e1, s2, e2): # <<<<<<<<<<<<<< - * """Finds intersections between two line segments. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_73lineLineIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_72lineLineIntersections[] = "lineLineIntersections(s1, e1, s2, e2)\nFinds intersections between two line segments.\n\n Args:\n s1, e1: Coordinates of the first line as 2D tuples.\n s2, e2: Coordinates of the second line as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n\n >>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))\n >>> len(a)\n 1\n >>> intersection = a[0]\n >>> intersection.pt\n (374.44882952482897, 313.73458370177315)\n >>> (intersection.t1, intersection.t2)\n (0.45069111555824465, 0.5408153767394238)\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_73lineLineIntersections = {"lineLineIntersections", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_73lineLineIntersections, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_72lineLineIntersections}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_73lineLineIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_s1 = 0; - PyObject *__pyx_v_e1 = 0; - PyObject *__pyx_v_s2 = 0; - PyObject *__pyx_v_e2 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("lineLineIntersections (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_s1,&__pyx_n_s_e1,&__pyx_n_s_s2,&__pyx_n_s_e2,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_s1)) != 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_e1)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("lineLineIntersections", 1, 4, 4, 1); __PYX_ERR(0, 1147, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_s2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("lineLineIntersections", 1, 4, 4, 2); __PYX_ERR(0, 1147, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_e2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("lineLineIntersections", 1, 4, 4, 3); __PYX_ERR(0, 1147, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "lineLineIntersections") < 0)) __PYX_ERR(0, 1147, __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_s1 = values[0]; - __pyx_v_e1 = values[1]; - __pyx_v_s2 = values[2]; - __pyx_v_e2 = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("lineLineIntersections", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1147, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.lineLineIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_72lineLineIntersections(__pyx_self, __pyx_v_s1, __pyx_v_e1, __pyx_v_s2, __pyx_v_e2); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_72lineLineIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_s1, PyObject *__pyx_v_e1, PyObject *__pyx_v_s2, PyObject *__pyx_v_e2) { - PyObject *__pyx_v_s1x = NULL; - PyObject *__pyx_v_s1y = NULL; - PyObject *__pyx_v_e1x = NULL; - PyObject *__pyx_v_e1y = NULL; - PyObject *__pyx_v_s2x = NULL; - PyObject *__pyx_v_s2y = NULL; - PyObject *__pyx_v_e2x = NULL; - PyObject *__pyx_v_e2y = NULL; - PyObject *__pyx_v_x = NULL; - PyObject *__pyx_v_slope34 = NULL; - PyObject *__pyx_v_y = NULL; - PyObject *__pyx_v_pt = NULL; - PyObject *__pyx_v_slope12 = 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)(PyObject *); - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("lineLineIntersections", 0); - - /* "fontTools/misc/bezierTools.py":1170 - * (0.45069111555824465, 0.5408153767394238) - * """ - * s1x, s1y = s1 # <<<<<<<<<<<<<< - * e1x, e1y = e1 - * s2x, s2y = s2 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_s1))) || (PyList_CheckExact(__pyx_v_s1))) { - PyObject* sequence = __pyx_v_s1; - 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(0, 1170, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1170, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1170, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_s1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1170, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1170, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1170, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_s1x = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_s1y = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1171 - * """ - * s1x, s1y = s1 - * e1x, e1y = e1 # <<<<<<<<<<<<<< - * s2x, s2y = s2 - * e2x, e2y = e2 - */ - if ((likely(PyTuple_CheckExact(__pyx_v_e1))) || (PyList_CheckExact(__pyx_v_e1))) { - PyObject* sequence = __pyx_v_e1; - 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(0, 1171, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_e1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1171, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1171, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_e1x = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_e1y = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1172 - * s1x, s1y = s1 - * e1x, e1y = e1 - * s2x, s2y = s2 # <<<<<<<<<<<<<< - * e2x, e2y = e2 - * if ( - */ - if ((likely(PyTuple_CheckExact(__pyx_v_s2))) || (PyList_CheckExact(__pyx_v_s2))) { - PyObject* sequence = __pyx_v_s2; - 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(0, 1172, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1172, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1172, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_s2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1172, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1172, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1172, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_v_s2x = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_s2y = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1173 - * e1x, e1y = e1 - * s2x, s2y = s2 - * e2x, e2y = e2 # <<<<<<<<<<<<<< - * if ( - * math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x) - */ - if ((likely(PyTuple_CheckExact(__pyx_v_e2))) || (PyList_CheckExact(__pyx_v_e2))) { - PyObject* sequence = __pyx_v_e2; - 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(0, 1173, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1173, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1173, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_v_e2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1173, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_1 = __pyx_t_4(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_4(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1173, __pyx_L1_error) - __pyx_t_4 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1173, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_v_e2x = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_e2y = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1175 - * e2x, e2y = e2 - * if ( - * math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x) # <<<<<<<<<<<<<< - * ): # Parallel vertical - * return [] - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_math); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_isclose); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - __pyx_t_6 = 0; - 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_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s2x, __pyx_v_e2x}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s2x, __pyx_v_e2x}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_s2x); - __Pyx_GIVEREF(__pyx_v_s2x); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_s2x); - __Pyx_INCREF(__pyx_v_e2x); - __Pyx_GIVEREF(__pyx_v_e2x); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_e2x); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_8) { - } else { - __pyx_t_5 = __pyx_t_8; - goto __pyx_L12_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_math); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_isclose); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_s1x, __pyx_v_e1x}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_s1x, __pyx_v_e1x}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_s1x); - __Pyx_GIVEREF(__pyx_v_s1x); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_6, __pyx_v_s1x); - __Pyx_INCREF(__pyx_v_e1x); - __Pyx_GIVEREF(__pyx_v_e1x); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_6, __pyx_v_e1x); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_8) { - } else { - __pyx_t_5 = __pyx_t_8; - goto __pyx_L12_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_math); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_isclose); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_s1x, __pyx_v_s2x}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_s1x, __pyx_v_s2x}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_3 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_s1x); - __Pyx_GIVEREF(__pyx_v_s1x); - PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_6, __pyx_v_s1x); - __Pyx_INCREF(__pyx_v_s2x); - __Pyx_GIVEREF(__pyx_v_s2x); - PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_6, __pyx_v_s2x); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1175, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_9 = ((!__pyx_t_8) != 0); - __pyx_t_5 = __pyx_t_9; - __pyx_L12_bool_binop_done:; - - /* "fontTools/misc/bezierTools.py":1174 - * s2x, s2y = s2 - * e2x, e2y = e2 - * if ( # <<<<<<<<<<<<<< - * math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x) - * ): # Parallel vertical - */ - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1177 - * math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x) - * ): # Parallel vertical - * return [] # <<<<<<<<<<<<<< - * if ( - * math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1174 - * s2x, s2y = s2 - * e2x, e2y = e2 - * if ( # <<<<<<<<<<<<<< - * math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x) - * ): # Parallel vertical - */ - } - - /* "fontTools/misc/bezierTools.py":1179 - * return [] - * if ( - * math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y) # <<<<<<<<<<<<<< - * ): # Parallel horizontal - * return [] - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_math); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_isclose); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - __pyx_t_6 = 0; - 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_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s2y, __pyx_v_e2y}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s2y, __pyx_v_e2y}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_s2y); - __Pyx_GIVEREF(__pyx_v_s2y); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_s2y); - __Pyx_INCREF(__pyx_v_e2y); - __Pyx_GIVEREF(__pyx_v_e2y); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_e2y); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_9) { - } else { - __pyx_t_5 = __pyx_t_9; - goto __pyx_L16_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_math); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_isclose); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_s1y, __pyx_v_e1y}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_s1y, __pyx_v_e1y}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_s1y); - __Pyx_GIVEREF(__pyx_v_s1y); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_6, __pyx_v_s1y); - __Pyx_INCREF(__pyx_v_e1y); - __Pyx_GIVEREF(__pyx_v_e1y); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_6, __pyx_v_e1y); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_9) { - } else { - __pyx_t_5 = __pyx_t_9; - goto __pyx_L16_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_math); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_isclose); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_s1y, __pyx_v_s2y}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_s1y, __pyx_v_s2y}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_3 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_s1y); - __Pyx_GIVEREF(__pyx_v_s1y); - PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_6, __pyx_v_s1y); - __Pyx_INCREF(__pyx_v_s2y); - __Pyx_GIVEREF(__pyx_v_s2y); - PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_6, __pyx_v_s2y); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 1179, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = ((!__pyx_t_9) != 0); - __pyx_t_5 = __pyx_t_8; - __pyx_L16_bool_binop_done:; - - /* "fontTools/misc/bezierTools.py":1178 - * ): # Parallel vertical - * return [] - * if ( # <<<<<<<<<<<<<< - * math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y) - * ): # Parallel horizontal - */ - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1181 - * math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y) - * ): # Parallel horizontal - * return [] # <<<<<<<<<<<<<< - * if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny - * return [] - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1181, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1178 - * ): # Parallel vertical - * return [] - * if ( # <<<<<<<<<<<<<< - * math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y) - * ): # Parallel horizontal - */ - } - - /* "fontTools/misc/bezierTools.py":1182 - * ): # Parallel horizontal - * return [] - * if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny # <<<<<<<<<<<<<< - * return [] - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_math); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_isclose); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - __pyx_t_6 = 0; - 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_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s2x, __pyx_v_e2x}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s2x, __pyx_v_e2x}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_s2x); - __Pyx_GIVEREF(__pyx_v_s2x); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_s2x); - __Pyx_INCREF(__pyx_v_e2x); - __Pyx_GIVEREF(__pyx_v_e2x); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_e2x); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_8) { - } else { - __pyx_t_5 = __pyx_t_8; - goto __pyx_L20_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_math); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_isclose); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_s2y, __pyx_v_e2y}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_s2y, __pyx_v_e2y}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_s2y); - __Pyx_GIVEREF(__pyx_v_s2y); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_6, __pyx_v_s2y); - __Pyx_INCREF(__pyx_v_e2y); - __Pyx_GIVEREF(__pyx_v_e2y); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_6, __pyx_v_e2y); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1182, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_t_8; - __pyx_L20_bool_binop_done:; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1183 - * return [] - * if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny - * return [] # <<<<<<<<<<<<<< - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny - * return [] - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1183, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1182 - * ): # Parallel horizontal - * return [] - * if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny # <<<<<<<<<<<<<< - * return [] - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny - */ - } - - /* "fontTools/misc/bezierTools.py":1184 - * if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny - * return [] - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny # <<<<<<<<<<<<<< - * return [] - * if math.isclose(e1x, s1x): - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_math); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_isclose); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_s1x, __pyx_v_e1x}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_s1x, __pyx_v_e1x}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_3 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_s1x); - __Pyx_GIVEREF(__pyx_v_s1x); - PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_6, __pyx_v_s1x); - __Pyx_INCREF(__pyx_v_e1x); - __Pyx_GIVEREF(__pyx_v_e1x); - PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_6, __pyx_v_e1x); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_8) { - } else { - __pyx_t_5 = __pyx_t_8; - goto __pyx_L23_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_math); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_isclose); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - __pyx_t_6 = 0; - 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_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s1y, __pyx_v_e1y}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_s1y, __pyx_v_e1y}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_s1y); - __Pyx_GIVEREF(__pyx_v_s1y); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_s1y); - __Pyx_INCREF(__pyx_v_e1y); - __Pyx_GIVEREF(__pyx_v_e1y); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_e1y); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1184, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_t_8; - __pyx_L23_bool_binop_done:; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1185 - * return [] - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny - * return [] # <<<<<<<<<<<<<< - * if math.isclose(e1x, s1x): - * x = s1x - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1185, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1184 - * if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny - * return [] - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny # <<<<<<<<<<<<<< - * return [] - * if math.isclose(e1x, s1x): - */ - } - - /* "fontTools/misc/bezierTools.py":1186 - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny - * return [] - * if math.isclose(e1x, s1x): # <<<<<<<<<<<<<< - * x = s1x - * slope34 = (e2y - s2y) / (e2x - s2x) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_math); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_isclose); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_e1x, __pyx_v_s1x}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_e1x, __pyx_v_s1x}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_e1x); - __Pyx_GIVEREF(__pyx_v_e1x); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_6, __pyx_v_e1x); - __Pyx_INCREF(__pyx_v_s1x); - __Pyx_GIVEREF(__pyx_v_s1x); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_6, __pyx_v_s1x); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1186, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1187 - * return [] - * if math.isclose(e1x, s1x): - * x = s1x # <<<<<<<<<<<<<< - * slope34 = (e2y - s2y) / (e2x - s2x) - * y = slope34 * (x - s2x) + s2y - */ - __Pyx_INCREF(__pyx_v_s1x); - __pyx_v_x = __pyx_v_s1x; - - /* "fontTools/misc/bezierTools.py":1188 - * if math.isclose(e1x, s1x): - * x = s1x - * slope34 = (e2y - s2y) / (e2x - s2x) # <<<<<<<<<<<<<< - * y = slope34 * (x - s2x) + s2y - * pt = (x, y) - */ - __pyx_t_1 = PyNumber_Subtract(__pyx_v_e2y, __pyx_v_s2y); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1188, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PyNumber_Subtract(__pyx_v_e2x, __pyx_v_s2x); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1188, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1188, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_slope34 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1189 - * x = s1x - * slope34 = (e2y - s2y) / (e2x - s2x) - * y = slope34 * (x - s2x) + s2y # <<<<<<<<<<<<<< - * pt = (x, y) - * return [ - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_x, __pyx_v_s2x); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PyNumber_Multiply(__pyx_v_slope34, __pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_7, __pyx_v_s2y); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_y = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1190 - * slope34 = (e2y - s2y) / (e2x - s2x) - * y = slope34 * (x - s2x) + s2y - * pt = (x, y) # <<<<<<<<<<<<<< - * return [ - * Intersection( - */ - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1190, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_x); - __Pyx_INCREF(__pyx_v_y); - __Pyx_GIVEREF(__pyx_v_y); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_y); - __pyx_v_pt = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1191 - * y = slope34 * (x - s2x) + s2y - * pt = (x, y) - * return [ # <<<<<<<<<<<<<< - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - */ - __Pyx_XDECREF(__pyx_r); - - /* "fontTools/misc/bezierTools.py":1192 - * pt = (x, y) - * return [ - * Intersection( # <<<<<<<<<<<<<< - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_Intersection); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":1193 - * return [ - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) # <<<<<<<<<<<<<< - * ) - * ] - */ - __pyx_t_7 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_pt, __pyx_v_pt) < 0) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_v_s1, __pyx_v_e1, __pyx_v_pt}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_v_s1, __pyx_v_e1, __pyx_v_pt}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_v_s1); - __Pyx_GIVEREF(__pyx_v_s1); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_6, __pyx_v_s1); - __Pyx_INCREF(__pyx_v_e1); - __Pyx_GIVEREF(__pyx_v_e1); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_6, __pyx_v_e1); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_6, __pyx_v_pt); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_11, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_t1, __pyx_t_1) < 0) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_11 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_v_s2, __pyx_v_e2, __pyx_v_pt}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_v_s2, __pyx_v_e2, __pyx_v_pt}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_10 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_11) { - __Pyx_GIVEREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_11); __pyx_t_11 = NULL; - } - __Pyx_INCREF(__pyx_v_s2); - __Pyx_GIVEREF(__pyx_v_s2); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_6, __pyx_v_s2); - __Pyx_INCREF(__pyx_v_e2); - __Pyx_GIVEREF(__pyx_v_e2); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_6, __pyx_v_e2); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_6, __pyx_v_pt); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_t2, __pyx_t_1) < 0) __PYX_ERR(0, 1193, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1192 - * pt = (x, y) - * return [ - * Intersection( # <<<<<<<<<<<<<< - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - * ) - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_empty_tuple, __pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1191 - * y = slope34 * (x - s2x) + s2y - * pt = (x, y) - * return [ # <<<<<<<<<<<<<< - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - */ - __pyx_t_7 = PyList_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1191, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_7, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_7; - __pyx_t_7 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1186 - * if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny - * return [] - * if math.isclose(e1x, s1x): # <<<<<<<<<<<<<< - * x = s1x - * slope34 = (e2y - s2y) / (e2x - s2x) - */ - } - - /* "fontTools/misc/bezierTools.py":1196 - * ) - * ] - * if math.isclose(s2x, e2x): # <<<<<<<<<<<<<< - * x = s2x - * slope12 = (e1y - s1y) / (e1x - s1x) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_math); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_isclose); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_v_s2x, __pyx_v_e2x}; - __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_v_s2x, __pyx_v_e2x}; - __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - { - __pyx_t_3 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_INCREF(__pyx_v_s2x); - __Pyx_GIVEREF(__pyx_v_s2x); - PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_6, __pyx_v_s2x); - __Pyx_INCREF(__pyx_v_e2x); - __Pyx_GIVEREF(__pyx_v_e2x); - PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_6, __pyx_v_e2x); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1196, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1197 - * ] - * if math.isclose(s2x, e2x): - * x = s2x # <<<<<<<<<<<<<< - * slope12 = (e1y - s1y) / (e1x - s1x) - * y = slope12 * (x - s1x) + s1y - */ - __Pyx_INCREF(__pyx_v_s2x); - __pyx_v_x = __pyx_v_s2x; - - /* "fontTools/misc/bezierTools.py":1198 - * if math.isclose(s2x, e2x): - * x = s2x - * slope12 = (e1y - s1y) / (e1x - s1x) # <<<<<<<<<<<<<< - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - */ - __pyx_t_7 = PyNumber_Subtract(__pyx_v_e1y, __pyx_v_s1y); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1198, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = PyNumber_Subtract(__pyx_v_e1x, __pyx_v_s1x); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1198, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_7, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1198, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_slope12 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1199 - * x = s2x - * slope12 = (e1y - s1y) / (e1x - s1x) - * y = slope12 * (x - s1x) + s1y # <<<<<<<<<<<<<< - * pt = (x, y) - * return [ - */ - __pyx_t_3 = PyNumber_Subtract(__pyx_v_x, __pyx_v_s1x); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Multiply(__pyx_v_slope12, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_v_s1y); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_y = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1200 - * slope12 = (e1y - s1y) / (e1x - s1x) - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) # <<<<<<<<<<<<<< - * return [ - * Intersection( - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1200, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x); - __Pyx_INCREF(__pyx_v_y); - __Pyx_GIVEREF(__pyx_v_y); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_y); - __pyx_v_pt = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1201 - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - * return [ # <<<<<<<<<<<<<< - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - */ - __Pyx_XDECREF(__pyx_r); - - /* "fontTools/misc/bezierTools.py":1202 - * pt = (x, y) - * return [ - * Intersection( # <<<<<<<<<<<<<< - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Intersection); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1202, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "fontTools/misc/bezierTools.py":1203 - * return [ - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) # <<<<<<<<<<<<<< - * ) - * ] - */ - __pyx_t_2 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_pt, __pyx_v_pt) < 0) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_v_s1, __pyx_v_e1, __pyx_v_pt}; - __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_v_s1, __pyx_v_e1, __pyx_v_pt}; - __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_v_s1); - __Pyx_GIVEREF(__pyx_v_s1); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_6, __pyx_v_s1); - __Pyx_INCREF(__pyx_v_e1); - __Pyx_GIVEREF(__pyx_v_e1); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_6, __pyx_v_e1); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_6, __pyx_v_pt); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_t1, __pyx_t_7) < 0) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_11 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_v_s2, __pyx_v_e2, __pyx_v_pt}; - __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_v_s2, __pyx_v_e2, __pyx_v_pt}; - __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - { - __pyx_t_10 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_11) { - __Pyx_GIVEREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_11); __pyx_t_11 = NULL; - } - __Pyx_INCREF(__pyx_v_s2); - __Pyx_GIVEREF(__pyx_v_s2); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_6, __pyx_v_s2); - __Pyx_INCREF(__pyx_v_e2); - __Pyx_GIVEREF(__pyx_v_e2); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_6, __pyx_v_e2); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_6, __pyx_v_pt); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_10, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_t2, __pyx_t_7) < 0) __PYX_ERR(0, 1203, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1202 - * pt = (x, y) - * return [ - * Intersection( # <<<<<<<<<<<<<< - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - * ) - */ - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, __pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1202, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1201 - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - * return [ # <<<<<<<<<<<<<< - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1201, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_7); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_7); - __pyx_t_7 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1196 - * ) - * ] - * if math.isclose(s2x, e2x): # <<<<<<<<<<<<<< - * x = s2x - * slope12 = (e1y - s1y) / (e1x - s1x) - */ - } - - /* "fontTools/misc/bezierTools.py":1207 - * ] - * - * slope12 = (e1y - s1y) / (e1x - s1x) # <<<<<<<<<<<<<< - * slope34 = (e2y - s2y) / (e2x - s2x) - * if math.isclose(slope12, slope34): - */ - __pyx_t_2 = PyNumber_Subtract(__pyx_v_e1y, __pyx_v_s1y); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1207, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PyNumber_Subtract(__pyx_v_e1x, __pyx_v_s1x); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1207, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1207, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_slope12 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1208 - * - * slope12 = (e1y - s1y) / (e1x - s1x) - * slope34 = (e2y - s2y) / (e2x - s2x) # <<<<<<<<<<<<<< - * if math.isclose(slope12, slope34): - * return [] - */ - __pyx_t_3 = PyNumber_Subtract(__pyx_v_e2y, __pyx_v_s2y); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1208, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyNumber_Subtract(__pyx_v_e2x, __pyx_v_s2x); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1208, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1208, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_slope34 = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1209 - * slope12 = (e1y - s1y) / (e1x - s1x) - * slope34 = (e2y - s2y) / (e2x - s2x) - * if math.isclose(slope12, slope34): # <<<<<<<<<<<<<< - * return [] - * x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_math); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_isclose); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_slope12, __pyx_v_slope34}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_slope12, __pyx_v_slope34}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - { - __pyx_t_1 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_slope12); - __Pyx_GIVEREF(__pyx_v_slope12); - PyTuple_SET_ITEM(__pyx_t_1, 0+__pyx_t_6, __pyx_v_slope12); - __Pyx_INCREF(__pyx_v_slope34); - __Pyx_GIVEREF(__pyx_v_slope34); - PyTuple_SET_ITEM(__pyx_t_1, 1+__pyx_t_6, __pyx_v_slope34); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1209, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1210 - * slope34 = (e2y - s2y) / (e2x - s2x) - * if math.isclose(slope12, slope34): - * return [] # <<<<<<<<<<<<<< - * x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34) - * y = slope12 * (x - s1x) + s1y - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1210, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1209 - * slope12 = (e1y - s1y) / (e1x - s1x) - * slope34 = (e2y - s2y) / (e2x - s2x) - * if math.isclose(slope12, slope34): # <<<<<<<<<<<<<< - * return [] - * x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34) - */ - } - - /* "fontTools/misc/bezierTools.py":1211 - * if math.isclose(slope12, slope34): - * return [] - * x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34) # <<<<<<<<<<<<<< - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - */ - __pyx_t_2 = PyNumber_Multiply(__pyx_v_slope12, __pyx_v_s1x); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Subtract(__pyx_t_2, __pyx_v_s1y); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_v_slope34, __pyx_v_s2x); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Subtract(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_v_s2y); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_v_slope12, __pyx_v_slope34); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1211, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_x = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1212 - * return [] - * x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34) - * y = slope12 * (x - s1x) + s1y # <<<<<<<<<<<<<< - * pt = (x, y) - * if _both_points_are_on_same_side_of_origin( - */ - __pyx_t_3 = PyNumber_Subtract(__pyx_v_x, __pyx_v_s1x); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1212, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyNumber_Multiply(__pyx_v_slope12, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1212, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_1, __pyx_v_s1y); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1212, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_y = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1213 - * x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34) - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) # <<<<<<<<<<<<<< - * if _both_points_are_on_same_side_of_origin( - * pt, e1, s1 - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1213, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_x); - __Pyx_INCREF(__pyx_v_y); - __Pyx_GIVEREF(__pyx_v_y); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_y); - __pyx_v_pt = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1214 - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - * if _both_points_are_on_same_side_of_origin( # <<<<<<<<<<<<<< - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_both_points_are_on_same_side_of); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1214, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - - /* "fontTools/misc/bezierTools.py":1215 - * pt = (x, y) - * if _both_points_are_on_same_side_of_origin( - * pt, e1, s1 # <<<<<<<<<<<<<< - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - * return [ - */ - __pyx_t_2 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_2, __pyx_v_pt, __pyx_v_e1, __pyx_v_s1}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1214, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_2, __pyx_v_pt, __pyx_v_e1, __pyx_v_s1}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1214, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_7 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1214, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_pt); - __Pyx_INCREF(__pyx_v_e1); - __Pyx_GIVEREF(__pyx_v_e1); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_e1); - __Pyx_INCREF(__pyx_v_s1); - __Pyx_GIVEREF(__pyx_v_s1); - PyTuple_SET_ITEM(__pyx_t_7, 2+__pyx_t_6, __pyx_v_s1); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1214, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1214 - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - * if _both_points_are_on_same_side_of_origin( # <<<<<<<<<<<<<< - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - */ - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1214, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_8) { - } else { - __pyx_t_5 = __pyx_t_8; - goto __pyx_L29_bool_binop_done; - } - - /* "fontTools/misc/bezierTools.py":1216 - * if _both_points_are_on_same_side_of_origin( - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): # <<<<<<<<<<<<<< - * return [ - * Intersection( - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_both_points_are_on_same_side_of); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1216, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_7, __pyx_v_pt, __pyx_v_s2, __pyx_v_e2}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1216, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) { - PyObject *__pyx_temp[4] = {__pyx_t_7, __pyx_v_pt, __pyx_v_s2, __pyx_v_e2}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1216, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_2 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1216, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_6, __pyx_v_pt); - __Pyx_INCREF(__pyx_v_s2); - __Pyx_GIVEREF(__pyx_v_s2); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_6, __pyx_v_s2); - __Pyx_INCREF(__pyx_v_e2); - __Pyx_GIVEREF(__pyx_v_e2); - PyTuple_SET_ITEM(__pyx_t_2, 2+__pyx_t_6, __pyx_v_e2); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1216, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 1216, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __pyx_t_8; - __pyx_L29_bool_binop_done:; - - /* "fontTools/misc/bezierTools.py":1214 - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - * if _both_points_are_on_same_side_of_origin( # <<<<<<<<<<<<<< - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - */ - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1217 - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - * return [ # <<<<<<<<<<<<<< - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - */ - __Pyx_XDECREF(__pyx_r); - - /* "fontTools/misc/bezierTools.py":1218 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - * return [ - * Intersection( # <<<<<<<<<<<<<< - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_Intersection); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1218, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "fontTools/misc/bezierTools.py":1219 - * return [ - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) # <<<<<<<<<<<<<< - * ) - * ] - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_pt, __pyx_v_pt) < 0) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_10 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_v_s1, __pyx_v_e1, __pyx_v_pt}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_v_s1, __pyx_v_e1, __pyx_v_pt}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_v_s1); - __Pyx_GIVEREF(__pyx_v_s1); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_6, __pyx_v_s1); - __Pyx_INCREF(__pyx_v_e1); - __Pyx_GIVEREF(__pyx_v_e1); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_6, __pyx_v_e1); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_6, __pyx_v_pt); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_11, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_t1, __pyx_t_2) < 0) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_11 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_v_s2, __pyx_v_e2, __pyx_v_pt}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_v_s2, __pyx_v_e2, __pyx_v_pt}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 3+__pyx_t_6); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - { - __pyx_t_10 = PyTuple_New(3+__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_11) { - __Pyx_GIVEREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_11); __pyx_t_11 = NULL; - } - __Pyx_INCREF(__pyx_v_s2); - __Pyx_GIVEREF(__pyx_v_s2); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_6, __pyx_v_s2); - __Pyx_INCREF(__pyx_v_e2); - __Pyx_GIVEREF(__pyx_v_e2); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_6, __pyx_v_e2); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_6, __pyx_v_pt); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_t2, __pyx_t_2) < 0) __PYX_ERR(0, 1219, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1218 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - * return [ - * Intersection( # <<<<<<<<<<<<<< - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - * ) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1218, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1217 - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - * return [ # <<<<<<<<<<<<<< - * Intersection( - * pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt) - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1217, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1214 - * y = slope12 * (x - s1x) + s1y - * pt = (x, y) - * if _both_points_are_on_same_side_of_origin( # <<<<<<<<<<<<<< - * pt, e1, s1 - * ) and _both_points_are_on_same_side_of_origin(pt, s2, e2): - */ - } - - /* "fontTools/misc/bezierTools.py":1222 - * ) - * ] - * return [] # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1222, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1147 - * - * - * def lineLineIntersections(s1, e1, s2, e2): # <<<<<<<<<<<<<< - * """Finds intersections between two line segments. - * - */ - - /* 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_7); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("fontTools.misc.bezierTools.lineLineIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_s1x); - __Pyx_XDECREF(__pyx_v_s1y); - __Pyx_XDECREF(__pyx_v_e1x); - __Pyx_XDECREF(__pyx_v_e1y); - __Pyx_XDECREF(__pyx_v_s2x); - __Pyx_XDECREF(__pyx_v_s2y); - __Pyx_XDECREF(__pyx_v_e2x); - __Pyx_XDECREF(__pyx_v_e2y); - __Pyx_XDECREF(__pyx_v_x); - __Pyx_XDECREF(__pyx_v_slope34); - __Pyx_XDECREF(__pyx_v_y); - __Pyx_XDECREF(__pyx_v_pt); - __Pyx_XDECREF(__pyx_v_slope12); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1225 - * - * - * def _alignment_transformation(segment): # <<<<<<<<<<<<<< - * # Returns a transformation which aligns a segment horizontally at the - * # origin. Apply this transformation to curves and root-find to find - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_75_alignment_transformation(PyObject *__pyx_self, PyObject *__pyx_v_segment); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_74_alignment_transformation[] = "_alignment_transformation(segment)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_75_alignment_transformation = {"_alignment_transformation", (PyCFunction)__pyx_pw_9fontTools_4misc_11bezierTools_75_alignment_transformation, METH_O, __pyx_doc_9fontTools_4misc_11bezierTools_74_alignment_transformation}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_75_alignment_transformation(PyObject *__pyx_self, PyObject *__pyx_v_segment) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_alignment_transformation (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_74_alignment_transformation(__pyx_self, ((PyObject *)__pyx_v_segment)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_74_alignment_transformation(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_segment) { - PyObject *__pyx_v_start = NULL; - PyObject *__pyx_v_end = NULL; - PyObject *__pyx_v_angle = 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; - int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_alignment_transformation", 0); - - /* "fontTools/misc/bezierTools.py":1229 - * # origin. Apply this transformation to curves and root-find to find - * # intersections with the segment. - * start = segment[0] # <<<<<<<<<<<<<< - * end = segment[-1] - * angle = math.atan2(end[1] - start[1], end[0] - start[0]) - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_segment, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_start = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1230 - * # intersections with the segment. - * start = segment[0] - * end = segment[-1] # <<<<<<<<<<<<<< - * angle = math.atan2(end[1] - start[1], end[0] - start[0]) - * return Identity.rotate(-angle).translate(-start[0], -start[1]) - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_segment, -1L, long, 1, __Pyx_PyInt_From_long, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1230, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_end = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1231 - * start = segment[0] - * end = segment[-1] - * angle = math.atan2(end[1] - start[1], end[0] - start[0]) # <<<<<<<<<<<<<< - * return Identity.rotate(-angle).translate(-start[0], -start[1]) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_math); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_atan2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_end, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_start, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyNumber_Subtract(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_end, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_start, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyNumber_Subtract(__pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - __pyx_t_7 = 0; - 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_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_t_5, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_t_5, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_4 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_7, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_7, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1231, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_angle = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1232 - * end = segment[-1] - * angle = math.atan2(end[1] - start[1], end[0] - start[0]) - * return Identity.rotate(-angle).translate(-start[0], -start[1]) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_Identity); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_rotate); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Negative(__pyx_v_angle); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(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_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_6, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_6, __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(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_translate); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_start, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Negative(__pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_start, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Negative(__pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_3); - __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_3, __pyx_t_4, __pyx_t_5}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_4, __pyx_t_5}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - { - __pyx_t_2 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_7, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_7, __pyx_t_5); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1232, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1225 - * - * - * def _alignment_transformation(segment): # <<<<<<<<<<<<<< - * # Returns a transformation which aligns a segment horizontally at the - * # origin. Apply this transformation to curves and root-find to find - */ - - /* 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_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("fontTools.misc.bezierTools._alignment_transformation", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_start); - __Pyx_XDECREF(__pyx_v_end); - __Pyx_XDECREF(__pyx_v_angle); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1235 - * - * - * def _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_77_curve_line_intersections_t(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_76_curve_line_intersections_t[] = "_curve_line_intersections_t(curve, line)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_77_curve_line_intersections_t = {"_curve_line_intersections_t", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_77_curve_line_intersections_t, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_76_curve_line_intersections_t}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_77_curve_line_intersections_t(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_curve = 0; - PyObject *__pyx_v_line = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_curve_line_intersections_t (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_curve,&__pyx_n_s_line,0}; - PyObject* values[2] = {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 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_curve)) != 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_line)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_curve_line_intersections_t", 1, 2, 2, 1); __PYX_ERR(0, 1235, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_curve_line_intersections_t") < 0)) __PYX_ERR(0, 1235, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_curve = values[0]; - __pyx_v_line = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_curve_line_intersections_t", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1235, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_line_intersections_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_76_curve_line_intersections_t(__pyx_self, __pyx_v_curve, __pyx_v_line); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_2generator4(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "fontTools/misc/bezierTools.py":1245 - * else: - * raise ValueError("Unknown curve degree") - * return sorted(i for i in intersections if 0.0 <= i <= 1) # <<<<<<<<<<<<<< - * - * - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_genexpr(PyObject *__pyx_self) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("genexpr", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 1245, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *) __pyx_self; - __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_2generator4, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_curve_line_intersections_t_loca, __pyx_n_s_fontTools_misc_bezierTools); if (unlikely(!gen)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_line_intersections_t.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_2generator4(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *(*__pyx_t_3)(PyObject *); - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("genexpr", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 1245, __pyx_L1_error) - __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_r); - if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_intersections)) { __Pyx_RaiseClosureNameError("intersections"); __PYX_ERR(0, 1245, __pyx_L1_error) } - if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_intersections)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_intersections)) { - __pyx_t_1 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_intersections; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - __pyx_t_3 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_intersections); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1245, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_3)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1245, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1245, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_3(__pyx_t_1); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 1245, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_i); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_i, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_RichCompare(__pyx_float_0_0, __pyx_cur_scope->__pyx_v_i, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1245, __pyx_L1_error) - if (__Pyx_PyObject_IsTrue(__pyx_t_4)) { - __Pyx_DECREF(__pyx_t_4); - __pyx_t_4 = PyObject_RichCompare(__pyx_cur_scope->__pyx_v_i, __pyx_int_1, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1245, __pyx_L1_error) - } - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { - if (unlikely(__Pyx_ListComp_Append(__pyx_r, (PyObject*)__pyx_cur_scope->__pyx_v_i))) __PYX_ERR(0, 1245, __pyx_L1_error) - } - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1235 - * - * - * def _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_76_curve_line_intersections_t(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve, PyObject *__pyx_v_line) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *__pyx_cur_scope; - PyObject *__pyx_v_aligned_curve = NULL; - PyObject *__pyx_v_a = NULL; - PyObject *__pyx_v_b = NULL; - PyObject *__pyx_v_c = NULL; - PyObject *__pyx_v_d = NULL; - PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_2generator4 = 0; - 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; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - int __pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_curve_line_intersections_t", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 1235, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - - /* "fontTools/misc/bezierTools.py":1236 - * - * def _curve_line_intersections_t(curve, line): - * aligned_curve = _alignment_transformation(line).transformPoints(curve) # <<<<<<<<<<<<<< - * if len(curve) == 3: - * a, b, c = calcQuadraticParameters(*aligned_curve) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_alignment_transformation); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1236, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_2 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_v_line) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_line); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1236, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_transformPoints); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1236, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_v_curve) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_curve); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1236, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_aligned_curve = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1237 - * def _curve_line_intersections_t(curve, line): - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: # <<<<<<<<<<<<<< - * a, b, c = calcQuadraticParameters(*aligned_curve) - * intersections = solveQuadratic(a[1], b[1], c[1]) - */ - __pyx_t_5 = PyObject_Length(__pyx_v_curve); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1237, __pyx_L1_error) - __pyx_t_6 = ((__pyx_t_5 == 3) != 0); - if (__pyx_t_6) { - - /* "fontTools/misc/bezierTools.py":1238 - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - * a, b, c = calcQuadraticParameters(*aligned_curve) # <<<<<<<<<<<<<< - * intersections = solveQuadratic(a[1], b[1], c[1]) - * elif len(curve) == 4: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_calcQuadraticParameters); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_aligned_curve); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 1238, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - __pyx_t_4 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_3)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_1 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_1)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 2; __pyx_t_4 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 3) < 0) __PYX_ERR(0, 1238, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L5_unpacking_done; - __pyx_L4_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1238, __pyx_L1_error) - __pyx_L5_unpacking_done:; - } - __pyx_v_a = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_b = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_c = __pyx_t_4; - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1239 - * if len(curve) == 3: - * a, b, c = calcQuadraticParameters(*aligned_curve) - * intersections = solveQuadratic(a[1], b[1], c[1]) # <<<<<<<<<<<<<< - * elif len(curve) == 4: - * a, b, c, d = calcCubicParameters(*aligned_curve) - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_solveQuadratic); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_a, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_b, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_c, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = NULL; - __pyx_t_10 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_10 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_t_1, __pyx_t_3, __pyx_t_7}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_10, 3+__pyx_t_10); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_t_1, __pyx_t_3, __pyx_t_7}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_10, 3+__pyx_t_10); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (__pyx_t_9) { - __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_9); __pyx_t_9 = NULL; - } - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_10, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_10, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_10, __pyx_t_7); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_t_7 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_11, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GIVEREF(__pyx_t_2); - __pyx_cur_scope->__pyx_v_intersections = __pyx_t_2; - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1237 - * def _curve_line_intersections_t(curve, line): - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: # <<<<<<<<<<<<<< - * a, b, c = calcQuadraticParameters(*aligned_curve) - * intersections = solveQuadratic(a[1], b[1], c[1]) - */ - goto __pyx_L3; - } - - /* "fontTools/misc/bezierTools.py":1240 - * a, b, c = calcQuadraticParameters(*aligned_curve) - * intersections = solveQuadratic(a[1], b[1], c[1]) - * elif len(curve) == 4: # <<<<<<<<<<<<<< - * a, b, c, d = calcCubicParameters(*aligned_curve) - * intersections = solveCubic(a[1], b[1], c[1], d[1]) - */ - __pyx_t_5 = PyObject_Length(__pyx_v_curve); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1240, __pyx_L1_error) - __pyx_t_6 = ((__pyx_t_5 == 4) != 0); - if (likely(__pyx_t_6)) { - - /* "fontTools/misc/bezierTools.py":1241 - * intersections = solveQuadratic(a[1], b[1], c[1]) - * elif len(curve) == 4: - * a, b, c, d = calcCubicParameters(*aligned_curve) # <<<<<<<<<<<<<< - * intersections = solveCubic(a[1], b[1], c[1], d[1]) - * else: - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_calcCubicParameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_aligned_curve); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_11))) || (PyList_CheckExact(__pyx_t_11))) { - PyObject* sequence = __pyx_t_11; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 4)) { - if (size > 4) __Pyx_RaiseTooManyValuesError(4); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 1241, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_7 = PyTuple_GET_ITEM(sequence, 2); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 3); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - __pyx_t_7 = PyList_GET_ITEM(sequence, 2); - __pyx_t_3 = PyList_GET_ITEM(sequence, 3); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - #else - { - Py_ssize_t i; - PyObject** temps[4] = {&__pyx_t_4,&__pyx_t_2,&__pyx_t_7,&__pyx_t_3}; - for (i=0; i < 4; i++) { - PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 1241, __pyx_L1_error) - __Pyx_GOTREF(item); - *(temps[i]) = item; - } - } - #endif - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else { - Py_ssize_t index = -1; - PyObject** temps[4] = {&__pyx_t_4,&__pyx_t_2,&__pyx_t_7,&__pyx_t_3}; - __pyx_t_1 = PyObject_GetIter(__pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_1)->tp_iternext; - for (index=0; index < 4; index++) { - PyObject* item = __pyx_t_8(__pyx_t_1); if (unlikely(!item)) goto __pyx_L6_unpacking_failed; - __Pyx_GOTREF(item); - *(temps[index]) = item; - } - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_1), 4) < 0) __PYX_ERR(0, 1241, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L7_unpacking_done; - __pyx_L6_unpacking_failed:; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1241, __pyx_L1_error) - __pyx_L7_unpacking_done:; - } - __pyx_v_a = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_v_b = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_c = __pyx_t_7; - __pyx_t_7 = 0; - __pyx_v_d = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1242 - * elif len(curve) == 4: - * a, b, c, d = calcCubicParameters(*aligned_curve) - * intersections = solveCubic(a[1], b[1], c[1], d[1]) # <<<<<<<<<<<<<< - * else: - * raise ValueError("Unknown curve degree") - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_solveCubic); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_a, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_b, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_c, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_d, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_9 = NULL; - __pyx_t_10 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_10 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[5] = {__pyx_t_9, __pyx_t_7, __pyx_t_2, __pyx_t_4, __pyx_t_1}; - __pyx_t_11 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_10, 4+__pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[5] = {__pyx_t_9, __pyx_t_7, __pyx_t_2, __pyx_t_4, __pyx_t_1}; - __pyx_t_11 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_10, 4+__pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_12 = PyTuple_New(4+__pyx_t_10); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_12); - if (__pyx_t_9) { - __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_9); __pyx_t_9 = NULL; - } - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_12, 0+__pyx_t_10, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_12, 1+__pyx_t_10, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_12, 2+__pyx_t_10, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_12, 3+__pyx_t_10, __pyx_t_1); - __pyx_t_7 = 0; - __pyx_t_2 = 0; - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_12, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GIVEREF(__pyx_t_11); - __pyx_cur_scope->__pyx_v_intersections = __pyx_t_11; - __pyx_t_11 = 0; - - /* "fontTools/misc/bezierTools.py":1240 - * a, b, c = calcQuadraticParameters(*aligned_curve) - * intersections = solveQuadratic(a[1], b[1], c[1]) - * elif len(curve) == 4: # <<<<<<<<<<<<<< - * a, b, c, d = calcCubicParameters(*aligned_curve) - * intersections = solveCubic(a[1], b[1], c[1], d[1]) - */ - goto __pyx_L3; - } - - /* "fontTools/misc/bezierTools.py":1244 - * intersections = solveCubic(a[1], b[1], c[1], d[1]) - * else: - * raise ValueError("Unknown curve degree") # <<<<<<<<<<<<<< - * return sorted(i for i in intersections if 0.0 <= i <= 1) - * - */ - /*else*/ { - __pyx_t_11 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_Raise(__pyx_t_11, 0, 0, 0); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __PYX_ERR(0, 1244, __pyx_L1_error) - } - __pyx_L3:; - - /* "fontTools/misc/bezierTools.py":1245 - * else: - * raise ValueError("Unknown curve degree") - * return sorted(i for i in intersections if 0.0 <= i <= 1) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_pf_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_12 = __Pyx_Generator_Next(__pyx_t_3); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_11 = ((PyObject*)__pyx_t_12); - __pyx_t_12 = 0; - __pyx_t_13 = PyList_Sort(__pyx_t_11); if (unlikely(__pyx_t_13 == ((int)-1))) __PYX_ERR(0, 1245, __pyx_L1_error) - __pyx_r = __pyx_t_11; - __pyx_t_11 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1235 - * - * - * def _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - */ - - /* 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_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_line_intersections_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_aligned_curve); - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_b); - __Pyx_XDECREF(__pyx_v_c); - __Pyx_XDECREF(__pyx_v_d); - __Pyx_XDECREF(__pyx_gb_9fontTools_4misc_11bezierTools_27_curve_line_intersections_t_2generator4); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1248 - * - * - * def curveLineIntersections(curve, line): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a line. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_79curveLineIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_78curveLineIntersections[] = "curveLineIntersections(curve, line)\nFinds intersections between a curve and a line.\n\n Args:\n curve: List of coordinates of the curve segment as 2D tuples.\n line: List of coordinates of the line segment as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n >>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ]\n >>> line = [ (25, 260), (230, 20) ]\n >>> intersections = curveLineIntersections(curve, line)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (84.9000930760723, 189.87306176459828)\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_79curveLineIntersections = {"curveLineIntersections", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_79curveLineIntersections, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_78curveLineIntersections}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_79curveLineIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_curve = 0; - PyObject *__pyx_v_line = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("curveLineIntersections (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_curve,&__pyx_n_s_line,0}; - PyObject* values[2] = {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 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_curve)) != 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_line)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("curveLineIntersections", 1, 2, 2, 1); __PYX_ERR(0, 1248, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "curveLineIntersections") < 0)) __PYX_ERR(0, 1248, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_curve = values[0]; - __pyx_v_line = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("curveLineIntersections", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1248, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.curveLineIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_78curveLineIntersections(__pyx_self, __pyx_v_curve, __pyx_v_line); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_78curveLineIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve, PyObject *__pyx_v_line) { - PyObject *__pyx_v_pointFinder = NULL; - PyObject *__pyx_v_intersections = NULL; - PyObject *__pyx_v_t = NULL; - PyObject *__pyx_v_pt = NULL; - PyObject *__pyx_v_line_t = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("curveLineIntersections", 0); - - /* "fontTools/misc/bezierTools.py":1269 - * (84.9000930760723, 189.87306176459828) - * """ - * if len(curve) == 3: # <<<<<<<<<<<<<< - * pointFinder = quadraticPointAtT - * elif len(curve) == 4: - */ - __pyx_t_1 = PyObject_Length(__pyx_v_curve); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1269, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 3) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1270 - * """ - * if len(curve) == 3: - * pointFinder = quadraticPointAtT # <<<<<<<<<<<<<< - * elif len(curve) == 4: - * pointFinder = cubicPointAtT - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_quadraticPointAtT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1270, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_pointFinder = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1269 - * (84.9000930760723, 189.87306176459828) - * """ - * if len(curve) == 3: # <<<<<<<<<<<<<< - * pointFinder = quadraticPointAtT - * elif len(curve) == 4: - */ - goto __pyx_L3; - } - - /* "fontTools/misc/bezierTools.py":1271 - * if len(curve) == 3: - * pointFinder = quadraticPointAtT - * elif len(curve) == 4: # <<<<<<<<<<<<<< - * pointFinder = cubicPointAtT - * else: - */ - __pyx_t_1 = PyObject_Length(__pyx_v_curve); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1271, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 4) != 0); - if (likely(__pyx_t_2)) { - - /* "fontTools/misc/bezierTools.py":1272 - * pointFinder = quadraticPointAtT - * elif len(curve) == 4: - * pointFinder = cubicPointAtT # <<<<<<<<<<<<<< - * else: - * raise ValueError("Unknown curve degree") - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_cubicPointAtT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1272, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_pointFinder = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1271 - * if len(curve) == 3: - * pointFinder = quadraticPointAtT - * elif len(curve) == 4: # <<<<<<<<<<<<<< - * pointFinder = cubicPointAtT - * else: - */ - goto __pyx_L3; - } - - /* "fontTools/misc/bezierTools.py":1274 - * pointFinder = cubicPointAtT - * else: - * raise ValueError("Unknown curve degree") # <<<<<<<<<<<<<< - * intersections = [] - * for t in _curve_line_intersections_t(curve, line): - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1274, __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(0, 1274, __pyx_L1_error) - } - __pyx_L3:; - - /* "fontTools/misc/bezierTools.py":1275 - * else: - * raise ValueError("Unknown curve degree") - * intersections = [] # <<<<<<<<<<<<<< - * for t in _curve_line_intersections_t(curve, line): - * pt = pointFinder(*curve, t) - */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1275, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_intersections = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1276 - * raise ValueError("Unknown curve degree") - * intersections = [] - * for t in _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * pt = pointFinder(*curve, t) - * # Back-project the point onto the line, to avoid problems with - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_curve_line_intersections_t); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - __pyx_t_6 = 0; - 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_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_v_curve, __pyx_v_line}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_v_curve, __pyx_v_line}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_INCREF(__pyx_v_curve); - __Pyx_GIVEREF(__pyx_v_curve); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_curve); - __Pyx_INCREF(__pyx_v_line); - __Pyx_GIVEREF(__pyx_v_line); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_line); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) { - __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_1 = 0; - __pyx_t_8 = NULL; - } else { - __pyx_t_1 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1276, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - for (;;) { - if (likely(!__pyx_t_8)) { - if (likely(PyList_CheckExact(__pyx_t_4))) { - if (__pyx_t_1 >= PyList_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(0, 1276, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - } else { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(0, 1276, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - } - } else { - __pyx_t_3 = __pyx_t_8(__pyx_t_4); - if (unlikely(!__pyx_t_3)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 1276, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_3); - } - __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1277 - * intersections = [] - * for t in _curve_line_intersections_t(curve, line): - * pt = pointFinder(*curve, t) # <<<<<<<<<<<<<< - * # Back-project the point onto the line, to avoid problems with - * # numerical accuracy in the case of vertical and horizontal lines - */ - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_curve); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1277, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1277, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_t); - __pyx_t_5 = PyNumber_Add(__pyx_t_3, __pyx_t_7); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1277, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_v_pointFinder, __pyx_t_5, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1277, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF_SET(__pyx_v_pt, __pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1280 - * # Back-project the point onto the line, to avoid problems with - * # numerical accuracy in the case of vertical and horizontal lines - * line_t = _line_t_of_pt(*line, pt) # <<<<<<<<<<<<<< - * pt = linePointAtT(*line, line_t) - * intersections.append(Intersection(pt=pt, t1=t, t2=line_t)) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_line_t_of_pt); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1280, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = __Pyx_PySequence_Tuple(__pyx_v_line); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1280, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1280, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_pt); - __Pyx_GIVEREF(__pyx_v_pt); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_pt); - __pyx_t_9 = PyNumber_Add(__pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1280, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1280, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF_SET(__pyx_v_line_t, __pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1281 - * # numerical accuracy in the case of vertical and horizontal lines - * line_t = _line_t_of_pt(*line, pt) - * pt = linePointAtT(*line, line_t) # <<<<<<<<<<<<<< - * intersections.append(Intersection(pt=pt, t1=t, t2=line_t)) - * return intersections - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_linePointAtT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = __Pyx_PySequence_Tuple(__pyx_v_line); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_v_line_t); - __Pyx_GIVEREF(__pyx_v_line_t); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_line_t); - __pyx_t_5 = PyNumber_Add(__pyx_t_9, __pyx_t_7); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1281, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_pt, __pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1282 - * line_t = _line_t_of_pt(*line, pt) - * pt = linePointAtT(*line, line_t) - * intersections.append(Intersection(pt=pt, t1=t, t2=line_t)) # <<<<<<<<<<<<<< - * return intersections - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_Intersection); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1282, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1282, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_pt, __pyx_v_pt) < 0) __PYX_ERR(0, 1282, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_t1, __pyx_v_t) < 0) __PYX_ERR(0, 1282, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_t2, __pyx_v_line_t) < 0) __PYX_ERR(0, 1282, __pyx_L1_error) - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_empty_tuple, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1282, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_intersections, __pyx_t_3); if (unlikely(__pyx_t_10 == ((int)-1))) __PYX_ERR(0, 1282, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1276 - * raise ValueError("Unknown curve degree") - * intersections = [] - * for t in _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * pt = pointFinder(*curve, t) - * # Back-project the point onto the line, to avoid problems with - */ - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1283 - * pt = linePointAtT(*line, line_t) - * intersections.append(Intersection(pt=pt, t1=t, t2=line_t)) - * return intersections # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_intersections); - __pyx_r = __pyx_v_intersections; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1248 - * - * - * def curveLineIntersections(curve, line): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a line. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("fontTools.misc.bezierTools.curveLineIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_pointFinder); - __Pyx_XDECREF(__pyx_v_intersections); - __Pyx_XDECREF(__pyx_v_t); - __Pyx_XDECREF(__pyx_v_pt); - __Pyx_XDECREF(__pyx_v_line_t); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1286 - * - * - * def _curve_bounds(c): # <<<<<<<<<<<<<< - * if len(c) == 3: - * return calcQuadraticBounds(*c) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_81_curve_bounds(PyObject *__pyx_self, PyObject *__pyx_v_c); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_80_curve_bounds[] = "_curve_bounds(c)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_81_curve_bounds = {"_curve_bounds", (PyCFunction)__pyx_pw_9fontTools_4misc_11bezierTools_81_curve_bounds, METH_O, __pyx_doc_9fontTools_4misc_11bezierTools_80_curve_bounds}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_81_curve_bounds(PyObject *__pyx_self, PyObject *__pyx_v_c) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_curve_bounds (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_80_curve_bounds(__pyx_self, ((PyObject *)__pyx_v_c)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_80_curve_bounds(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - 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("_curve_bounds", 0); - - /* "fontTools/misc/bezierTools.py":1287 - * - * def _curve_bounds(c): - * if len(c) == 3: # <<<<<<<<<<<<<< - * return calcQuadraticBounds(*c) - * elif len(c) == 4: - */ - __pyx_t_1 = PyObject_Length(__pyx_v_c); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1287, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 3) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1288 - * def _curve_bounds(c): - * if len(c) == 3: - * return calcQuadraticBounds(*c) # <<<<<<<<<<<<<< - * elif len(c) == 4: - * return calcCubicBounds(*c) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_calcQuadraticBounds); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_c); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1287 - * - * def _curve_bounds(c): - * if len(c) == 3: # <<<<<<<<<<<<<< - * return calcQuadraticBounds(*c) - * elif len(c) == 4: - */ - } - - /* "fontTools/misc/bezierTools.py":1289 - * if len(c) == 3: - * return calcQuadraticBounds(*c) - * elif len(c) == 4: # <<<<<<<<<<<<<< - * return calcCubicBounds(*c) - * raise ValueError("Unknown curve degree") - */ - __pyx_t_1 = PyObject_Length(__pyx_v_c); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1289, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 4) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1290 - * return calcQuadraticBounds(*c) - * elif len(c) == 4: - * return calcCubicBounds(*c) # <<<<<<<<<<<<<< - * raise ValueError("Unknown curve degree") - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_calcCubicBounds); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1290, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_c); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1290, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1290, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1289 - * if len(c) == 3: - * return calcQuadraticBounds(*c) - * elif len(c) == 4: # <<<<<<<<<<<<<< - * return calcCubicBounds(*c) - * raise ValueError("Unknown curve degree") - */ - } - - /* "fontTools/misc/bezierTools.py":1291 - * elif len(c) == 4: - * return calcCubicBounds(*c) - * raise ValueError("Unknown curve degree") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1291, __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(0, 1291, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1286 - * - * - * def _curve_bounds(c): # <<<<<<<<<<<<<< - * if len(c) == 3: - * return calcQuadraticBounds(*c) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_bounds", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1294 - * - * - * def _split_segment_at_t(c, t): # <<<<<<<<<<<<<< - * if len(c) == 2: - * s, e = c - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_83_split_segment_at_t(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_82_split_segment_at_t[] = "_split_segment_at_t(c, t)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_83_split_segment_at_t = {"_split_segment_at_t", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_83_split_segment_at_t, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_82_split_segment_at_t}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_83_split_segment_at_t(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_c = 0; - PyObject *__pyx_v_t = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_split_segment_at_t (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_c,&__pyx_n_s_t,0}; - PyObject* values[2] = {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 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_c)) != 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_t)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_split_segment_at_t", 1, 2, 2, 1); __PYX_ERR(0, 1294, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_split_segment_at_t") < 0)) __PYX_ERR(0, 1294, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_c = values[0]; - __pyx_v_t = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_split_segment_at_t", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1294, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._split_segment_at_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_82_split_segment_at_t(__pyx_self, __pyx_v_c, __pyx_v_t); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_82_split_segment_at_t(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_c, PyObject *__pyx_v_t) { - PyObject *__pyx_v_s = NULL; - PyObject *__pyx_v_e = NULL; - PyObject *__pyx_v_midpoint = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __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)(PyObject *); - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_split_segment_at_t", 0); - - /* "fontTools/misc/bezierTools.py":1295 - * - * def _split_segment_at_t(c, t): - * if len(c) == 2: # <<<<<<<<<<<<<< - * s, e = c - * midpoint = linePointAtT(s, e, t) - */ - __pyx_t_1 = PyObject_Length(__pyx_v_c); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1295, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 2) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1296 - * def _split_segment_at_t(c, t): - * if len(c) == 2: - * s, e = c # <<<<<<<<<<<<<< - * midpoint = linePointAtT(s, e, t) - * return [(s, midpoint), (midpoint, e)] - */ - if ((likely(PyTuple_CheckExact(__pyx_v_c))) || (PyList_CheckExact(__pyx_v_c))) { - PyObject* sequence = __pyx_v_c; - 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(0, 1296, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_4 = PyList_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(0, 1296, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1296, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(__pyx_v_c); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1296, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) __PYX_ERR(0, 1296, __pyx_L1_error) - __pyx_t_6 = NULL; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L5_unpacking_done; - __pyx_L4_unpacking_failed:; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1296, __pyx_L1_error) - __pyx_L5_unpacking_done:; - } - __pyx_v_s = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_e = __pyx_t_4; - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1297 - * if len(c) == 2: - * s, e = c - * midpoint = linePointAtT(s, e, t) # <<<<<<<<<<<<<< - * return [(s, midpoint), (midpoint, e)] - * if len(c) == 3: - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_linePointAtT); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1297, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_5, __pyx_v_s, __pyx_v_e, __pyx_v_t}; - __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1297, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[4] = {__pyx_t_5, __pyx_v_s, __pyx_v_e, __pyx_v_t}; - __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_7, 3+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1297, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - } else - #endif - { - __pyx_t_8 = PyTuple_New(3+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1297, __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_INCREF(__pyx_v_s); - __Pyx_GIVEREF(__pyx_v_s); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_v_s); - __Pyx_INCREF(__pyx_v_e); - __Pyx_GIVEREF(__pyx_v_e); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_e); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_8, 2+__pyx_t_7, __pyx_v_t); - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1297, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_midpoint = __pyx_t_4; - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1298 - * s, e = c - * midpoint = linePointAtT(s, e, t) - * return [(s, midpoint), (midpoint, e)] # <<<<<<<<<<<<<< - * if len(c) == 3: - * return splitQuadraticAtT(*c, t) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1298, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_s); - __Pyx_GIVEREF(__pyx_v_s); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_s); - __Pyx_INCREF(__pyx_v_midpoint); - __Pyx_GIVEREF(__pyx_v_midpoint); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_midpoint); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1298, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_midpoint); - __Pyx_GIVEREF(__pyx_v_midpoint); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_midpoint); - __Pyx_INCREF(__pyx_v_e); - __Pyx_GIVEREF(__pyx_v_e); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_e); - __pyx_t_8 = PyList_New(2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1298, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GIVEREF(__pyx_t_4); - PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyList_SET_ITEM(__pyx_t_8, 1, __pyx_t_3); - __pyx_t_4 = 0; - __pyx_t_3 = 0; - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1295 - * - * def _split_segment_at_t(c, t): - * if len(c) == 2: # <<<<<<<<<<<<<< - * s, e = c - * midpoint = linePointAtT(s, e, t) - */ - } - - /* "fontTools/misc/bezierTools.py":1299 - * midpoint = linePointAtT(s, e, t) - * return [(s, midpoint), (midpoint, e)] - * if len(c) == 3: # <<<<<<<<<<<<<< - * return splitQuadraticAtT(*c, t) - * elif len(c) == 4: - */ - __pyx_t_1 = PyObject_Length(__pyx_v_c); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1299, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 3) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1300 - * return [(s, midpoint), (midpoint, e)] - * if len(c) == 3: - * return splitQuadraticAtT(*c, t) # <<<<<<<<<<<<<< - * elif len(c) == 4: - * return splitCubicAtT(*c, t) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_n_s_splitQuadraticAtT_2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1300, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_3 = __Pyx_PySequence_Tuple(__pyx_v_c); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1300, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1300, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_t); - __pyx_t_5 = PyNumber_Add(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1300, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1300, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1299 - * midpoint = linePointAtT(s, e, t) - * return [(s, midpoint), (midpoint, e)] - * if len(c) == 3: # <<<<<<<<<<<<<< - * return splitQuadraticAtT(*c, t) - * elif len(c) == 4: - */ - } - - /* "fontTools/misc/bezierTools.py":1301 - * if len(c) == 3: - * return splitQuadraticAtT(*c, t) - * elif len(c) == 4: # <<<<<<<<<<<<<< - * return splitCubicAtT(*c, t) - * raise ValueError("Unknown curve degree") - */ - __pyx_t_1 = PyObject_Length(__pyx_v_c); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1301, __pyx_L1_error) - __pyx_t_2 = ((__pyx_t_1 == 4) != 0); - if (__pyx_t_2) { - - /* "fontTools/misc/bezierTools.py":1302 - * return splitQuadraticAtT(*c, t) - * elif len(c) == 4: - * return splitCubicAtT(*c, t) # <<<<<<<<<<<<<< - * raise ValueError("Unknown curve degree") - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_splitCubicAtT_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1302, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PySequence_Tuple(__pyx_v_c); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1302, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1302, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_v_t); - __Pyx_GIVEREF(__pyx_v_t); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_t); - __pyx_t_3 = PyNumber_Add(__pyx_t_5, __pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1302, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1302, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1301 - * if len(c) == 3: - * return splitQuadraticAtT(*c, t) - * elif len(c) == 4: # <<<<<<<<<<<<<< - * return splitCubicAtT(*c, t) - * raise ValueError("Unknown curve degree") - */ - } - - /* "fontTools/misc/bezierTools.py":1303 - * elif len(c) == 4: - * return splitCubicAtT(*c, t) - * raise ValueError("Unknown curve degree") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1303, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(0, 1303, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1294 - * - * - * def _split_segment_at_t(c, t): # <<<<<<<<<<<<<< - * if len(c) == 2: - * s, e = c - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("fontTools.misc.bezierTools._split_segment_at_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_s); - __Pyx_XDECREF(__pyx_v_e); - __Pyx_XDECREF(__pyx_v_midpoint); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_85_curve_curve_intersections_t(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_84_curve_curve_intersections_t[] = "_curve_curve_intersections_t(curve1, curve2, precision=1e-3, range1=None, range2=None)"; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_85_curve_curve_intersections_t = {"_curve_curve_intersections_t", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_85_curve_curve_intersections_t, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_84_curve_curve_intersections_t}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_85_curve_curve_intersections_t(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_curve1 = 0; - PyObject *__pyx_v_curve2 = 0; - PyObject *__pyx_v_precision = 0; - PyObject *__pyx_v_range1 = 0; - PyObject *__pyx_v_range2 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_curve_curve_intersections_t (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_curve1,&__pyx_n_s_curve2,&__pyx_n_s_precision,&__pyx_n_s_range1,&__pyx_n_s_range2,0}; - PyObject* values[5] = {0,0,0,0,0}; - values[2] = ((PyObject *)((PyObject*)__pyx_float_1eneg_3)); - - /* "fontTools/misc/bezierTools.py":1307 - * - * def _curve_curve_intersections_t( - * curve1, curve2, precision=1e-3, range1=None, range2=None # <<<<<<<<<<<<<< - * ): - * bounds1 = _curve_bounds(curve1) - */ - values[3] = ((PyObject *)((PyObject *)Py_None)); - values[4] = ((PyObject *)((PyObject *)Py_None)); - 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_curve1)) != 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_curve2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_curve_curve_intersections_t", 0, 2, 5, 1); __PYX_ERR(0, 1306, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_precision); - if (value) { values[2] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_range1); - 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_range2); - if (value) { values[4] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_curve_curve_intersections_t") < 0)) __PYX_ERR(0, 1306, __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); - 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_curve1 = values[0]; - __pyx_v_curve2 = values[1]; - __pyx_v_precision = values[2]; - __pyx_v_range1 = values[3]; - __pyx_v_range2 = values[4]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_curve_curve_intersections_t", 0, 2, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1306, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_curve_intersections_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_84_curve_curve_intersections_t(__pyx_self, __pyx_v_curve1, __pyx_v_curve2, __pyx_v_precision, __pyx_v_range1, __pyx_v_range2); - - /* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1322 - * return [] - * - * def midpoint(r): # <<<<<<<<<<<<<< - * return 0.5 * (r[0] + r[1]) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_1midpoint(PyObject *__pyx_self, PyObject *__pyx_v_r); /*proto*/ -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_1midpoint = {"midpoint", (PyCFunction)__pyx_pw_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_1midpoint, METH_O, 0}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_1midpoint(PyObject *__pyx_self, PyObject *__pyx_v_r) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("midpoint (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_self, ((PyObject *)__pyx_v_r)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_r) { - 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("midpoint", 0); - - /* "fontTools/misc/bezierTools.py":1323 - * - * def midpoint(r): - * return 0.5 * (r[0] + r[1]) # <<<<<<<<<<<<<< - * - * # If they do overlap but they're tiny, approximate - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_r, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1323, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_r, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1323, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1323, __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_t_2 = PyNumber_Multiply(__pyx_float_0_5, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1323, __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; - - /* "fontTools/misc/bezierTools.py":1322 - * return [] - * - * def midpoint(r): # <<<<<<<<<<<<<< - * return 0.5 * (r[0] + r[1]) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_curve_intersections_t.midpoint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1359 - * ) - * - * unique_key = lambda ts: (int(ts[0] / precision), int(ts[1] / precision)) # <<<<<<<<<<<<<< - * seen = set() - * unique_values = [] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_2lambda3(PyObject *__pyx_self, PyObject *__pyx_v_ts); /*proto*/ -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_2lambda3 = {"lambda3", (PyCFunction)__pyx_pw_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_2lambda3, METH_O, 0}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_2lambda3(PyObject *__pyx_self, PyObject *__pyx_v_ts) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("lambda3 (wrapper)", 0); - __pyx_r = __pyx_lambda_funcdef_lambda3(__pyx_self, ((PyObject *)__pyx_v_ts)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_lambda_funcdef_lambda3(PyObject *__pyx_self, PyObject *__pyx_v_ts) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *__pyx_cur_scope; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *__pyx_outer_scope; - 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("lambda3", 0); - __pyx_outer_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *) __Pyx_CyFunction_GetClosure(__pyx_self); - __pyx_cur_scope = __pyx_outer_scope; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_ts, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(!__pyx_cur_scope->__pyx_v_precision)) { __Pyx_RaiseClosureNameError("precision"); __PYX_ERR(0, 1359, __pyx_L1_error) } - __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_cur_scope->__pyx_v_precision); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyNumber_Int(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_ts, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (unlikely(!__pyx_cur_scope->__pyx_v_precision)) { __Pyx_RaiseClosureNameError("precision"); __PYX_ERR(0, 1359, __pyx_L1_error) } - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_cur_scope->__pyx_v_precision); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyNumber_Int(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1359, __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_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_curve_intersections_t.lambda3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_84_curve_curve_intersections_t(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve1, PyObject *__pyx_v_curve2, PyObject *__pyx_v_precision, PyObject *__pyx_v_range1, PyObject *__pyx_v_range2) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *__pyx_cur_scope; - PyObject *__pyx_v_bounds1 = NULL; - PyObject *__pyx_v_bounds2 = NULL; - PyObject *__pyx_v_intersects = NULL; - CYTHON_UNUSED PyObject *__pyx_v__ = NULL; - PyObject *__pyx_v_midpoint = 0; - PyObject *__pyx_v_c11 = NULL; - PyObject *__pyx_v_c12 = NULL; - PyObject *__pyx_v_c11_range = NULL; - PyObject *__pyx_v_c12_range = NULL; - PyObject *__pyx_v_c21 = NULL; - PyObject *__pyx_v_c22 = NULL; - PyObject *__pyx_v_c21_range = NULL; - PyObject *__pyx_v_c22_range = NULL; - PyObject *__pyx_v_found = NULL; - PyObject *__pyx_v_unique_key = NULL; - PyObject *__pyx_v_seen = NULL; - PyObject *__pyx_v_unique_values = NULL; - PyObject *__pyx_v_ts = NULL; - PyObject *__pyx_v_key = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - int __pyx_t_9; - Py_ssize_t __pyx_t_10; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_curve_curve_intersections_t", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 1306, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_v_precision = __pyx_v_precision; - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_precision); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_precision); - __Pyx_INCREF(__pyx_v_range1); - __Pyx_INCREF(__pyx_v_range2); - - /* "fontTools/misc/bezierTools.py":1309 - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - * bounds1 = _curve_bounds(curve1) # <<<<<<<<<<<<<< - * bounds2 = _curve_bounds(curve2) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_curve_bounds); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1309, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, __pyx_v_curve1) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_curve1); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1309, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_bounds1 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1310 - * ): - * bounds1 = _curve_bounds(curve1) - * bounds2 = _curve_bounds(curve2) # <<<<<<<<<<<<<< - * - * if not range1: - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_curve_bounds); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1310, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, __pyx_v_curve2) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_curve2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1310, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_bounds2 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1312 - * bounds2 = _curve_bounds(curve2) - * - * if not range1: # <<<<<<<<<<<<<< - * range1 = (0.0, 1.0) - * if not range2: - */ - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_range1); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 1312, __pyx_L1_error) - __pyx_t_5 = ((!__pyx_t_4) != 0); - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1313 - * - * if not range1: - * range1 = (0.0, 1.0) # <<<<<<<<<<<<<< - * if not range2: - * range2 = (0.0, 1.0) - */ - __Pyx_INCREF(__pyx_tuple__5); - __Pyx_DECREF_SET(__pyx_v_range1, __pyx_tuple__5); - - /* "fontTools/misc/bezierTools.py":1312 - * bounds2 = _curve_bounds(curve2) - * - * if not range1: # <<<<<<<<<<<<<< - * range1 = (0.0, 1.0) - * if not range2: - */ - } - - /* "fontTools/misc/bezierTools.py":1314 - * if not range1: - * range1 = (0.0, 1.0) - * if not range2: # <<<<<<<<<<<<<< - * range2 = (0.0, 1.0) - * - */ - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_range2); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1314, __pyx_L1_error) - __pyx_t_4 = ((!__pyx_t_5) != 0); - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":1315 - * range1 = (0.0, 1.0) - * if not range2: - * range2 = (0.0, 1.0) # <<<<<<<<<<<<<< - * - * # If bounds don't intersect, go home - */ - __Pyx_INCREF(__pyx_tuple__5); - __Pyx_DECREF_SET(__pyx_v_range2, __pyx_tuple__5); - - /* "fontTools/misc/bezierTools.py":1314 - * if not range1: - * range1 = (0.0, 1.0) - * if not range2: # <<<<<<<<<<<<<< - * range2 = (0.0, 1.0) - * - */ - } - - /* "fontTools/misc/bezierTools.py":1318 - * - * # If bounds don't intersect, go home - * intersects, _ = sectRect(bounds1, bounds2) # <<<<<<<<<<<<<< - * if not intersects: - * return [] - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_sectRect); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_bounds1, __pyx_v_bounds2}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_bounds1, __pyx_v_bounds2}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_bounds1); - __Pyx_GIVEREF(__pyx_v_bounds1); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_bounds1); - __Pyx_INCREF(__pyx_v_bounds2); - __Pyx_GIVEREF(__pyx_v_bounds2); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_bounds2); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - 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(0, 1318, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_7 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_7); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1318, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_8(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_7 = __pyx_t_8(__pyx_t_3); if (unlikely(!__pyx_t_7)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_7); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_3), 2) < 0) __PYX_ERR(0, 1318, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1318, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_v_intersects = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v__ = __pyx_t_7; - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1319 - * # If bounds don't intersect, go home - * intersects, _ = sectRect(bounds1, bounds2) - * if not intersects: # <<<<<<<<<<<<<< - * return [] - * - */ - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_intersects); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 1319, __pyx_L1_error) - __pyx_t_5 = ((!__pyx_t_4) != 0); - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1320 - * intersects, _ = sectRect(bounds1, bounds2) - * if not intersects: - * return [] # <<<<<<<<<<<<<< - * - * def midpoint(r): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1320, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1319 - * # If bounds don't intersect, go home - * intersects, _ = sectRect(bounds1, bounds2) - * if not intersects: # <<<<<<<<<<<<<< - * return [] - * - */ - } - - /* "fontTools/misc/bezierTools.py":1322 - * return [] - * - * def midpoint(r): # <<<<<<<<<<<<<< - * return 0.5 * (r[0] + r[1]) - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_1midpoint, 0, __pyx_n_s_curve_curve_intersections_t_loc, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__7)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1322, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_midpoint = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1326 - * - * # If they do overlap but they're tiny, approximate - * if rectArea(bounds1) < precision and rectArea(bounds2) < precision: # <<<<<<<<<<<<<< - * return [(midpoint(range1), midpoint(range2))] - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_rectArea); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_2, __pyx_v_bounds1) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_v_bounds1); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_RichCompare(__pyx_t_1, __pyx_cur_scope->__pyx_v_precision, Py_LT); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (__pyx_t_4) { - } else { - __pyx_t_5 = __pyx_t_4; - goto __pyx_L9_bool_binop_done; - } - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_rectArea); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - __pyx_t_7 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_2, __pyx_v_bounds2) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_v_bounds2); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_RichCompare(__pyx_t_7, __pyx_cur_scope->__pyx_v_precision, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 1326, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_t_4; - __pyx_L9_bool_binop_done:; - if (__pyx_t_5) { - - /* "fontTools/misc/bezierTools.py":1327 - * # If they do overlap but they're tiny, approximate - * if rectArea(bounds1) < precision and rectArea(bounds2) < precision: - * return [(midpoint(range1), midpoint(range2))] # <<<<<<<<<<<<<< - * - * c11, c12 = _split_segment_at_t(curve1, 0.5) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_v_midpoint, __pyx_v_range1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_v_midpoint, __pyx_v_range2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_7); - __pyx_t_1 = 0; - __pyx_t_7 = 0; - __pyx_t_7 = PyList_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_2); - PyList_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_r = __pyx_t_7; - __pyx_t_7 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1326 - * - * # If they do overlap but they're tiny, approximate - * if rectArea(bounds1) < precision and rectArea(bounds2) < precision: # <<<<<<<<<<<<<< - * return [(midpoint(range1), midpoint(range2))] - * - */ - } - - /* "fontTools/misc/bezierTools.py":1329 - * return [(midpoint(range1), midpoint(range2))] - * - * c11, c12 = _split_segment_at_t(curve1, 0.5) # <<<<<<<<<<<<<< - * c11_range = (range1[0], midpoint(range1)) - * c12_range = (midpoint(range1), range1[1]) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_split_segment_at_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = NULL; - __pyx_t_6 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_v_curve1, __pyx_float_0_5}; - __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_v_curve1, __pyx_float_0_5}; - __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - { - __pyx_t_3 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_INCREF(__pyx_v_curve1); - __Pyx_GIVEREF(__pyx_v_curve1); - PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_6, __pyx_v_curve1); - __Pyx_INCREF(__pyx_float_0_5); - __Pyx_GIVEREF(__pyx_float_0_5); - PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_6, __pyx_float_0_5); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_7))) || (PyList_CheckExact(__pyx_t_7))) { - PyObject* sequence = __pyx_t_7; - 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(0, 1329, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_3 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_1 = PyObject_GetIter(__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1329, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_1)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_8(__pyx_t_1); if (unlikely(!__pyx_t_2)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_3 = __pyx_t_8(__pyx_t_1); if (unlikely(!__pyx_t_3)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_1), 2) < 0) __PYX_ERR(0, 1329, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L12_unpacking_done; - __pyx_L11_unpacking_failed:; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1329, __pyx_L1_error) - __pyx_L12_unpacking_done:; - } - __pyx_v_c11 = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_c12 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1330 - * - * c11, c12 = _split_segment_at_t(curve1, 0.5) - * c11_range = (range1[0], midpoint(range1)) # <<<<<<<<<<<<<< - * c12_range = (midpoint(range1), range1[1]) - * - */ - __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_range1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1330, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_v_midpoint, __pyx_v_range1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1330, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1330, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); - __pyx_t_7 = 0; - __pyx_t_3 = 0; - __pyx_v_c11_range = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1331 - * c11, c12 = _split_segment_at_t(curve1, 0.5) - * c11_range = (range1[0], midpoint(range1)) - * c12_range = (midpoint(range1), range1[1]) # <<<<<<<<<<<<<< - * - * c21, c22 = _split_segment_at_t(curve2, 0.5) - */ - __pyx_t_2 = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_v_midpoint, __pyx_v_range1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1331, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_range1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1331, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1331, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_v_c12_range = ((PyObject*)__pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1333 - * c12_range = (midpoint(range1), range1[1]) - * - * c21, c22 = _split_segment_at_t(curve2, 0.5) # <<<<<<<<<<<<<< - * c21_range = (range2[0], midpoint(range2)) - * c22_range = (midpoint(range2), range2[1]) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_split_segment_at_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = NULL; - __pyx_t_6 = 0; - 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_6 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_curve2, __pyx_float_0_5}; - __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_v_curve2, __pyx_float_0_5}; - __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - { - __pyx_t_1 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(__pyx_v_curve2); - __Pyx_GIVEREF(__pyx_v_curve2); - PyTuple_SET_ITEM(__pyx_t_1, 0+__pyx_t_6, __pyx_v_curve2); - __Pyx_INCREF(__pyx_float_0_5); - __Pyx_GIVEREF(__pyx_float_0_5); - PyTuple_SET_ITEM(__pyx_t_1, 1+__pyx_t_6, __pyx_float_0_5); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_7))) || (PyList_CheckExact(__pyx_t_7))) { - PyObject* sequence = __pyx_t_7; - 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(0, 1333, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_1); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_2 = PyObject_GetIter(__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1333, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_2)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_8(__pyx_t_2); if (unlikely(!__pyx_t_3)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_1 = __pyx_t_8(__pyx_t_2); if (unlikely(!__pyx_t_1)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_2), 2) < 0) __PYX_ERR(0, 1333, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L14_unpacking_done; - __pyx_L13_unpacking_failed:; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 1333, __pyx_L1_error) - __pyx_L14_unpacking_done:; - } - __pyx_v_c21 = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_c22 = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1334 - * - * c21, c22 = _split_segment_at_t(curve2, 0.5) - * c21_range = (range2[0], midpoint(range2)) # <<<<<<<<<<<<<< - * c22_range = (midpoint(range2), range2[1]) - * - */ - __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_range2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1334, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_1 = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_v_midpoint, __pyx_v_range2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1334, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1334, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __pyx_t_7 = 0; - __pyx_t_1 = 0; - __pyx_v_c21_range = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1335 - * c21, c22 = _split_segment_at_t(curve2, 0.5) - * c21_range = (range2[0], midpoint(range2)) - * c22_range = (midpoint(range2), range2[1]) # <<<<<<<<<<<<<< - * - * found = [] - */ - __pyx_t_3 = __pyx_pf_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_midpoint(__pyx_v_midpoint, __pyx_v_range2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1335, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_range2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1335, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1335, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_1); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_v_c22_range = ((PyObject*)__pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1337 - * c22_range = (midpoint(range2), range2[1]) - * - * found = [] # <<<<<<<<<<<<<< - * found.extend( - * _curve_curve_intersections_t( - */ - __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1337, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_v_found = ((PyObject*)__pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1339 - * found = [] - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c11, c21, precision, range1=c11_range, range2=c21_range - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_curve_curve_intersections_t); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1339, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "fontTools/misc/bezierTools.py":1340 - * found.extend( - * _curve_curve_intersections_t( - * c11, c21, precision, range1=c11_range, range2=c21_range # <<<<<<<<<<<<<< - * ) - * ) - */ - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1339, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_c11); - __Pyx_GIVEREF(__pyx_v_c11); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_c11); - __Pyx_INCREF(__pyx_v_c21); - __Pyx_GIVEREF(__pyx_v_c21); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_c21); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_precision); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_precision); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_cur_scope->__pyx_v_precision); - __pyx_t_3 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1340, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_range1, __pyx_v_c11_range) < 0) __PYX_ERR(0, 1340, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_range2, __pyx_v_c21_range) < 0) __PYX_ERR(0, 1340, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1339 - * found = [] - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c11, c21, precision, range1=c11_range, range2=c21_range - * ) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1339, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1338 - * - * found = [] - * found.extend( # <<<<<<<<<<<<<< - * _curve_curve_intersections_t( - * c11, c21, precision, range1=c11_range, range2=c21_range - */ - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_found, __pyx_t_2); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 1338, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1344 - * ) - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c12, c21, precision, range1=c12_range, range2=c21_range - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_curve_curve_intersections_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1344, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":1345 - * found.extend( - * _curve_curve_intersections_t( - * c12, c21, precision, range1=c12_range, range2=c21_range # <<<<<<<<<<<<<< - * ) - * ) - */ - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1344, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_c12); - __Pyx_GIVEREF(__pyx_v_c12); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_c12); - __Pyx_INCREF(__pyx_v_c21); - __Pyx_GIVEREF(__pyx_v_c21); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_c21); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_precision); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_precision); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_cur_scope->__pyx_v_precision); - __pyx_t_1 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1345, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_range1, __pyx_v_c12_range) < 0) __PYX_ERR(0, 1345, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_range2, __pyx_v_c21_range) < 0) __PYX_ERR(0, 1345, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1344 - * ) - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c12, c21, precision, range1=c12_range, range2=c21_range - * ) - */ - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1344, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1343 - * ) - * ) - * found.extend( # <<<<<<<<<<<<<< - * _curve_curve_intersections_t( - * c12, c21, precision, range1=c12_range, range2=c21_range - */ - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_found, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 1343, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1349 - * ) - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c11, c22, precision, range1=c11_range, range2=c22_range - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_curve_curve_intersections_t); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1349, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "fontTools/misc/bezierTools.py":1350 - * found.extend( - * _curve_curve_intersections_t( - * c11, c22, precision, range1=c11_range, range2=c22_range # <<<<<<<<<<<<<< - * ) - * ) - */ - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1349, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_c11); - __Pyx_GIVEREF(__pyx_v_c11); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_c11); - __Pyx_INCREF(__pyx_v_c22); - __Pyx_GIVEREF(__pyx_v_c22); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_c22); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_precision); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_precision); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_cur_scope->__pyx_v_precision); - __pyx_t_3 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1350, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_range1, __pyx_v_c11_range) < 0) __PYX_ERR(0, 1350, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_range2, __pyx_v_c22_range) < 0) __PYX_ERR(0, 1350, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1349 - * ) - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c11, c22, precision, range1=c11_range, range2=c22_range - * ) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1349, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "fontTools/misc/bezierTools.py":1348 - * ) - * ) - * found.extend( # <<<<<<<<<<<<<< - * _curve_curve_intersections_t( - * c11, c22, precision, range1=c11_range, range2=c22_range - */ - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_found, __pyx_t_2); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 1348, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1354 - * ) - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c12, c22, precision, range1=c12_range, range2=c22_range - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_curve_curve_intersections_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1354, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "fontTools/misc/bezierTools.py":1355 - * found.extend( - * _curve_curve_intersections_t( - * c12, c22, precision, range1=c12_range, range2=c22_range # <<<<<<<<<<<<<< - * ) - * ) - */ - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1354, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_c12); - __Pyx_GIVEREF(__pyx_v_c12); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_c12); - __Pyx_INCREF(__pyx_v_c22); - __Pyx_GIVEREF(__pyx_v_c22); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_c22); - __Pyx_INCREF(__pyx_cur_scope->__pyx_v_precision); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_precision); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_cur_scope->__pyx_v_precision); - __pyx_t_1 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1355, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_range1, __pyx_v_c12_range) < 0) __PYX_ERR(0, 1355, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_range2, __pyx_v_c22_range) < 0) __PYX_ERR(0, 1355, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1354 - * ) - * found.extend( - * _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * c12, c22, precision, range1=c12_range, range2=c22_range - * ) - */ - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1354, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1353 - * ) - * ) - * found.extend( # <<<<<<<<<<<<<< - * _curve_curve_intersections_t( - * c12, c22, precision, range1=c12_range, range2=c22_range - */ - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_found, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 1353, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1359 - * ) - * - * unique_key = lambda ts: (int(ts[0] / precision), int(ts[1] / precision)) # <<<<<<<<<<<<<< - * seen = set() - * unique_values = [] - */ - __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_28_curve_curve_intersections_t_2lambda3, 0, __pyx_n_s_curve_curve_intersections_t_loc_2, ((PyObject*)__pyx_cur_scope), __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_v_unique_key = __pyx_t_7; - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1360 - * - * unique_key = lambda ts: (int(ts[0] / precision), int(ts[1] / precision)) - * seen = set() # <<<<<<<<<<<<<< - * unique_values = [] - * - */ - __pyx_t_7 = PySet_New(0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1360, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_v_seen = ((PyObject*)__pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1361 - * unique_key = lambda ts: (int(ts[0] / precision), int(ts[1] / precision)) - * seen = set() - * unique_values = [] # <<<<<<<<<<<<<< - * - * for ts in found: - */ - __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1361, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_v_unique_values = ((PyObject*)__pyx_t_7); - __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1363 - * unique_values = [] - * - * for ts in found: # <<<<<<<<<<<<<< - * key = unique_key(ts) - * if key in seen: - */ - __pyx_t_7 = __pyx_v_found; __Pyx_INCREF(__pyx_t_7); __pyx_t_10 = 0; - for (;;) { - if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_10); __Pyx_INCREF(__pyx_t_1); __pyx_t_10++; if (unlikely(0 < 0)) __PYX_ERR(0, 1363, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_7, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1363, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - __Pyx_XDECREF_SET(__pyx_v_ts, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1364 - * - * for ts in found: - * key = unique_key(ts) # <<<<<<<<<<<<<< - * if key in seen: - * continue - */ - __pyx_t_1 = __pyx_lambda_funcdef_lambda3(__pyx_v_unique_key, __pyx_v_ts); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1364, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_1); - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1365 - * for ts in found: - * key = unique_key(ts) - * if key in seen: # <<<<<<<<<<<<<< - * continue - * seen.add(key) - */ - __pyx_t_5 = (__Pyx_PySet_ContainsTF(__pyx_v_key, __pyx_v_seen, Py_EQ)); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 1365, __pyx_L1_error) - __pyx_t_4 = (__pyx_t_5 != 0); - if (__pyx_t_4) { - - /* "fontTools/misc/bezierTools.py":1366 - * key = unique_key(ts) - * if key in seen: - * continue # <<<<<<<<<<<<<< - * seen.add(key) - * unique_values.append(ts) - */ - goto __pyx_L15_continue; - - /* "fontTools/misc/bezierTools.py":1365 - * for ts in found: - * key = unique_key(ts) - * if key in seen: # <<<<<<<<<<<<<< - * continue - * seen.add(key) - */ - } - - /* "fontTools/misc/bezierTools.py":1367 - * if key in seen: - * continue - * seen.add(key) # <<<<<<<<<<<<<< - * unique_values.append(ts) - * - */ - __pyx_t_9 = PySet_Add(__pyx_v_seen, __pyx_v_key); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 1367, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1368 - * continue - * seen.add(key) - * unique_values.append(ts) # <<<<<<<<<<<<<< - * - * return unique_values - */ - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_unique_values, __pyx_v_ts); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 1368, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1363 - * unique_values = [] - * - * for ts in found: # <<<<<<<<<<<<<< - * key = unique_key(ts) - * if key in seen: - */ - __pyx_L15_continue:; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "fontTools/misc/bezierTools.py":1370 - * unique_values.append(ts) - * - * return unique_values # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_unique_values); - __pyx_r = __pyx_v_unique_values; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ - - /* 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_7); - __Pyx_AddTraceback("fontTools.misc.bezierTools._curve_curve_intersections_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_bounds1); - __Pyx_XDECREF(__pyx_v_bounds2); - __Pyx_XDECREF(__pyx_v_intersects); - __Pyx_XDECREF(__pyx_v__); - __Pyx_XDECREF(__pyx_v_midpoint); - __Pyx_XDECREF(__pyx_v_c11); - __Pyx_XDECREF(__pyx_v_c12); - __Pyx_XDECREF(__pyx_v_c11_range); - __Pyx_XDECREF(__pyx_v_c12_range); - __Pyx_XDECREF(__pyx_v_c21); - __Pyx_XDECREF(__pyx_v_c22); - __Pyx_XDECREF(__pyx_v_c21_range); - __Pyx_XDECREF(__pyx_v_c22_range); - __Pyx_XDECREF(__pyx_v_found); - __Pyx_XDECREF(__pyx_v_unique_key); - __Pyx_XDECREF(__pyx_v_seen); - __Pyx_XDECREF(__pyx_v_unique_values); - __Pyx_XDECREF(__pyx_v_ts); - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XDECREF(__pyx_v_range1); - __Pyx_XDECREF(__pyx_v_range2); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1373 - * - * - * def curveCurveIntersections(curve1, curve2): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a curve. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_87curveCurveIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_86curveCurveIntersections[] = "curveCurveIntersections(curve1, curve2)\nFinds intersections between a curve and a curve.\n\n Args:\n curve1: List of coordinates of the first curve segment as 2D tuples.\n curve2: List of coordinates of the second curve segment as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]\n >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]\n >>> intersections = curveCurveIntersections(curve1, curve2)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (81.7831487395506, 109.88904552375288)\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_87curveCurveIntersections = {"curveCurveIntersections", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_87curveCurveIntersections, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_86curveCurveIntersections}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_87curveCurveIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_curve1 = 0; - PyObject *__pyx_v_curve2 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("curveCurveIntersections (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_curve1,&__pyx_n_s_curve2,0}; - PyObject* values[2] = {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 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_curve1)) != 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_curve2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("curveCurveIntersections", 1, 2, 2, 1); __PYX_ERR(0, 1373, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "curveCurveIntersections") < 0)) __PYX_ERR(0, 1373, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_curve1 = values[0]; - __pyx_v_curve2 = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("curveCurveIntersections", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1373, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.curveCurveIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_86curveCurveIntersections(__pyx_self, __pyx_v_curve1, __pyx_v_curve2); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_86curveCurveIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_curve1, PyObject *__pyx_v_curve2) { - PyObject *__pyx_v_intersection_ts = NULL; - PyObject *__pyx_8genexpr7__pyx_v_ts = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - Py_ssize_t __pyx_t_6; - PyObject *(*__pyx_t_7)(PyObject *); - 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("curveCurveIntersections", 0); - - /* "fontTools/misc/bezierTools.py":1394 - * (81.7831487395506, 109.88904552375288) - * """ - * intersection_ts = _curve_curve_intersections_t(curve1, curve2) # <<<<<<<<<<<<<< - * return [ - * Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1]) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_curve_curve_intersections_t); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1394, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_curve1, __pyx_v_curve2}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1394, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_curve1, __pyx_v_curve2}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1394, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(2+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1394, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_curve1); - __Pyx_GIVEREF(__pyx_v_curve1); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, __pyx_v_curve1); - __Pyx_INCREF(__pyx_v_curve2); - __Pyx_GIVEREF(__pyx_v_curve2); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, __pyx_v_curve2); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1394, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_intersection_ts = __pyx_t_1; - __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1395 - * """ - * intersection_ts = _curve_curve_intersections_t(curve1, curve2) - * return [ # <<<<<<<<<<<<<< - * Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1]) - * for ts in intersection_ts - */ - __Pyx_XDECREF(__pyx_r); - { /* enter inner scope */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1395, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_1); - - /* "fontTools/misc/bezierTools.py":1397 - * return [ - * Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1]) - * for ts in intersection_ts # <<<<<<<<<<<<<< - * ] - * - */ - if (likely(PyList_CheckExact(__pyx_v_intersection_ts)) || PyTuple_CheckExact(__pyx_v_intersection_ts)) { - __pyx_t_2 = __pyx_v_intersection_ts; __Pyx_INCREF(__pyx_t_2); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - } else { - __pyx_t_6 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_intersection_ts); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1397, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1397, __pyx_L5_error) - } - for (;;) { - if (likely(!__pyx_t_7)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_6 >= 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_6); __Pyx_INCREF(__pyx_t_5); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 1397, __pyx_L5_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1397, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } else { - if (__pyx_t_6 >= 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_6); __Pyx_INCREF(__pyx_t_5); __pyx_t_6++; if (unlikely(0 < 0)) __PYX_ERR(0, 1397, __pyx_L5_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1397, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } - } else { - __pyx_t_5 = __pyx_t_7(__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(0, 1397, __pyx_L5_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_5); - } - __Pyx_XDECREF_SET(__pyx_8genexpr7__pyx_v_ts, __pyx_t_5); - __pyx_t_5 = 0; - - /* "fontTools/misc/bezierTools.py":1396 - * intersection_ts = _curve_curve_intersections_t(curve1, curve2) - * return [ - * Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1]) # <<<<<<<<<<<<<< - * for ts in intersection_ts - * ] - */ - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_Intersection); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_n_s_segmentPointAtT); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_10 = __Pyx_GetItemInt(__pyx_8genexpr7__pyx_v_ts, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_11 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_9))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_9); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_9, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_9)) { - PyObject *__pyx_temp[3] = {__pyx_t_11, __pyx_v_curve1, __pyx_t_10}; - __pyx_t_8 = __Pyx_PyFunction_FastCall(__pyx_t_9, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_9)) { - PyObject *__pyx_temp[3] = {__pyx_t_11, __pyx_v_curve1, __pyx_t_10}; - __pyx_t_8 = __Pyx_PyCFunction_FastCall(__pyx_t_9, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - { - __pyx_t_12 = PyTuple_New(2+__pyx_t_4); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_12); - if (__pyx_t_11) { - __Pyx_GIVEREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_11); __pyx_t_11 = NULL; - } - __Pyx_INCREF(__pyx_v_curve1); - __Pyx_GIVEREF(__pyx_v_curve1); - PyTuple_SET_ITEM(__pyx_t_12, 0+__pyx_t_4, __pyx_v_curve1); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_12, 1+__pyx_t_4, __pyx_t_10); - __pyx_t_10 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_t_12, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_pt, __pyx_t_8) < 0) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_GetItemInt(__pyx_8genexpr7__pyx_v_ts, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_8); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_t1, __pyx_t_8) < 0) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_GetItemInt(__pyx_8genexpr7__pyx_v_ts, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_8); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_t2, __pyx_t_8) < 0) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_empty_tuple, __pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1396, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_8))) __PYX_ERR(0, 1395, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "fontTools/misc/bezierTools.py":1397 - * return [ - * Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1]) - * for ts in intersection_ts # <<<<<<<<<<<<<< - * ] - * - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_8genexpr7__pyx_v_ts); __pyx_8genexpr7__pyx_v_ts = 0; - goto __pyx_L8_exit_scope; - __pyx_L5_error:; - __Pyx_XDECREF(__pyx_8genexpr7__pyx_v_ts); __pyx_8genexpr7__pyx_v_ts = 0; - goto __pyx_L1_error; - __pyx_L8_exit_scope:; - } /* exit inner scope */ - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1373 - * - * - * def curveCurveIntersections(curve1, curve2): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a curve. - * - */ - - /* 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_5); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("fontTools.misc.bezierTools.curveCurveIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_intersection_ts); - __Pyx_XDECREF(__pyx_8genexpr7__pyx_v_ts); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1401 - * - * - * def segmentSegmentIntersections(seg1, seg2): # <<<<<<<<<<<<<< - * """Finds intersections between two segments. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_89segmentSegmentIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_88segmentSegmentIntersections[] = "segmentSegmentIntersections(seg1, seg2)\nFinds intersections between two segments.\n\n Args:\n seg1: List of coordinates of the first segment as 2D tuples.\n seg2: List of coordinates of the second segment as 2D tuples.\n\n Returns:\n A list of ``Intersection`` objects, each object having ``pt``, ``t1``\n and ``t2`` attributes containing the intersection point, time on first\n segment and time on second segment respectively.\n\n Examples::\n >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]\n >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]\n >>> intersections = segmentSegmentIntersections(curve1, curve2)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (81.7831487395506, 109.88904552375288)\n >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ]\n >>> line = [ (25, 260), (230, 20) ]\n >>> intersections = segmentSegmentIntersections(curve3, line)\n >>> len(intersections)\n 3\n >>> intersections[0].pt\n (84.9000930760723, 189.87306176459828)\n\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_89segmentSegmentIntersections = {"segmentSegmentIntersections", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_9fontTools_4misc_11bezierTools_89segmentSegmentIntersections, METH_VARARGS|METH_KEYWORDS, __pyx_doc_9fontTools_4misc_11bezierTools_88segmentSegmentIntersections}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_89segmentSegmentIntersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_seg1 = 0; - PyObject *__pyx_v_seg2 = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("segmentSegmentIntersections (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_seg1,&__pyx_n_s_seg2,0}; - PyObject* values[2] = {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 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_seg1)) != 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_seg2)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("segmentSegmentIntersections", 1, 2, 2, 1); __PYX_ERR(0, 1401, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "segmentSegmentIntersections") < 0)) __PYX_ERR(0, 1401, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_seg1 = values[0]; - __pyx_v_seg2 = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("segmentSegmentIntersections", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 1401, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools.segmentSegmentIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_88segmentSegmentIntersections(__pyx_self, __pyx_v_seg1, __pyx_v_seg2); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_88segmentSegmentIntersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_seg1, PyObject *__pyx_v_seg2) { - int __pyx_v_swapped; - PyObject *__pyx_v_intersections = NULL; - PyObject *__pyx_8genexpr8__pyx_v_i = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - Py_ssize_t __pyx_t_2; - int __pyx_t_3; - 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; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - PyObject *(*__pyx_t_12)(PyObject *); - PyObject *__pyx_t_13 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("segmentSegmentIntersections", 0); - __Pyx_INCREF(__pyx_v_seg1); - __Pyx_INCREF(__pyx_v_seg2); - - /* "fontTools/misc/bezierTools.py":1431 - * """ - * # Arrange by degree - * swapped = False # <<<<<<<<<<<<<< - * if len(seg2) > len(seg1): - * seg2, seg1 = seg1, seg2 - */ - __pyx_v_swapped = 0; - - /* "fontTools/misc/bezierTools.py":1432 - * # Arrange by degree - * swapped = False - * if len(seg2) > len(seg1): # <<<<<<<<<<<<<< - * seg2, seg1 = seg1, seg2 - * swapped = True - */ - __pyx_t_1 = PyObject_Length(__pyx_v_seg2); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1432, __pyx_L1_error) - __pyx_t_2 = PyObject_Length(__pyx_v_seg1); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1432, __pyx_L1_error) - __pyx_t_3 = ((__pyx_t_1 > __pyx_t_2) != 0); - if (__pyx_t_3) { - - /* "fontTools/misc/bezierTools.py":1433 - * swapped = False - * if len(seg2) > len(seg1): - * seg2, seg1 = seg1, seg2 # <<<<<<<<<<<<<< - * swapped = True - * if len(seg1) > 2: - */ - __pyx_t_4 = __pyx_v_seg1; - __pyx_t_5 = __pyx_v_seg2; - __pyx_v_seg2 = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_v_seg1 = __pyx_t_5; - __pyx_t_5 = 0; - - /* "fontTools/misc/bezierTools.py":1434 - * if len(seg2) > len(seg1): - * seg2, seg1 = seg1, seg2 - * swapped = True # <<<<<<<<<<<<<< - * if len(seg1) > 2: - * if len(seg2) > 2: - */ - __pyx_v_swapped = 1; - - /* "fontTools/misc/bezierTools.py":1432 - * # Arrange by degree - * swapped = False - * if len(seg2) > len(seg1): # <<<<<<<<<<<<<< - * seg2, seg1 = seg1, seg2 - * swapped = True - */ - } - - /* "fontTools/misc/bezierTools.py":1435 - * seg2, seg1 = seg1, seg2 - * swapped = True - * if len(seg1) > 2: # <<<<<<<<<<<<<< - * if len(seg2) > 2: - * intersections = curveCurveIntersections(seg1, seg2) - */ - __pyx_t_2 = PyObject_Length(__pyx_v_seg1); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1435, __pyx_L1_error) - __pyx_t_3 = ((__pyx_t_2 > 2) != 0); - if (__pyx_t_3) { - - /* "fontTools/misc/bezierTools.py":1436 - * swapped = True - * if len(seg1) > 2: - * if len(seg2) > 2: # <<<<<<<<<<<<<< - * intersections = curveCurveIntersections(seg1, seg2) - * else: - */ - __pyx_t_2 = PyObject_Length(__pyx_v_seg2); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1436, __pyx_L1_error) - __pyx_t_3 = ((__pyx_t_2 > 2) != 0); - if (__pyx_t_3) { - - /* "fontTools/misc/bezierTools.py":1437 - * if len(seg1) > 2: - * if len(seg2) > 2: - * intersections = curveCurveIntersections(seg1, seg2) # <<<<<<<<<<<<<< - * else: - * intersections = curveLineIntersections(seg1, seg2) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_curveCurveIntersections); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1437, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = NULL; - __pyx_t_9 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(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_9 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_v_seg1, __pyx_v_seg2}; - __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_9, 2+__pyx_t_9); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1437, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_v_seg1, __pyx_v_seg2}; - __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_9, 2+__pyx_t_9); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1437, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - { - __pyx_t_10 = PyTuple_New(2+__pyx_t_9); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1437, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_8) { - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_8); __pyx_t_8 = NULL; - } - __Pyx_INCREF(__pyx_v_seg1); - __Pyx_GIVEREF(__pyx_v_seg1); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_9, __pyx_v_seg1); - __Pyx_INCREF(__pyx_v_seg2); - __Pyx_GIVEREF(__pyx_v_seg2); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_9, __pyx_v_seg2); - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_10, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1437, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_intersections = __pyx_t_6; - __pyx_t_6 = 0; - - /* "fontTools/misc/bezierTools.py":1436 - * swapped = True - * if len(seg1) > 2: - * if len(seg2) > 2: # <<<<<<<<<<<<<< - * intersections = curveCurveIntersections(seg1, seg2) - * else: - */ - goto __pyx_L5; - } - - /* "fontTools/misc/bezierTools.py":1439 - * intersections = curveCurveIntersections(seg1, seg2) - * else: - * intersections = curveLineIntersections(seg1, seg2) # <<<<<<<<<<<<<< - * elif len(seg1) == 2 and len(seg2) == 2: - * intersections = lineLineIntersections(*seg1, *seg2) - */ - /*else*/ { - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_curveLineIntersections); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1439, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_10 = NULL; - __pyx_t_9 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_9 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_10, __pyx_v_seg1, __pyx_v_seg2}; - __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_9, 2+__pyx_t_9); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1439, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_10, __pyx_v_seg1, __pyx_v_seg2}; - __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_9, 2+__pyx_t_9); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1439, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - { - __pyx_t_8 = PyTuple_New(2+__pyx_t_9); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1439, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_v_seg1); - __Pyx_GIVEREF(__pyx_v_seg1); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_9, __pyx_v_seg1); - __Pyx_INCREF(__pyx_v_seg2); - __Pyx_GIVEREF(__pyx_v_seg2); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_9, __pyx_v_seg2); - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_8, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1439, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_intersections = __pyx_t_6; - __pyx_t_6 = 0; - } - __pyx_L5:; - - /* "fontTools/misc/bezierTools.py":1435 - * seg2, seg1 = seg1, seg2 - * swapped = True - * if len(seg1) > 2: # <<<<<<<<<<<<<< - * if len(seg2) > 2: - * intersections = curveCurveIntersections(seg1, seg2) - */ - goto __pyx_L4; - } - - /* "fontTools/misc/bezierTools.py":1440 - * else: - * intersections = curveLineIntersections(seg1, seg2) - * elif len(seg1) == 2 and len(seg2) == 2: # <<<<<<<<<<<<<< - * intersections = lineLineIntersections(*seg1, *seg2) - * else: - */ - __pyx_t_2 = PyObject_Length(__pyx_v_seg1); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1440, __pyx_L1_error) - __pyx_t_11 = ((__pyx_t_2 == 2) != 0); - if (__pyx_t_11) { - } else { - __pyx_t_3 = __pyx_t_11; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_2 = PyObject_Length(__pyx_v_seg2); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 1440, __pyx_L1_error) - __pyx_t_11 = ((__pyx_t_2 == 2) != 0); - __pyx_t_3 = __pyx_t_11; - __pyx_L6_bool_binop_done:; - if (likely(__pyx_t_3)) { - - /* "fontTools/misc/bezierTools.py":1441 - * intersections = curveLineIntersections(seg1, seg2) - * elif len(seg1) == 2 and len(seg2) == 2: - * intersections = lineLineIntersections(*seg1, *seg2) # <<<<<<<<<<<<<< - * else: - * raise ValueError("Couldn't work out which intersection function to use") - */ - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_lineLineIntersections); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1441, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PySequence_Tuple(__pyx_v_seg1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1441, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PySequence_Tuple(__pyx_v_seg2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1441, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = PyNumber_Add(__pyx_t_7, __pyx_t_8); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1441, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_10, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1441, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_v_intersections = __pyx_t_8; - __pyx_t_8 = 0; - - /* "fontTools/misc/bezierTools.py":1440 - * else: - * intersections = curveLineIntersections(seg1, seg2) - * elif len(seg1) == 2 and len(seg2) == 2: # <<<<<<<<<<<<<< - * intersections = lineLineIntersections(*seg1, *seg2) - * else: - */ - goto __pyx_L4; - } - - /* "fontTools/misc/bezierTools.py":1443 - * intersections = lineLineIntersections(*seg1, *seg2) - * else: - * raise ValueError("Couldn't work out which intersection function to use") # <<<<<<<<<<<<<< - * if not swapped: - * return intersections - */ - /*else*/ { - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1443, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(0, 1443, __pyx_L1_error) - } - __pyx_L4:; - - /* "fontTools/misc/bezierTools.py":1444 - * else: - * raise ValueError("Couldn't work out which intersection function to use") - * if not swapped: # <<<<<<<<<<<<<< - * return intersections - * return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections] - */ - __pyx_t_3 = ((!(__pyx_v_swapped != 0)) != 0); - if (__pyx_t_3) { - - /* "fontTools/misc/bezierTools.py":1445 - * raise ValueError("Couldn't work out which intersection function to use") - * if not swapped: - * return intersections # <<<<<<<<<<<<<< - * return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections] - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_intersections); - __pyx_r = __pyx_v_intersections; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1444 - * else: - * raise ValueError("Couldn't work out which intersection function to use") - * if not swapped: # <<<<<<<<<<<<<< - * return intersections - * return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections] - */ - } - - /* "fontTools/misc/bezierTools.py":1446 - * if not swapped: - * return intersections - * return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections] # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - { /* enter inner scope */ - __pyx_t_8 = PyList_New(0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_8); - if (likely(PyList_CheckExact(__pyx_v_intersections)) || PyTuple_CheckExact(__pyx_v_intersections)) { - __pyx_t_10 = __pyx_v_intersections; __Pyx_INCREF(__pyx_t_10); __pyx_t_2 = 0; - __pyx_t_12 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_10 = PyObject_GetIter(__pyx_v_intersections); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_12 = Py_TYPE(__pyx_t_10)->tp_iternext; if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1446, __pyx_L11_error) - } - for (;;) { - if (likely(!__pyx_t_12)) { - if (likely(PyList_CheckExact(__pyx_t_10))) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_10)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_6 = PyList_GET_ITEM(__pyx_t_10, __pyx_t_2); __Pyx_INCREF(__pyx_t_6); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1446, __pyx_L11_error) - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_10, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - } else { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_10)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_10, __pyx_t_2); __Pyx_INCREF(__pyx_t_6); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1446, __pyx_L11_error) - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_10, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - } - } else { - __pyx_t_6 = __pyx_t_12(__pyx_t_10); - if (unlikely(!__pyx_t_6)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 1446, __pyx_L11_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_6); - } - __Pyx_XDECREF_SET(__pyx_8genexpr8__pyx_v_i, __pyx_t_6); - __pyx_t_6 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_Intersection); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_13 = __Pyx_PyObject_GetAttrStr(__pyx_8genexpr8__pyx_v_i, __pyx_n_s_pt); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_13); - if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_pt, __pyx_t_13) < 0) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_13 = __Pyx_PyObject_GetAttrStr(__pyx_8genexpr8__pyx_v_i, __pyx_n_s_t2); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_13); - if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_t1, __pyx_t_13) < 0) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_13 = __Pyx_PyObject_GetAttrStr(__pyx_8genexpr8__pyx_v_i, __pyx_n_s_t1); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_13); - if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_t2, __pyx_t_13) < 0) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_13 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_empty_tuple, __pyx_t_7); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_t_8, (PyObject*)__pyx_t_13))) __PYX_ERR(0, 1446, __pyx_L11_error) - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - } - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_8genexpr8__pyx_v_i); __pyx_8genexpr8__pyx_v_i = 0; - goto __pyx_L14_exit_scope; - __pyx_L11_error:; - __Pyx_XDECREF(__pyx_8genexpr8__pyx_v_i); __pyx_8genexpr8__pyx_v_i = 0; - goto __pyx_L1_error; - __pyx_L14_exit_scope:; - } /* exit inner scope */ - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L0; - - /* "fontTools/misc/bezierTools.py":1401 - * - * - * def segmentSegmentIntersections(seg1, seg2): # <<<<<<<<<<<<<< - * """Finds intersections between two segments. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_AddTraceback("fontTools.misc.bezierTools.segmentSegmentIntersections", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_intersections); - __Pyx_XDECREF(__pyx_8genexpr8__pyx_v_i); - __Pyx_XDECREF(__pyx_v_seg1); - __Pyx_XDECREF(__pyx_v_seg2); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1449 - * - * - * def _segmentrepr(obj): # <<<<<<<<<<<<<< - * """ - * >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]]) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_91_segmentrepr(PyObject *__pyx_self, PyObject *__pyx_v_obj); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_90_segmentrepr[] = "_segmentrepr(obj)\n\n >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]])\n '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))'\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_91_segmentrepr = {"_segmentrepr", (PyCFunction)__pyx_pw_9fontTools_4misc_11bezierTools_91_segmentrepr, METH_O, __pyx_doc_9fontTools_4misc_11bezierTools_90_segmentrepr}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_91_segmentrepr(PyObject *__pyx_self, PyObject *__pyx_v_obj) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_segmentrepr (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_90_segmentrepr(__pyx_self, ((PyObject *)__pyx_v_obj)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_12_segmentrepr_2generator5(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "fontTools/misc/bezierTools.py":1459 - * return "%g" % obj - * else: - * return "(%s)" % ", ".join(_segmentrepr(x) for x in it) # <<<<<<<<<<<<<< - * - * - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_12_segmentrepr_genexpr(PyObject *__pyx_self) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("genexpr", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 1459, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *) __pyx_self; - __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_4misc_11bezierTools_12_segmentrepr_2generator5, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_segmentrepr_locals_genexpr, __pyx_n_s_fontTools_misc_bezierTools); if (unlikely(!gen)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("fontTools.misc.bezierTools._segmentrepr.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_12_segmentrepr_2generator5(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *(*__pyx_t_3)(PyObject *); - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("genexpr", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 1459, __pyx_L1_error) - __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_GOTREF(__pyx_r); - if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_it)) { __Pyx_RaiseClosureNameError("it"); __PYX_ERR(0, 1459, __pyx_L1_error) } - if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_it)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_it)) { - __pyx_t_1 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_it; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - __pyx_t_3 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_it); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1459, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_3)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1459, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1459, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_3(__pyx_t_1); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 1459, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_x); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_x, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_segmentrepr); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(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_4 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_cur_scope->__pyx_v_x) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_cur_scope->__pyx_v_x); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_r, (PyObject*)__pyx_t_4))) __PYX_ERR(0, 1459, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1449 - * - * - * def _segmentrepr(obj): # <<<<<<<<<<<<<< - * """ - * >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]]) - */ - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_90_segmentrepr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *__pyx_cur_scope; - PyObject *__pyx_gb_9fontTools_4misc_11bezierTools_12_segmentrepr_2generator5 = 0; - 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; - int __pyx_t_6; - 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("_segmentrepr", 0); - __pyx_cur_scope = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *)__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr(__pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 1449, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - - /* "fontTools/misc/bezierTools.py":1454 - * '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))' - * """ - * try: # <<<<<<<<<<<<<< - * it = iter(obj) - * except TypeError: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "fontTools/misc/bezierTools.py":1455 - * """ - * try: - * it = iter(obj) # <<<<<<<<<<<<<< - * except TypeError: - * return "%g" % obj - */ - __pyx_t_4 = PyObject_GetIter(__pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1455, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_cur_scope->__pyx_v_it = __pyx_t_4; - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1454 - * '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))' - * """ - * try: # <<<<<<<<<<<<<< - * it = iter(obj) - * except TypeError: - */ - } - - /* "fontTools/misc/bezierTools.py":1459 - * return "%g" % obj - * else: - * return "(%s)" % ", ".join(_segmentrepr(x) for x in it) # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __pyx_pf_9fontTools_4misc_11bezierTools_12_segmentrepr_genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1459, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_Generator_Next(__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1459, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyUnicode_Join(__pyx_kp_u__9, __pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1459, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyUnicode_Format(__pyx_kp_u_s_2, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1459, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1456 - * try: - * it = iter(obj) - * except TypeError: # <<<<<<<<<<<<<< - * return "%g" % obj - * else: - */ - __pyx_t_6 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_6) { - __Pyx_AddTraceback("fontTools.misc.bezierTools._segmentrepr", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_4, &__pyx_t_7) < 0) __PYX_ERR(0, 1456, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GOTREF(__pyx_t_7); - - /* "fontTools/misc/bezierTools.py":1457 - * it = iter(obj) - * except TypeError: - * return "%g" % obj # <<<<<<<<<<<<<< - * else: - * return "(%s)" % ", ".join(_segmentrepr(x) for x in it) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_8 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_g, __pyx_v_obj); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1457, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L6_except_return; - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "fontTools/misc/bezierTools.py":1454 - * '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))' - * """ - * try: # <<<<<<<<<<<<<< - * it = iter(obj) - * except TypeError: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L0; - } - - /* "fontTools/misc/bezierTools.py":1449 - * - * - * def _segmentrepr(obj): # <<<<<<<<<<<<<< - * """ - * >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]]) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("fontTools.misc.bezierTools._segmentrepr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_gb_9fontTools_4misc_11bezierTools_12_segmentrepr_2generator5); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "fontTools/misc/bezierTools.py":1462 - * - * - * def printSegments(segments): # <<<<<<<<<<<<<< - * """Helper for the doctests, displaying each segment in a list of - * segments on a single line as a tuple. - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_93printSegments(PyObject *__pyx_self, PyObject *__pyx_v_segments); /*proto*/ -static char __pyx_doc_9fontTools_4misc_11bezierTools_92printSegments[] = "printSegments(segments)\nHelper for the doctests, displaying each segment in a list of\n segments on a single line as a tuple.\n "; -static PyMethodDef __pyx_mdef_9fontTools_4misc_11bezierTools_93printSegments = {"printSegments", (PyCFunction)__pyx_pw_9fontTools_4misc_11bezierTools_93printSegments, METH_O, __pyx_doc_9fontTools_4misc_11bezierTools_92printSegments}; -static PyObject *__pyx_pw_9fontTools_4misc_11bezierTools_93printSegments(PyObject *__pyx_self, PyObject *__pyx_v_segments) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("printSegments (wrapper)", 0); - __pyx_r = __pyx_pf_9fontTools_4misc_11bezierTools_92printSegments(__pyx_self, ((PyObject *)__pyx_v_segments)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_9fontTools_4misc_11bezierTools_92printSegments(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_segments) { - PyObject *__pyx_v_segment = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *(*__pyx_t_3)(PyObject *); - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("printSegments", 0); - - /* "fontTools/misc/bezierTools.py":1466 - * segments on a single line as a tuple. - * """ - * for segment in segments: # <<<<<<<<<<<<<< - * print(_segmentrepr(segment)) - * - */ - if (likely(PyList_CheckExact(__pyx_v_segments)) || PyTuple_CheckExact(__pyx_v_segments)) { - __pyx_t_1 = __pyx_v_segments; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - __pyx_t_3 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_segments); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1466, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1466, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_3)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1466, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1466, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 1466, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1466, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_3(__pyx_t_1); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 1466, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __Pyx_XDECREF_SET(__pyx_v_segment, __pyx_t_4); - __pyx_t_4 = 0; - - /* "fontTools/misc/bezierTools.py":1467 - * """ - * for segment in segments: - * print(_segmentrepr(segment)) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_segmentrepr); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1467, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(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_4 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_v_segment) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_v_segment); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1467, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_PyObject_CallOneArg(__pyx_builtin_print, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1467, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - - /* "fontTools/misc/bezierTools.py":1466 - * segments on a single line as a tuple. - * """ - * for segment in segments: # <<<<<<<<<<<<<< - * print(_segmentrepr(segment)) - * - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":1462 - * - * - * def printSegments(segments): # <<<<<<<<<<<<<< - * """Helper for the doctests, displaying each segment in a list of - * segments on a single line as a tuple. - */ - - /* 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_AddTraceback("fontTools.misc.bezierTools.printSegments", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_segment); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_solutions); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *)o; - if (p->__pyx_v_solutions) { - e = (*v)(p->__pyx_v_solutions, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic *)o; - tmp = ((PyObject*)p->__pyx_v_solutions); - p->__pyx_v_solutions = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct__splitQuadratic", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic, /*tp_traverse*/ - __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_outer_scope); - Py_CLEAR(p->__pyx_v_t); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr *)o; - if (p->__pyx_outer_scope) { - e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; - } - if (p->__pyx_v_t) { - e = (*v)(p->__pyx_v_t, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_1_genexpr", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_solutions); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *)o; - if (p->__pyx_v_solutions) { - e = (*v)(p->__pyx_v_solutions, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic *)o; - tmp = ((PyObject*)p->__pyx_v_solutions); - p->__pyx_v_solutions = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_2_splitCubic", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic, /*tp_traverse*/ - __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_outer_scope); - Py_CLEAR(p->__pyx_v_t); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr *)o; - if (p->__pyx_outer_scope) { - e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; - } - if (p->__pyx_v_t) { - e = (*v)(p->__pyx_v_t, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_3_genexpr", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_ts); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC *)o; - if (p->__pyx_v_ts) { - e = (*v)(p->__pyx_v_ts, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_4_splitCubicAtTC", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_i); - Py_CLEAR(p->__pyx_v_pt1); - Py_CLEAR(p->__pyx_v_pt2); - Py_CLEAR(p->__pyx_v_pt3); - Py_CLEAR(p->__pyx_v_pt4); - Py_CLEAR(p->__pyx_v_ts); - Py_CLEAR(p->__pyx_t_0); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC *)o; - if (p->__pyx_v_i) { - e = (*v)(p->__pyx_v_i, a); if (e) return e; - } - if (p->__pyx_v_pt1) { - e = (*v)(p->__pyx_v_pt1, a); if (e) return e; - } - if (p->__pyx_v_pt2) { - e = (*v)(p->__pyx_v_pt2, a); if (e) return e; - } - if (p->__pyx_v_pt3) { - e = (*v)(p->__pyx_v_pt3, a); if (e) return e; - } - if (p->__pyx_v_pt4) { - e = (*v)(p->__pyx_v_pt4, a); if (e) return e; - } - if (p->__pyx_v_ts) { - e = (*v)(p->__pyx_v_ts, a); if (e) return e; - } - if (p->__pyx_t_0) { - e = (*v)(p->__pyx_t_0, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_5__splitCubicAtTC", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_intersections); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *)o; - if (p->__pyx_v_intersections) { - e = (*v)(p->__pyx_v_intersections, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t *)o; - tmp = ((PyObject*)p->__pyx_v_intersections); - p->__pyx_v_intersections = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_6__curve_line_intersections_t", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t, /*tp_traverse*/ - __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_outer_scope); - Py_CLEAR(p->__pyx_v_i); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr *)o; - if (p->__pyx_outer_scope) { - e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; - } - if (p->__pyx_v_i) { - e = (*v)(p->__pyx_v_i, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_7_genexpr", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_precision); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *)o; - if (p->__pyx_v_precision) { - e = (*v)(p->__pyx_v_precision, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t *)o; - tmp = ((PyObject*)p->__pyx_v_precision); - p->__pyx_v_precision = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_8__curve_curve_intersections_t", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t, /*tp_traverse*/ - __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_it); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *)o; - if (p->__pyx_v_it) { - e = (*v)(p->__pyx_v_it, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr *)o; - tmp = ((PyObject*)p->__pyx_v_it); - p->__pyx_v_it = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_9__segmentrepr", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr, /*tp_traverse*/ - __pyx_tp_clear_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr[8]; -static int __pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr = 0; - -static PyObject *__pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr)))) { - o = (PyObject*)__pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr[--__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr]; - memset(o, 0, sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr(PyObject *o) { - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_outer_scope); - Py_CLEAR(p->__pyx_v_x); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr)))) { - __pyx_freelist_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr[__pyx_freecount_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr++] = ((struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *p = (struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr *)o; - if (p->__pyx_outer_scope) { - e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; - } - if (p->__pyx_v_x) { - e = (*v)(p->__pyx_v_x, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr = { - PyVarObject_HEAD_INIT(0, 0) - "fontTools.misc.bezierTools.__pyx_scope_struct_10_genexpr", /*tp_name*/ - sizeof(struct __pyx_obj_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr, /*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*/ - 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_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*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*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr, /*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 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {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_bezierTools(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec_bezierTools}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "bezierTools", - __pyx_k_fontTools_misc_bezierTools_py_to, /* 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_1_t, __pyx_k_1_t, sizeof(__pyx_k_1_t), 0, 0, 1, 1}, - {&__pyx_n_s_1_t_2, __pyx_k_1_t_2, sizeof(__pyx_k_1_t_2), 0, 0, 1, 1}, - {&__pyx_n_s_2_t_1_t, __pyx_k_2_t_1_t, sizeof(__pyx_k_2_t_1_t), 0, 0, 1, 1}, - {&__pyx_kp_u_Approximates_the_arc_length_for, __pyx_k_Approximates_the_arc_length_for, sizeof(__pyx_k_Approximates_the_arc_length_for), 0, 1, 0, 0}, - {&__pyx_n_s_AttributeError, __pyx_k_AttributeError, sizeof(__pyx_k_AttributeError), 0, 0, 1, 1}, - {&__pyx_n_s_COMPILED, __pyx_k_COMPILED, sizeof(__pyx_k_COMPILED), 0, 0, 1, 1}, - {&__pyx_kp_u_Calculates_the_arc_length_for_a, __pyx_k_Calculates_the_arc_length_for_a, sizeof(__pyx_k_Calculates_the_arc_length_for_a), 0, 1, 0, 0}, - {&__pyx_kp_u_Calculates_the_bounding_rectangl, __pyx_k_Calculates_the_bounding_rectangl, sizeof(__pyx_k_Calculates_the_bounding_rectangl), 0, 1, 0, 0}, - {&__pyx_kp_u_Calculates_the_bounding_rectangl_2, __pyx_k_Calculates_the_bounding_rectangl_2, sizeof(__pyx_k_Calculates_the_bounding_rectangl_2), 0, 1, 0, 0}, - {&__pyx_kp_u_Couldn_t_work_out_which_intersec, __pyx_k_Couldn_t_work_out_which_intersec, sizeof(__pyx_k_Couldn_t_work_out_which_intersec), 0, 1, 0, 0}, - {&__pyx_n_s_DD, __pyx_k_DD, sizeof(__pyx_k_DD), 0, 0, 1, 1}, - {&__pyx_kp_u_Finds_intersections_between_a_cu, __pyx_k_Finds_intersections_between_a_cu, sizeof(__pyx_k_Finds_intersections_between_a_cu), 0, 1, 0, 0}, - {&__pyx_kp_u_Finds_intersections_between_a_cu_2, __pyx_k_Finds_intersections_between_a_cu_2, sizeof(__pyx_k_Finds_intersections_between_a_cu_2), 0, 1, 0, 0}, - {&__pyx_kp_u_Finds_intersections_between_two, __pyx_k_Finds_intersections_between_two, sizeof(__pyx_k_Finds_intersections_between_two), 0, 1, 0, 0}, - {&__pyx_kp_u_Finds_intersections_between_two_2, __pyx_k_Finds_intersections_between_two_2, sizeof(__pyx_k_Finds_intersections_between_two_2), 0, 1, 0, 0}, - {&__pyx_n_s_Identity, __pyx_k_Identity, sizeof(__pyx_k_Identity), 0, 0, 1, 1}, - {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, - {&__pyx_n_s_Intersection, __pyx_k_Intersection, sizeof(__pyx_k_Intersection), 0, 0, 1, 1}, - {&__pyx_n_u_Intersection, __pyx_k_Intersection, sizeof(__pyx_k_Intersection), 0, 1, 0, 1}, - {&__pyx_n_s_Len, __pyx_k_Len, sizeof(__pyx_k_Len), 0, 0, 1, 1}, - {&__pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_k_Lib_fontTools_misc_bezierTools_p, sizeof(__pyx_k_Lib_fontTools_misc_bezierTools_p), 0, 0, 1, 0}, - {&__pyx_n_s_Q, __pyx_k_Q, sizeof(__pyx_k_Q), 0, 0, 1, 1}, - {&__pyx_n_s_Q3, __pyx_k_Q3, sizeof(__pyx_k_Q3), 0, 0, 1, 1}, - {&__pyx_n_s_R, __pyx_k_R, sizeof(__pyx_k_R), 0, 0, 1, 1}, - {&__pyx_n_s_R2, __pyx_k_R2, sizeof(__pyx_k_R2), 0, 0, 1, 1}, - {&__pyx_n_s_R2_Q3, __pyx_k_R2_Q3, sizeof(__pyx_k_R2_Q3), 0, 0, 1, 1}, - {&__pyx_kp_u_Solve_a_cubic_equation_Solves_a, __pyx_k_Solve_a_cubic_equation_Solves_a, sizeof(__pyx_k_Solve_a_cubic_equation_Solves_a), 0, 1, 0, 0}, - {&__pyx_kp_u_Split_a_cubic_Bezier_curve_at_a, __pyx_k_Split_a_cubic_Bezier_curve_at_a, sizeof(__pyx_k_Split_a_cubic_Bezier_curve_at_a), 0, 1, 0, 0}, - {&__pyx_kp_u_Split_a_cubic_Bezier_curve_at_on, __pyx_k_Split_a_cubic_Bezier_curve_at_on, sizeof(__pyx_k_Split_a_cubic_Bezier_curve_at_on), 0, 1, 0, 0}, - {&__pyx_kp_u_Split_a_line_at_a_given_coordina, __pyx_k_Split_a_line_at_a_given_coordina, sizeof(__pyx_k_Split_a_line_at_a_given_coordina), 0, 1, 0, 0}, - {&__pyx_kp_u_Split_a_quadratic_Bezier_curve_a, __pyx_k_Split_a_quadratic_Bezier_curve_a, sizeof(__pyx_k_Split_a_quadratic_Bezier_curve_a), 0, 1, 0, 0}, - {&__pyx_kp_u_Split_a_quadratic_Bezier_curve_a_2, __pyx_k_Split_a_quadratic_Bezier_curve_a_2, sizeof(__pyx_k_Split_a_quadratic_Bezier_curve_a_2), 0, 1, 0, 0}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_kp_u_Unknown_curve_degree, __pyx_k_Unknown_curve_degree, sizeof(__pyx_k_Unknown_curve_degree), 0, 1, 0, 0}, - {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, - {&__pyx_kp_u__9, __pyx_k__9, sizeof(__pyx_k__9), 0, 1, 0, 0}, - {&__pyx_n_s__91, __pyx_k__91, sizeof(__pyx_k__91), 0, 0, 1, 1}, - {&__pyx_n_s_a, __pyx_k_a, sizeof(__pyx_k_a), 0, 0, 1, 1}, - {&__pyx_n_s_a1, __pyx_k_a1, sizeof(__pyx_k_a1), 0, 0, 1, 1}, - {&__pyx_n_s_a1_3, __pyx_k_a1_3, sizeof(__pyx_k_a1_3), 0, 0, 1, 1}, - {&__pyx_n_s_a1x, __pyx_k_a1x, sizeof(__pyx_k_a1x), 0, 0, 1, 1}, - {&__pyx_n_s_a1y, __pyx_k_a1y, sizeof(__pyx_k_a1y), 0, 0, 1, 1}, - {&__pyx_n_s_a2, __pyx_k_a2, sizeof(__pyx_k_a2), 0, 0, 1, 1}, - {&__pyx_n_s_a3, __pyx_k_a3, sizeof(__pyx_k_a3), 0, 0, 1, 1}, - {&__pyx_n_s_acos, __pyx_k_acos, sizeof(__pyx_k_acos), 0, 0, 1, 1}, - {&__pyx_n_s_aligned_curve, __pyx_k_aligned_curve, sizeof(__pyx_k_aligned_curve), 0, 0, 1, 1}, - {&__pyx_n_s_alignment_transformation, __pyx_k_alignment_transformation, sizeof(__pyx_k_alignment_transformation), 0, 0, 1, 1}, - {&__pyx_n_s_all, __pyx_k_all, sizeof(__pyx_k_all), 0, 0, 1, 1}, - {&__pyx_n_s_angle, __pyx_k_angle, sizeof(__pyx_k_angle), 0, 0, 1, 1}, - {&__pyx_n_s_append, __pyx_k_append, sizeof(__pyx_k_append), 0, 0, 1, 1}, - {&__pyx_n_s_approximateCubicArcLength, __pyx_k_approximateCubicArcLength, sizeof(__pyx_k_approximateCubicArcLength), 0, 0, 1, 1}, - {&__pyx_n_u_approximateCubicArcLength, __pyx_k_approximateCubicArcLength, sizeof(__pyx_k_approximateCubicArcLength), 0, 1, 0, 1}, - {&__pyx_n_s_approximateCubicArcLengthC, __pyx_k_approximateCubicArcLengthC, sizeof(__pyx_k_approximateCubicArcLengthC), 0, 0, 1, 1}, - {&__pyx_n_u_approximateCubicArcLengthC, __pyx_k_approximateCubicArcLengthC, sizeof(__pyx_k_approximateCubicArcLengthC), 0, 1, 0, 1}, - {&__pyx_kp_u_approximateCubicArcLength_line_3, __pyx_k_approximateCubicArcLength_line_3, sizeof(__pyx_k_approximateCubicArcLength_line_3), 0, 1, 0, 0}, - {&__pyx_n_s_approximateQuadraticArcLength, __pyx_k_approximateQuadraticArcLength, sizeof(__pyx_k_approximateQuadraticArcLength), 0, 0, 1, 1}, - {&__pyx_n_u_approximateQuadraticArcLength, __pyx_k_approximateQuadraticArcLength, sizeof(__pyx_k_approximateQuadraticArcLength), 0, 1, 0, 1}, - {&__pyx_n_s_approximateQuadraticArcLengthC, __pyx_k_approximateQuadraticArcLengthC, sizeof(__pyx_k_approximateQuadraticArcLengthC), 0, 0, 1, 1}, - {&__pyx_n_u_approximateQuadraticArcLengthC, __pyx_k_approximateQuadraticArcLengthC, sizeof(__pyx_k_approximateQuadraticArcLengthC), 0, 1, 0, 1}, - {&__pyx_n_s_arch, __pyx_k_arch, sizeof(__pyx_k_arch), 0, 0, 1, 1}, - {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, - {&__pyx_n_s_asinh, __pyx_k_asinh, sizeof(__pyx_k_asinh), 0, 0, 1, 1}, - {&__pyx_n_s_atan2, __pyx_k_atan2, sizeof(__pyx_k_atan2), 0, 0, 1, 1}, - {&__pyx_n_s_ax, __pyx_k_ax, sizeof(__pyx_k_ax), 0, 0, 1, 1}, - {&__pyx_n_s_ax2, __pyx_k_ax2, sizeof(__pyx_k_ax2), 0, 0, 1, 1}, - {&__pyx_n_s_ax3, __pyx_k_ax3, sizeof(__pyx_k_ax3), 0, 0, 1, 1}, - {&__pyx_n_s_ay, __pyx_k_ay, sizeof(__pyx_k_ay), 0, 0, 1, 1}, - {&__pyx_n_s_ay2, __pyx_k_ay2, sizeof(__pyx_k_ay2), 0, 0, 1, 1}, - {&__pyx_n_s_ay3, __pyx_k_ay3, sizeof(__pyx_k_ay3), 0, 0, 1, 1}, - {&__pyx_n_s_b, __pyx_k_b, sizeof(__pyx_k_b), 0, 0, 1, 1}, - {&__pyx_n_s_b1, __pyx_k_b1, sizeof(__pyx_k_b1), 0, 0, 1, 1}, - {&__pyx_n_s_b1x, __pyx_k_b1x, sizeof(__pyx_k_b1x), 0, 0, 1, 1}, - {&__pyx_n_s_b1y, __pyx_k_b1y, sizeof(__pyx_k_b1y), 0, 0, 1, 1}, - {&__pyx_n_s_both_points_are_on_same_side_of, __pyx_k_both_points_are_on_same_side_of, sizeof(__pyx_k_both_points_are_on_same_side_of), 0, 0, 1, 1}, - {&__pyx_n_s_bounds1, __pyx_k_bounds1, sizeof(__pyx_k_bounds1), 0, 0, 1, 1}, - {&__pyx_n_s_bounds2, __pyx_k_bounds2, sizeof(__pyx_k_bounds2), 0, 0, 1, 1}, - {&__pyx_n_s_box, __pyx_k_box, sizeof(__pyx_k_box), 0, 0, 1, 1}, - {&__pyx_n_s_bx, __pyx_k_bx, sizeof(__pyx_k_bx), 0, 0, 1, 1}, - {&__pyx_n_s_bx2, __pyx_k_bx2, sizeof(__pyx_k_bx2), 0, 0, 1, 1}, - {&__pyx_n_s_by, __pyx_k_by, sizeof(__pyx_k_by), 0, 0, 1, 1}, - {&__pyx_n_s_by2, __pyx_k_by2, sizeof(__pyx_k_by2), 0, 0, 1, 1}, - {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, - {&__pyx_n_s_c1, __pyx_k_c1, sizeof(__pyx_k_c1), 0, 0, 1, 1}, - {&__pyx_n_s_c11, __pyx_k_c11, sizeof(__pyx_k_c11), 0, 0, 1, 1}, - {&__pyx_n_s_c11_range, __pyx_k_c11_range, sizeof(__pyx_k_c11_range), 0, 0, 1, 1}, - {&__pyx_n_s_c12, __pyx_k_c12, sizeof(__pyx_k_c12), 0, 0, 1, 1}, - {&__pyx_n_s_c12_range, __pyx_k_c12_range, sizeof(__pyx_k_c12_range), 0, 0, 1, 1}, - {&__pyx_n_s_c1x, __pyx_k_c1x, sizeof(__pyx_k_c1x), 0, 0, 1, 1}, - {&__pyx_n_s_c1y, __pyx_k_c1y, sizeof(__pyx_k_c1y), 0, 0, 1, 1}, - {&__pyx_n_s_c21, __pyx_k_c21, sizeof(__pyx_k_c21), 0, 0, 1, 1}, - {&__pyx_n_s_c21_range, __pyx_k_c21_range, sizeof(__pyx_k_c21_range), 0, 0, 1, 1}, - {&__pyx_n_s_c22, __pyx_k_c22, sizeof(__pyx_k_c22), 0, 0, 1, 1}, - {&__pyx_n_s_c22_range, __pyx_k_c22_range, sizeof(__pyx_k_c22_range), 0, 0, 1, 1}, - {&__pyx_n_s_calcBounds, __pyx_k_calcBounds, sizeof(__pyx_k_calcBounds), 0, 0, 1, 1}, - {&__pyx_n_s_calcCubicArcLength, __pyx_k_calcCubicArcLength, sizeof(__pyx_k_calcCubicArcLength), 0, 0, 1, 1}, - {&__pyx_n_u_calcCubicArcLength, __pyx_k_calcCubicArcLength, sizeof(__pyx_k_calcCubicArcLength), 0, 1, 0, 1}, - {&__pyx_n_s_calcCubicArcLengthC, __pyx_k_calcCubicArcLengthC, sizeof(__pyx_k_calcCubicArcLengthC), 0, 0, 1, 1}, - {&__pyx_n_u_calcCubicArcLengthC, __pyx_k_calcCubicArcLengthC, sizeof(__pyx_k_calcCubicArcLengthC), 0, 1, 0, 1}, - {&__pyx_n_s_calcCubicArcLengthCRecurse, __pyx_k_calcCubicArcLengthCRecurse, sizeof(__pyx_k_calcCubicArcLengthCRecurse), 0, 0, 1, 1}, - {&__pyx_n_s_calcCubicBounds, __pyx_k_calcCubicBounds, sizeof(__pyx_k_calcCubicBounds), 0, 0, 1, 1}, - {&__pyx_n_u_calcCubicBounds, __pyx_k_calcCubicBounds, sizeof(__pyx_k_calcCubicBounds), 0, 1, 0, 1}, - {&__pyx_kp_u_calcCubicBounds_line_412, __pyx_k_calcCubicBounds_line_412, sizeof(__pyx_k_calcCubicBounds_line_412), 0, 1, 0, 0}, - {&__pyx_n_s_calcCubicParameters, __pyx_k_calcCubicParameters, sizeof(__pyx_k_calcCubicParameters), 0, 0, 1, 1}, - {&__pyx_n_s_calcCubicPoints, __pyx_k_calcCubicPoints, sizeof(__pyx_k_calcCubicPoints), 0, 0, 1, 1}, - {&__pyx_n_s_calcQuadraticArcLength, __pyx_k_calcQuadraticArcLength, sizeof(__pyx_k_calcQuadraticArcLength), 0, 0, 1, 1}, - {&__pyx_n_u_calcQuadraticArcLength, __pyx_k_calcQuadraticArcLength, sizeof(__pyx_k_calcQuadraticArcLength), 0, 1, 0, 1}, - {&__pyx_n_s_calcQuadraticArcLengthC, __pyx_k_calcQuadraticArcLengthC, sizeof(__pyx_k_calcQuadraticArcLengthC), 0, 0, 1, 1}, - {&__pyx_n_u_calcQuadraticArcLengthC, __pyx_k_calcQuadraticArcLengthC, sizeof(__pyx_k_calcQuadraticArcLengthC), 0, 1, 0, 1}, - {&__pyx_kp_u_calcQuadraticArcLength_line_151, __pyx_k_calcQuadraticArcLength_line_151, sizeof(__pyx_k_calcQuadraticArcLength_line_151), 0, 1, 0, 0}, - {&__pyx_n_s_calcQuadraticBounds, __pyx_k_calcQuadraticBounds, sizeof(__pyx_k_calcQuadraticBounds), 0, 0, 1, 1}, - {&__pyx_n_u_calcQuadraticBounds, __pyx_k_calcQuadraticBounds, sizeof(__pyx_k_calcQuadraticBounds), 0, 1, 0, 1}, - {&__pyx_kp_u_calcQuadraticBounds_line_298, __pyx_k_calcQuadraticBounds_line_298, sizeof(__pyx_k_calcQuadraticBounds_line_298), 0, 1, 0, 0}, - {&__pyx_n_s_calcQuadraticParameters, __pyx_k_calcQuadraticParameters, sizeof(__pyx_k_calcQuadraticParameters), 0, 0, 1, 1}, - {&__pyx_n_s_calcQuadraticPoints, __pyx_k_calcQuadraticPoints, sizeof(__pyx_k_calcQuadraticPoints), 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_n_s_close, __pyx_k_close, sizeof(__pyx_k_close), 0, 0, 1, 1}, - {&__pyx_n_s_collections, __pyx_k_collections, sizeof(__pyx_k_collections), 0, 0, 1, 1}, - {&__pyx_n_s_cos, __pyx_k_cos, sizeof(__pyx_k_cos), 0, 0, 1, 1}, - {&__pyx_n_s_cubicPointAtT, __pyx_k_cubicPointAtT, sizeof(__pyx_k_cubicPointAtT), 0, 0, 1, 1}, - {&__pyx_n_u_cubicPointAtT, __pyx_k_cubicPointAtT, sizeof(__pyx_k_cubicPointAtT), 0, 1, 0, 1}, - {&__pyx_n_s_cubicPointAtTC, __pyx_k_cubicPointAtTC, sizeof(__pyx_k_cubicPointAtTC), 0, 0, 1, 1}, - {&__pyx_n_u_cubicPointAtTC, __pyx_k_cubicPointAtTC, sizeof(__pyx_k_cubicPointAtTC), 0, 1, 0, 1}, - {&__pyx_n_s_curve, __pyx_k_curve, sizeof(__pyx_k_curve), 0, 0, 1, 1}, - {&__pyx_n_s_curve1, __pyx_k_curve1, sizeof(__pyx_k_curve1), 0, 0, 1, 1}, - {&__pyx_n_s_curve2, __pyx_k_curve2, sizeof(__pyx_k_curve2), 0, 0, 1, 1}, - {&__pyx_n_s_curveCurveIntersections, __pyx_k_curveCurveIntersections, sizeof(__pyx_k_curveCurveIntersections), 0, 0, 1, 1}, - {&__pyx_n_u_curveCurveIntersections, __pyx_k_curveCurveIntersections, sizeof(__pyx_k_curveCurveIntersections), 0, 1, 0, 1}, - {&__pyx_kp_u_curveCurveIntersections_line_137, __pyx_k_curveCurveIntersections_line_137, sizeof(__pyx_k_curveCurveIntersections_line_137), 0, 1, 0, 0}, - {&__pyx_n_s_curveLineIntersections, __pyx_k_curveLineIntersections, sizeof(__pyx_k_curveLineIntersections), 0, 0, 1, 1}, - {&__pyx_n_u_curveLineIntersections, __pyx_k_curveLineIntersections, sizeof(__pyx_k_curveLineIntersections), 0, 1, 0, 1}, - {&__pyx_kp_u_curveLineIntersections_line_1248, __pyx_k_curveLineIntersections_line_1248, sizeof(__pyx_k_curveLineIntersections_line_1248), 0, 1, 0, 0}, - {&__pyx_n_s_curve_bounds, __pyx_k_curve_bounds, sizeof(__pyx_k_curve_bounds), 0, 0, 1, 1}, - {&__pyx_n_s_curve_curve_intersections_t, __pyx_k_curve_curve_intersections_t, sizeof(__pyx_k_curve_curve_intersections_t), 0, 0, 1, 1}, - {&__pyx_n_s_curve_curve_intersections_t_loc, __pyx_k_curve_curve_intersections_t_loc, sizeof(__pyx_k_curve_curve_intersections_t_loc), 0, 0, 1, 1}, - {&__pyx_n_s_curve_curve_intersections_t_loc_2, __pyx_k_curve_curve_intersections_t_loc_2, sizeof(__pyx_k_curve_curve_intersections_t_loc_2), 0, 0, 1, 1}, - {&__pyx_n_s_curve_line_intersections_t, __pyx_k_curve_line_intersections_t, sizeof(__pyx_k_curve_line_intersections_t), 0, 0, 1, 1}, - {&__pyx_n_s_curve_line_intersections_t_loca, __pyx_k_curve_line_intersections_t_loca, sizeof(__pyx_k_curve_line_intersections_t_loca), 0, 0, 1, 1}, - {&__pyx_n_s_cx, __pyx_k_cx, sizeof(__pyx_k_cx), 0, 0, 1, 1}, - {&__pyx_n_s_cy, __pyx_k_cy, sizeof(__pyx_k_cy), 0, 0, 1, 1}, - {&__pyx_n_s_cython, __pyx_k_cython, sizeof(__pyx_k_cython), 0, 0, 1, 1}, - {&__pyx_n_s_d, __pyx_k_d, sizeof(__pyx_k_d), 0, 0, 1, 1}, - {&__pyx_n_s_d0, __pyx_k_d0, sizeof(__pyx_k_d0), 0, 0, 1, 1}, - {&__pyx_n_s_d1, __pyx_k_d1, sizeof(__pyx_k_d1), 0, 0, 1, 1}, - {&__pyx_n_s_d1x, __pyx_k_d1x, sizeof(__pyx_k_d1x), 0, 0, 1, 1}, - {&__pyx_n_s_d1y, __pyx_k_d1y, sizeof(__pyx_k_d1y), 0, 0, 1, 1}, - {&__pyx_n_s_delta, __pyx_k_delta, sizeof(__pyx_k_delta), 0, 0, 1, 1}, - {&__pyx_n_s_delta_2, __pyx_k_delta_2, sizeof(__pyx_k_delta_2), 0, 0, 1, 1}, - {&__pyx_n_s_delta_3, __pyx_k_delta_3, sizeof(__pyx_k_delta_3), 0, 0, 1, 1}, - {&__pyx_n_s_deriv3, __pyx_k_deriv3, sizeof(__pyx_k_deriv3), 0, 0, 1, 1}, - {&__pyx_n_s_doctest, __pyx_k_doctest, sizeof(__pyx_k_doctest), 0, 0, 1, 1}, - {&__pyx_n_s_dx, __pyx_k_dx, sizeof(__pyx_k_dx), 0, 0, 1, 1}, - {&__pyx_n_s_dy, __pyx_k_dy, sizeof(__pyx_k_dy), 0, 0, 1, 1}, - {&__pyx_n_s_e, __pyx_k_e, sizeof(__pyx_k_e), 0, 0, 1, 1}, - {&__pyx_n_s_e1, __pyx_k_e1, sizeof(__pyx_k_e1), 0, 0, 1, 1}, - {&__pyx_n_s_e1x, __pyx_k_e1x, sizeof(__pyx_k_e1x), 0, 0, 1, 1}, - {&__pyx_n_s_e1y, __pyx_k_e1y, sizeof(__pyx_k_e1y), 0, 0, 1, 1}, - {&__pyx_n_s_e2, __pyx_k_e2, sizeof(__pyx_k_e2), 0, 0, 1, 1}, - {&__pyx_n_s_e2x, __pyx_k_e2x, sizeof(__pyx_k_e2x), 0, 0, 1, 1}, - {&__pyx_n_s_e2y, __pyx_k_e2y, sizeof(__pyx_k_e2y), 0, 0, 1, 1}, - {&__pyx_n_s_end, __pyx_k_end, sizeof(__pyx_k_end), 0, 0, 1, 1}, - {&__pyx_n_s_epsilon, __pyx_k_epsilon, sizeof(__pyx_k_epsilon), 0, 0, 1, 1}, - {&__pyx_n_s_epsilonDigits, __pyx_k_epsilonDigits, sizeof(__pyx_k_epsilonDigits), 0, 0, 1, 1}, - {&__pyx_n_s_ex, __pyx_k_ex, sizeof(__pyx_k_ex), 0, 0, 1, 1}, - {&__pyx_n_s_exit, __pyx_k_exit, sizeof(__pyx_k_exit), 0, 0, 1, 1}, - {&__pyx_n_s_ey, __pyx_k_ey, sizeof(__pyx_k_ey), 0, 0, 1, 1}, - {&__pyx_n_s_failed, __pyx_k_failed, sizeof(__pyx_k_failed), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_misc, __pyx_k_fontTools_misc, sizeof(__pyx_k_fontTools_misc), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_misc_arrayTools, __pyx_k_fontTools_misc_arrayTools, sizeof(__pyx_k_fontTools_misc_arrayTools), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_misc_bezierTools, __pyx_k_fontTools_misc_bezierTools, sizeof(__pyx_k_fontTools_misc_bezierTools), 0, 0, 1, 1}, - {&__pyx_n_s_fontTools_misc_transform, __pyx_k_fontTools_misc_transform, sizeof(__pyx_k_fontTools_misc_transform), 0, 0, 1, 1}, - {&__pyx_n_s_found, __pyx_k_found, sizeof(__pyx_k_found), 0, 0, 1, 1}, - {&__pyx_kp_u_g, __pyx_k_g, sizeof(__pyx_k_g), 0, 1, 0, 0}, - {&__pyx_n_s_genexpr, __pyx_k_genexpr, sizeof(__pyx_k_genexpr), 0, 0, 1, 1}, - {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_insert, __pyx_k_insert, sizeof(__pyx_k_insert), 0, 0, 1, 1}, - {&__pyx_n_s_intersection_ts, __pyx_k_intersection_ts, sizeof(__pyx_k_intersection_ts), 0, 0, 1, 1}, - {&__pyx_n_s_intersections, __pyx_k_intersections, sizeof(__pyx_k_intersections), 0, 0, 1, 1}, - {&__pyx_n_s_intersects, __pyx_k_intersects, sizeof(__pyx_k_intersects), 0, 0, 1, 1}, - {&__pyx_n_s_isHorizontal, __pyx_k_isHorizontal, sizeof(__pyx_k_isHorizontal), 0, 0, 1, 1}, - {&__pyx_n_s_isclose, __pyx_k_isclose, sizeof(__pyx_k_isclose), 0, 0, 1, 1}, - {&__pyx_n_s_it, __pyx_k_it, sizeof(__pyx_k_it), 0, 0, 1, 1}, - {&__pyx_n_s_key, __pyx_k_key, sizeof(__pyx_k_key), 0, 0, 1, 1}, - {&__pyx_n_s_line, __pyx_k_line, sizeof(__pyx_k_line), 0, 0, 1, 1}, - {&__pyx_n_s_lineLineIntersections, __pyx_k_lineLineIntersections, sizeof(__pyx_k_lineLineIntersections), 0, 0, 1, 1}, - {&__pyx_n_u_lineLineIntersections, __pyx_k_lineLineIntersections, sizeof(__pyx_k_lineLineIntersections), 0, 1, 0, 1}, - {&__pyx_kp_u_lineLineIntersections_line_1147, __pyx_k_lineLineIntersections_line_1147, sizeof(__pyx_k_lineLineIntersections_line_1147), 0, 1, 0, 0}, - {&__pyx_n_s_linePointAtT, __pyx_k_linePointAtT, sizeof(__pyx_k_linePointAtT), 0, 0, 1, 1}, - {&__pyx_n_u_linePointAtT, __pyx_k_linePointAtT, sizeof(__pyx_k_linePointAtT), 0, 1, 0, 1}, - {&__pyx_n_s_line_t, __pyx_k_line_t, sizeof(__pyx_k_line_t), 0, 0, 1, 1}, - {&__pyx_n_s_line_t_of_pt, __pyx_k_line_t_of_pt, sizeof(__pyx_k_line_t_of_pt), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_u_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 1, 0, 1}, - {&__pyx_n_s_math, __pyx_k_math, sizeof(__pyx_k_math), 0, 0, 1, 1}, - {&__pyx_n_s_mid, __pyx_k_mid, sizeof(__pyx_k_mid), 0, 0, 1, 1}, - {&__pyx_n_s_midPt, __pyx_k_midPt, sizeof(__pyx_k_midPt), 0, 0, 1, 1}, - {&__pyx_n_s_midpoint, __pyx_k_midpoint, sizeof(__pyx_k_midpoint), 0, 0, 1, 1}, - {&__pyx_n_s_mult, __pyx_k_mult, sizeof(__pyx_k_mult), 0, 0, 1, 1}, - {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_namedtuple, __pyx_k_namedtuple, sizeof(__pyx_k_namedtuple), 0, 0, 1, 1}, - {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, - {&__pyx_n_s_off1, __pyx_k_off1, sizeof(__pyx_k_off1), 0, 0, 1, 1}, - {&__pyx_n_s_off2, __pyx_k_off2, sizeof(__pyx_k_off2), 0, 0, 1, 1}, - {&__pyx_n_s_one, __pyx_k_one, sizeof(__pyx_k_one), 0, 0, 1, 1}, - {&__pyx_n_s_origDist, __pyx_k_origDist, sizeof(__pyx_k_origDist), 0, 0, 1, 1}, - {&__pyx_n_s_origin, __pyx_k_origin, sizeof(__pyx_k_origin), 0, 0, 1, 1}, - {&__pyx_n_s_p0, __pyx_k_p0, sizeof(__pyx_k_p0), 0, 0, 1, 1}, - {&__pyx_n_s_p1, __pyx_k_p1, sizeof(__pyx_k_p1), 0, 0, 1, 1}, - {&__pyx_n_s_p2, __pyx_k_p2, sizeof(__pyx_k_p2), 0, 0, 1, 1}, - {&__pyx_n_s_p3, __pyx_k_p3, sizeof(__pyx_k_p3), 0, 0, 1, 1}, - {&__pyx_n_s_pi, __pyx_k_pi, sizeof(__pyx_k_pi), 0, 0, 1, 1}, - {&__pyx_n_s_pointAtT, __pyx_k_pointAtT, sizeof(__pyx_k_pointAtT), 0, 0, 1, 1}, - {&__pyx_n_s_pointFinder, __pyx_k_pointFinder, sizeof(__pyx_k_pointFinder), 0, 0, 1, 1}, - {&__pyx_n_s_points, __pyx_k_points, sizeof(__pyx_k_points), 0, 0, 1, 1}, - {&__pyx_n_s_precision, __pyx_k_precision, sizeof(__pyx_k_precision), 0, 0, 1, 1}, - {&__pyx_n_s_print, __pyx_k_print, sizeof(__pyx_k_print), 0, 0, 1, 1}, - {&__pyx_n_s_printSegments, __pyx_k_printSegments, sizeof(__pyx_k_printSegments), 0, 0, 1, 1}, - {&__pyx_n_s_pt, __pyx_k_pt, sizeof(__pyx_k_pt), 0, 0, 1, 1}, - {&__pyx_n_u_pt, __pyx_k_pt, sizeof(__pyx_k_pt), 0, 1, 0, 1}, - {&__pyx_n_s_pt1, __pyx_k_pt1, sizeof(__pyx_k_pt1), 0, 0, 1, 1}, - {&__pyx_n_s_pt1x, __pyx_k_pt1x, sizeof(__pyx_k_pt1x), 0, 0, 1, 1}, - {&__pyx_n_s_pt1y, __pyx_k_pt1y, sizeof(__pyx_k_pt1y), 0, 0, 1, 1}, - {&__pyx_n_s_pt2, __pyx_k_pt2, sizeof(__pyx_k_pt2), 0, 0, 1, 1}, - {&__pyx_n_s_pt2x, __pyx_k_pt2x, sizeof(__pyx_k_pt2x), 0, 0, 1, 1}, - {&__pyx_n_s_pt2y, __pyx_k_pt2y, sizeof(__pyx_k_pt2y), 0, 0, 1, 1}, - {&__pyx_n_s_pt3, __pyx_k_pt3, sizeof(__pyx_k_pt3), 0, 0, 1, 1}, - {&__pyx_n_s_pt4, __pyx_k_pt4, sizeof(__pyx_k_pt4), 0, 0, 1, 1}, - {&__pyx_n_s_px, __pyx_k_px, sizeof(__pyx_k_px), 0, 0, 1, 1}, - {&__pyx_n_s_py, __pyx_k_py, sizeof(__pyx_k_py), 0, 0, 1, 1}, - {&__pyx_n_s_quadraticPointAtT, __pyx_k_quadraticPointAtT, sizeof(__pyx_k_quadraticPointAtT), 0, 0, 1, 1}, - {&__pyx_n_u_quadraticPointAtT, __pyx_k_quadraticPointAtT, sizeof(__pyx_k_quadraticPointAtT), 0, 1, 0, 1}, - {&__pyx_n_s_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 0, 1, 1}, - {&__pyx_n_s_rDD, __pyx_k_rDD, sizeof(__pyx_k_rDD), 0, 0, 1, 1}, - {&__pyx_n_s_rQ2, __pyx_k_rQ2, sizeof(__pyx_k_rQ2), 0, 0, 1, 1}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_range1, __pyx_k_range1, sizeof(__pyx_k_range1), 0, 0, 1, 1}, - {&__pyx_n_s_range2, __pyx_k_range2, sizeof(__pyx_k_range2), 0, 0, 1, 1}, - {&__pyx_n_s_rectArea, __pyx_k_rectArea, sizeof(__pyx_k_rectArea), 0, 0, 1, 1}, - {&__pyx_n_s_roots, __pyx_k_roots, sizeof(__pyx_k_roots), 0, 0, 1, 1}, - {&__pyx_n_s_rotate, __pyx_k_rotate, sizeof(__pyx_k_rotate), 0, 0, 1, 1}, - {&__pyx_n_s_round, __pyx_k_round, sizeof(__pyx_k_round), 0, 0, 1, 1}, - {&__pyx_n_s_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 0, 1, 1}, - {&__pyx_n_s_s1, __pyx_k_s1, sizeof(__pyx_k_s1), 0, 0, 1, 1}, - {&__pyx_n_s_s1x, __pyx_k_s1x, sizeof(__pyx_k_s1x), 0, 0, 1, 1}, - {&__pyx_n_s_s1y, __pyx_k_s1y, sizeof(__pyx_k_s1y), 0, 0, 1, 1}, - {&__pyx_n_s_s2, __pyx_k_s2, sizeof(__pyx_k_s2), 0, 0, 1, 1}, - {&__pyx_n_s_s2x, __pyx_k_s2x, sizeof(__pyx_k_s2x), 0, 0, 1, 1}, - {&__pyx_n_s_s2y, __pyx_k_s2y, sizeof(__pyx_k_s2y), 0, 0, 1, 1}, - {&__pyx_kp_u_s_2, __pyx_k_s_2, sizeof(__pyx_k_s_2), 0, 1, 0, 0}, - {&__pyx_n_s_scale, __pyx_k_scale, sizeof(__pyx_k_scale), 0, 0, 1, 1}, - {&__pyx_n_s_sectRect, __pyx_k_sectRect, sizeof(__pyx_k_sectRect), 0, 0, 1, 1}, - {&__pyx_n_s_seen, __pyx_k_seen, sizeof(__pyx_k_seen), 0, 0, 1, 1}, - {&__pyx_n_s_seg, __pyx_k_seg, sizeof(__pyx_k_seg), 0, 0, 1, 1}, - {&__pyx_n_s_seg1, __pyx_k_seg1, sizeof(__pyx_k_seg1), 0, 0, 1, 1}, - {&__pyx_n_s_seg2, __pyx_k_seg2, sizeof(__pyx_k_seg2), 0, 0, 1, 1}, - {&__pyx_n_s_segment, __pyx_k_segment, sizeof(__pyx_k_segment), 0, 0, 1, 1}, - {&__pyx_n_s_segmentPointAtT, __pyx_k_segmentPointAtT, sizeof(__pyx_k_segmentPointAtT), 0, 0, 1, 1}, - {&__pyx_n_u_segmentPointAtT, __pyx_k_segmentPointAtT, sizeof(__pyx_k_segmentPointAtT), 0, 1, 0, 1}, - {&__pyx_n_s_segmentSegmentIntersections, __pyx_k_segmentSegmentIntersections, sizeof(__pyx_k_segmentSegmentIntersections), 0, 0, 1, 1}, - {&__pyx_n_u_segmentSegmentIntersections, __pyx_k_segmentSegmentIntersections, sizeof(__pyx_k_segmentSegmentIntersections), 0, 1, 0, 1}, - {&__pyx_kp_u_segmentSegmentIntersections_line, __pyx_k_segmentSegmentIntersections_line, sizeof(__pyx_k_segmentSegmentIntersections_line), 0, 1, 0, 0}, - {&__pyx_n_s_segmentrepr, __pyx_k_segmentrepr, sizeof(__pyx_k_segmentrepr), 0, 0, 1, 1}, - {&__pyx_kp_u_segmentrepr_1_2_3_2_3_4_0_1_2, __pyx_k_segmentrepr_1_2_3_2_3_4_0_1_2, sizeof(__pyx_k_segmentrepr_1_2_3_2_3_4_0_1_2), 0, 1, 0, 0}, - {&__pyx_kp_u_segmentrepr_line_1449, __pyx_k_segmentrepr_line_1449, sizeof(__pyx_k_segmentrepr_line_1449), 0, 1, 0, 0}, - {&__pyx_n_s_segmentrepr_locals_genexpr, __pyx_k_segmentrepr_locals_genexpr, sizeof(__pyx_k_segmentrepr_locals_genexpr), 0, 0, 1, 1}, - {&__pyx_n_s_segments, __pyx_k_segments, sizeof(__pyx_k_segments), 0, 0, 1, 1}, - {&__pyx_n_s_send, __pyx_k_send, sizeof(__pyx_k_send), 0, 0, 1, 1}, - {&__pyx_n_s_slope12, __pyx_k_slope12, sizeof(__pyx_k_slope12), 0, 0, 1, 1}, - {&__pyx_n_s_slope34, __pyx_k_slope34, sizeof(__pyx_k_slope34), 0, 0, 1, 1}, - {&__pyx_n_s_solutions, __pyx_k_solutions, sizeof(__pyx_k_solutions), 0, 0, 1, 1}, - {&__pyx_n_s_solveCubic, __pyx_k_solveCubic, sizeof(__pyx_k_solveCubic), 0, 0, 1, 1}, - {&__pyx_n_u_solveCubic, __pyx_k_solveCubic, sizeof(__pyx_k_solveCubic), 0, 1, 0, 1}, - {&__pyx_kp_u_solveCubic_line_841, __pyx_k_solveCubic_line_841, sizeof(__pyx_k_solveCubic_line_841), 0, 1, 0, 0}, - {&__pyx_n_s_solveQuadratic, __pyx_k_solveQuadratic, sizeof(__pyx_k_solveQuadratic), 0, 0, 1, 1}, - {&__pyx_n_u_solveQuadratic, __pyx_k_solveQuadratic, sizeof(__pyx_k_solveQuadratic), 0, 1, 0, 1}, - {&__pyx_n_s_splitCubic, __pyx_k_splitCubic, sizeof(__pyx_k_splitCubic), 0, 0, 1, 1}, - {&__pyx_n_u_splitCubic, __pyx_k_splitCubic, sizeof(__pyx_k_splitCubic), 0, 1, 0, 1}, - {&__pyx_n_s_splitCubicAtT, __pyx_k_splitCubicAtT, sizeof(__pyx_k_splitCubicAtT), 0, 0, 1, 1}, - {&__pyx_n_s_splitCubicAtTC, __pyx_k_splitCubicAtTC, sizeof(__pyx_k_splitCubicAtTC), 0, 0, 1, 1}, - {&__pyx_n_u_splitCubicAtTC, __pyx_k_splitCubicAtTC, sizeof(__pyx_k_splitCubicAtTC), 0, 1, 0, 1}, - {&__pyx_n_s_splitCubicAtTC_2, __pyx_k_splitCubicAtTC_2, sizeof(__pyx_k_splitCubicAtTC_2), 0, 0, 1, 1}, - {&__pyx_n_s_splitCubicAtT_2, __pyx_k_splitCubicAtT_2, sizeof(__pyx_k_splitCubicAtT_2), 0, 0, 1, 1}, - {&__pyx_n_u_splitCubicAtT_2, __pyx_k_splitCubicAtT_2, sizeof(__pyx_k_splitCubicAtT_2), 0, 1, 0, 1}, - {&__pyx_kp_u_splitCubicAtT_line_613, __pyx_k_splitCubicAtT_line_613, sizeof(__pyx_k_splitCubicAtT_line_613), 0, 1, 0, 0}, - {&__pyx_n_s_splitCubicIntoTwoAtTC, __pyx_k_splitCubicIntoTwoAtTC, sizeof(__pyx_k_splitCubicIntoTwoAtTC), 0, 0, 1, 1}, - {&__pyx_n_u_splitCubicIntoTwoAtTC, __pyx_k_splitCubicIntoTwoAtTC, sizeof(__pyx_k_splitCubicIntoTwoAtTC), 0, 1, 0, 1}, - {&__pyx_kp_u_splitCubic_line_552, __pyx_k_splitCubic_line_552, sizeof(__pyx_k_splitCubic_line_552), 0, 1, 0, 0}, - {&__pyx_n_s_splitCubic_locals_genexpr, __pyx_k_splitCubic_locals_genexpr, sizeof(__pyx_k_splitCubic_locals_genexpr), 0, 0, 1, 1}, - {&__pyx_n_s_splitLine, __pyx_k_splitLine, sizeof(__pyx_k_splitLine), 0, 0, 1, 1}, - {&__pyx_n_u_splitLine, __pyx_k_splitLine, sizeof(__pyx_k_splitLine), 0, 1, 0, 1}, - {&__pyx_kp_u_splitLine_line_450, __pyx_k_splitLine_line_450, sizeof(__pyx_k_splitLine_line_450), 0, 1, 0, 0}, - {&__pyx_n_s_splitQuadratic, __pyx_k_splitQuadratic, sizeof(__pyx_k_splitQuadratic), 0, 0, 1, 1}, - {&__pyx_n_u_splitQuadratic, __pyx_k_splitQuadratic, sizeof(__pyx_k_splitQuadratic), 0, 1, 0, 1}, - {&__pyx_n_s_splitQuadraticAtT, __pyx_k_splitQuadraticAtT, sizeof(__pyx_k_splitQuadraticAtT), 0, 0, 1, 1}, - {&__pyx_n_s_splitQuadraticAtT_2, __pyx_k_splitQuadraticAtT_2, sizeof(__pyx_k_splitQuadraticAtT_2), 0, 0, 1, 1}, - {&__pyx_n_u_splitQuadraticAtT_2, __pyx_k_splitQuadraticAtT_2, sizeof(__pyx_k_splitQuadraticAtT_2), 0, 1, 0, 1}, - {&__pyx_kp_u_splitQuadraticAtT_line_589, __pyx_k_splitQuadraticAtT_line_589, sizeof(__pyx_k_splitQuadraticAtT_line_589), 0, 1, 0, 0}, - {&__pyx_kp_u_splitQuadratic_line_507, __pyx_k_splitQuadratic_line_507, sizeof(__pyx_k_splitQuadratic_line_507), 0, 1, 0, 0}, - {&__pyx_n_s_splitQuadratic_locals_genexpr, __pyx_k_splitQuadratic_locals_genexpr, sizeof(__pyx_k_splitQuadratic_locals_genexpr), 0, 0, 1, 1}, - {&__pyx_n_s_split_cubic_into_two, __pyx_k_split_cubic_into_two, sizeof(__pyx_k_split_cubic_into_two), 0, 0, 1, 1}, - {&__pyx_n_s_split_segment_at_t, __pyx_k_split_segment_at_t, sizeof(__pyx_k_split_segment_at_t), 0, 0, 1, 1}, - {&__pyx_n_s_sqrt, __pyx_k_sqrt, sizeof(__pyx_k_sqrt), 0, 0, 1, 1}, - {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, - {&__pyx_n_s_swapped, __pyx_k_swapped, sizeof(__pyx_k_swapped), 0, 0, 1, 1}, - {&__pyx_n_s_sx, __pyx_k_sx, sizeof(__pyx_k_sx), 0, 0, 1, 1}, - {&__pyx_n_s_sy, __pyx_k_sy, sizeof(__pyx_k_sy), 0, 0, 1, 1}, - {&__pyx_n_s_sys, __pyx_k_sys, sizeof(__pyx_k_sys), 0, 0, 1, 1}, - {&__pyx_n_s_t, __pyx_k_t, sizeof(__pyx_k_t), 0, 0, 1, 1}, - {&__pyx_n_s_t1, __pyx_k_t1, sizeof(__pyx_k_t1), 0, 0, 1, 1}, - {&__pyx_n_u_t1, __pyx_k_t1, sizeof(__pyx_k_t1), 0, 1, 0, 1}, - {&__pyx_n_s_t1_2, __pyx_k_t1_2, sizeof(__pyx_k_t1_2), 0, 0, 1, 1}, - {&__pyx_n_s_t1_3, __pyx_k_t1_3, sizeof(__pyx_k_t1_3), 0, 0, 1, 1}, - {&__pyx_n_s_t2, __pyx_k_t2, sizeof(__pyx_k_t2), 0, 0, 1, 1}, - {&__pyx_n_u_t2, __pyx_k_t2, sizeof(__pyx_k_t2), 0, 1, 0, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_testmod, __pyx_k_testmod, sizeof(__pyx_k_testmod), 0, 0, 1, 1}, - {&__pyx_n_s_theta, __pyx_k_theta, sizeof(__pyx_k_theta), 0, 0, 1, 1}, - {&__pyx_n_s_throw, __pyx_k_throw, sizeof(__pyx_k_throw), 0, 0, 1, 1}, - {&__pyx_n_s_tolerance, __pyx_k_tolerance, sizeof(__pyx_k_tolerance), 0, 0, 1, 1}, - {&__pyx_n_s_transformPoints, __pyx_k_transformPoints, sizeof(__pyx_k_transformPoints), 0, 0, 1, 1}, - {&__pyx_n_s_translate, __pyx_k_translate, sizeof(__pyx_k_translate), 0, 0, 1, 1}, - {&__pyx_n_s_ts, __pyx_k_ts, sizeof(__pyx_k_ts), 0, 0, 1, 1}, - {&__pyx_n_s_two, __pyx_k_two, sizeof(__pyx_k_two), 0, 0, 1, 1}, - {&__pyx_n_s_unique_key, __pyx_k_unique_key, sizeof(__pyx_k_unique_key), 0, 0, 1, 1}, - {&__pyx_n_s_unique_values, __pyx_k_unique_values, sizeof(__pyx_k_unique_values), 0, 0, 1, 1}, - {&__pyx_n_s_v0, __pyx_k_v0, sizeof(__pyx_k_v0), 0, 0, 1, 1}, - {&__pyx_n_s_v1, __pyx_k_v1, sizeof(__pyx_k_v1), 0, 0, 1, 1}, - {&__pyx_n_s_v2, __pyx_k_v2, sizeof(__pyx_k_v2), 0, 0, 1, 1}, - {&__pyx_n_s_v3, __pyx_k_v3, sizeof(__pyx_k_v3), 0, 0, 1, 1}, - {&__pyx_n_s_v4, __pyx_k_v4, sizeof(__pyx_k_v4), 0, 0, 1, 1}, - {&__pyx_n_s_where, __pyx_k_where, sizeof(__pyx_k_where), 0, 0, 1, 1}, - {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, - {&__pyx_n_s_x0, __pyx_k_x0, sizeof(__pyx_k_x0), 0, 0, 1, 1}, - {&__pyx_n_s_x1, __pyx_k_x1, sizeof(__pyx_k_x1), 0, 0, 1, 1}, - {&__pyx_n_s_x2, __pyx_k_x2, sizeof(__pyx_k_x2), 0, 0, 1, 1}, - {&__pyx_n_s_x3, __pyx_k_x3, sizeof(__pyx_k_x3), 0, 0, 1, 1}, - {&__pyx_n_s_x4, __pyx_k_x4, sizeof(__pyx_k_x4), 0, 0, 1, 1}, - {&__pyx_n_s_xDiff, __pyx_k_xDiff, sizeof(__pyx_k_xDiff), 0, 0, 1, 1}, - {&__pyx_n_s_xRoots, __pyx_k_xRoots, sizeof(__pyx_k_xRoots), 0, 0, 1, 1}, - {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, - {&__pyx_n_s_y1, __pyx_k_y1, sizeof(__pyx_k_y1), 0, 0, 1, 1}, - {&__pyx_n_s_y2, __pyx_k_y2, sizeof(__pyx_k_y2), 0, 0, 1, 1}, - {&__pyx_n_s_y3, __pyx_k_y3, sizeof(__pyx_k_y3), 0, 0, 1, 1}, - {&__pyx_n_s_y4, __pyx_k_y4, sizeof(__pyx_k_y4), 0, 0, 1, 1}, - {&__pyx_n_s_yDiff, __pyx_k_yDiff, sizeof(__pyx_k_yDiff), 0, 0, 1, 1}, - {&__pyx_n_s_yRoots, __pyx_k_yRoots, sizeof(__pyx_k_yRoots), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_AttributeError = __Pyx_GetBuiltinName(__pyx_n_s_AttributeError); if (!__pyx_builtin_AttributeError) __PYX_ERR(0, 14, __pyx_L1_error) - __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(0, 14, __pyx_L1_error) - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 709, __pyx_L1_error) - __pyx_builtin_round = __Pyx_GetBuiltinName(__pyx_n_s_round); if (!__pyx_builtin_round) __PYX_ERR(0, 899, __pyx_L1_error) - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 1119, __pyx_L1_error) - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(0, 1456, __pyx_L1_error) - __pyx_builtin_print = __Pyx_GetBuiltinName(__pyx_n_s_print); if (!__pyx_builtin_print) __PYX_ERR(0, 1467, __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); - - /* "fontTools/misc/bezierTools.py":704 - * ts = list(ts) - * segments = [] - * ts.insert(0, 0.0) # <<<<<<<<<<<<<< - * ts.append(1.0) - * ax, ay = a - */ - __pyx_tuple__2 = PyTuple_Pack(2, __pyx_int_0, __pyx_float_0_0); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(0, 704, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - - /* "fontTools/misc/bezierTools.py":1119 - * elif len(seg) == 4: - * return cubicPointAtT(*seg, t) - * raise ValueError("Unknown curve degree") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Unknown_curve_degree); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 1119, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - - /* "fontTools/misc/bezierTools.py":1313 - * - * if not range1: - * range1 = (0.0, 1.0) # <<<<<<<<<<<<<< - * if not range2: - * range2 = (0.0, 1.0) - */ - __pyx_tuple__5 = PyTuple_Pack(2, __pyx_float_0_0, __pyx_float_1_0); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(0, 1313, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "fontTools/misc/bezierTools.py":1322 - * return [] - * - * def midpoint(r): # <<<<<<<<<<<<<< - * return 0.5 * (r[0] + r[1]) - * - */ - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_n_s_r); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(0, 1322, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - __pyx_codeobj__7 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__6, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_midpoint, 1322, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__7)) __PYX_ERR(0, 1322, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1443 - * intersections = lineLineIntersections(*seg1, *seg2) - * else: - * raise ValueError("Couldn't work out which intersection function to use") # <<<<<<<<<<<<<< - * if not swapped: - * return intersections - */ - __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_Couldn_t_work_out_which_intersec); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 1443, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - - /* "fontTools/misc/bezierTools.py":56 - * - * - * def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - __pyx_tuple__10 = PyTuple_Pack(5, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_tolerance); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(5, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcCubicArcLength, 56, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 56, __pyx_L1_error) - __pyx_tuple__12 = PyTuple_Pack(1, ((PyObject*)__pyx_float_0_005)); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); - - /* "fontTools/misc/bezierTools.py":75 - * - * - * def _split_cubic_into_two(p0, p1, p2, p3): # <<<<<<<<<<<<<< - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - */ - __pyx_tuple__13 = PyTuple_Pack(6, __pyx_n_s_p0, __pyx_n_s_p1, __pyx_n_s_p2, __pyx_n_s_p3, __pyx_n_s_mid, __pyx_n_s_deriv3); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(0, 75, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_GIVEREF(__pyx_tuple__13); - __pyx_codeobj__14 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_split_cubic_into_two, 75, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__14)) __PYX_ERR(0, 75, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":92 - * ) - * @cython.locals(mult=cython.double, arch=cython.double, box=cython.double) - * def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3): # <<<<<<<<<<<<<< - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - */ - __pyx_tuple__15 = PyTuple_Pack(9, __pyx_n_s_mult, __pyx_n_s_p0, __pyx_n_s_p1, __pyx_n_s_p2, __pyx_n_s_p3, __pyx_n_s_arch, __pyx_n_s_box, __pyx_n_s_one, __pyx_n_s_two); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__15); - __Pyx_GIVEREF(__pyx_tuple__15); - __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(5, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcCubicArcLengthCRecurse, 92, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) __PYX_ERR(0, 92, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":115 - * mult=cython.double, - * ) - * def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - __pyx_tuple__17 = PyTuple_Pack(6, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_tolerance, __pyx_n_s_mult); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__17); - __Pyx_GIVEREF(__pyx_tuple__17); - __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(5, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcCubicArcLengthC, 115, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) __PYX_ERR(0, 115, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":151 - * - * - * def calcQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_tuple__19 = PyTuple_Pack(3, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(0, 151, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__19); - __Pyx_GIVEREF(__pyx_tuple__19); - __pyx_codeobj__20 = (PyObject*)__Pyx_PyCode_New(3, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcQuadraticArcLength, 151, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) __PYX_ERR(0, 151, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":205 - * Len=cython.double, - * ) - * def calcQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_tuple__21 = PyTuple_Pack(14, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_scale, __pyx_n_s_origDist, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_x0, __pyx_n_s_x1, __pyx_n_s_Len, __pyx_n_s_d0, __pyx_n_s_d1, __pyx_n_s_d, __pyx_n_s_n); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(0, 205, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); - __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(3, 0, 14, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__21, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcQuadraticArcLengthC, 205, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) __PYX_ERR(0, 205, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":237 - * - * - * def approximateQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_tuple__23 = PyTuple_Pack(3, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(0, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__23); - __Pyx_GIVEREF(__pyx_tuple__23); - __pyx_codeobj__24 = (PyObject*)__Pyx_PyCode_New(3, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__23, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_approximateQuadraticArcLength, 237, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__24)) __PYX_ERR(0, 237, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":265 - * v2=cython.double, - * ) - * def approximateQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_tuple__25 = PyTuple_Pack(6, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_v0, __pyx_n_s_v1, __pyx_n_s_v2); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(0, 265, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__25); - __Pyx_GIVEREF(__pyx_tuple__25); - __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(3, 0, 6, 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_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_approximateQuadraticArcLengthC, 265, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) __PYX_ERR(0, 265, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":298 - * - * - * def calcQuadraticBounds(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - __pyx_tuple__27 = PyTuple_Pack(14, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_ax2, __pyx_n_s_ay2, __pyx_n_s_roots, __pyx_n_s_points, __pyx_n_s_t); if (unlikely(!__pyx_tuple__27)) __PYX_ERR(0, 298, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__27); - __Pyx_GIVEREF(__pyx_tuple__27); - __pyx_codeobj__28 = (PyObject*)__Pyx_PyCode_New(3, 0, 14, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__27, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcQuadraticBounds, 298, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__28)) __PYX_ERR(0, 298, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":332 - * - * - * def approximateCubicArcLength(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - __pyx_tuple__29 = PyTuple_Pack(4, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4); if (unlikely(!__pyx_tuple__29)) __PYX_ERR(0, 332, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__29); - __Pyx_GIVEREF(__pyx_tuple__29); - __pyx_codeobj__30 = (PyObject*)__Pyx_PyCode_New(4, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__29, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_approximateCubicArcLength, 332, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__30)) __PYX_ERR(0, 332, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":376 - * v4=cython.double, - * ) - * def approximateCubicArcLengthC(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - __pyx_tuple__31 = PyTuple_Pack(9, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_v0, __pyx_n_s_v1, __pyx_n_s_v2, __pyx_n_s_v3, __pyx_n_s_v4); if (unlikely(!__pyx_tuple__31)) __PYX_ERR(0, 376, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__31); - __Pyx_GIVEREF(__pyx_tuple__31); - __pyx_codeobj__32 = (PyObject*)__Pyx_PyCode_New(4, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__31, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_approximateCubicArcLengthC, 376, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__32)) __PYX_ERR(0, 376, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":412 - * - * - * def calcCubicBounds(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - __pyx_tuple__33 = PyTuple_Pack(23, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_ax3, __pyx_n_s_ay3, __pyx_n_s_bx2, __pyx_n_s_by2, __pyx_n_s_xRoots, __pyx_n_s_yRoots, __pyx_n_s_roots, __pyx_n_s_points, __pyx_n_s_t, __pyx_n_s_t, __pyx_n_s_t); if (unlikely(!__pyx_tuple__33)) __PYX_ERR(0, 412, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__33); - __Pyx_GIVEREF(__pyx_tuple__33); - __pyx_codeobj__34 = (PyObject*)__Pyx_PyCode_New(4, 0, 23, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__33, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcCubicBounds, 412, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__34)) __PYX_ERR(0, 412, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":450 - * - * - * def splitLine(pt1, pt2, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a line at a given coordinate. - * - */ - __pyx_tuple__35 = PyTuple_Pack(15, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_where, __pyx_n_s_isHorizontal, __pyx_n_s_pt1x, __pyx_n_s_pt1y, __pyx_n_s_pt2x, __pyx_n_s_pt2y, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_a, __pyx_n_s_t, __pyx_n_s_midPt); if (unlikely(!__pyx_tuple__35)) __PYX_ERR(0, 450, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__35); - __Pyx_GIVEREF(__pyx_tuple__35); - __pyx_codeobj__36 = (PyObject*)__Pyx_PyCode_New(4, 0, 15, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__35, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitLine, 450, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__36)) __PYX_ERR(0, 450, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":507 - * - * - * def splitQuadratic(pt1, pt2, pt3, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at a given coordinate. - * - */ - __pyx_tuple__37 = PyTuple_Pack(11, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_where, __pyx_n_s_isHorizontal, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_solutions, __pyx_n_s_genexpr, __pyx_n_s_genexpr); if (unlikely(!__pyx_tuple__37)) __PYX_ERR(0, 507, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__37); - __Pyx_GIVEREF(__pyx_tuple__37); - __pyx_codeobj__38 = (PyObject*)__Pyx_PyCode_New(5, 0, 11, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__37, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitQuadratic, 507, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__38)) __PYX_ERR(0, 507, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":552 - * - * - * def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at a given coordinate. - * - */ - __pyx_tuple__39 = PyTuple_Pack(13, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_where, __pyx_n_s_isHorizontal, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d, __pyx_n_s_solutions, __pyx_n_s_genexpr, __pyx_n_s_genexpr); if (unlikely(!__pyx_tuple__39)) __PYX_ERR(0, 552, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__39); - __Pyx_GIVEREF(__pyx_tuple__39); - __pyx_codeobj__40 = (PyObject*)__Pyx_PyCode_New(6, 0, 13, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__39, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitCubic, 552, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__40)) __PYX_ERR(0, 552, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":589 - * - * - * def splitQuadraticAtT(pt1, pt2, pt3, *ts): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at one or more values of t. - * - */ - __pyx_tuple__41 = PyTuple_Pack(7, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_ts, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c); if (unlikely(!__pyx_tuple__41)) __PYX_ERR(0, 589, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__41); - __Pyx_GIVEREF(__pyx_tuple__41); - __pyx_codeobj__42 = (PyObject*)__Pyx_PyCode_New(3, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__41, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitQuadraticAtT_2, 589, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__42)) __PYX_ERR(0, 589, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":613 - * - * - * def splitCubicAtT(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - __pyx_tuple__43 = PyTuple_Pack(9, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_ts, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d); if (unlikely(!__pyx_tuple__43)) __PYX_ERR(0, 613, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__43); - __Pyx_GIVEREF(__pyx_tuple__43); - __pyx_codeobj__44 = (PyObject*)__Pyx_PyCode_New(4, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__43, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitCubicAtT_2, 613, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__44)) __PYX_ERR(0, 613, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":647 - * d=cython.complex, - * ) - * def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - __pyx_tuple__45 = PyTuple_Pack(9, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_ts, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d); if (unlikely(!__pyx_tuple__45)) __PYX_ERR(0, 647, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__45); - __Pyx_GIVEREF(__pyx_tuple__45); - __pyx_codeobj_ = (PyObject*)__Pyx_PyCode_New(4, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__45, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitCubicAtTC, 647, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj_)) __PYX_ERR(0, 647, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":675 - * t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.double - * ) - * def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at t. - * - */ - __pyx_tuple__46 = PyTuple_Pack(12, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_t, __pyx_n_s_t2, __pyx_n_s_1_t, __pyx_n_s_1_t_2, __pyx_n_s_2_t_1_t, __pyx_n_s_pointAtT, __pyx_n_s_off1, __pyx_n_s_off2); if (unlikely(!__pyx_tuple__46)) __PYX_ERR(0, 675, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__46); - __Pyx_GIVEREF(__pyx_tuple__46); - __pyx_codeobj__47 = (PyObject*)__Pyx_PyCode_New(5, 0, 12, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__46, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitCubicIntoTwoAtTC, 675, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__47)) __PYX_ERR(0, 675, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":701 - * - * - * def _splitQuadraticAtT(a, b, c, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * segments = [] - */ - __pyx_tuple__48 = PyTuple_Pack(26, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_ts, __pyx_n_s_segments, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_i, __pyx_n_s_t1, __pyx_n_s_t2, __pyx_n_s_delta, __pyx_n_s_delta_2, __pyx_n_s_a1x, __pyx_n_s_a1y, __pyx_n_s_b1x, __pyx_n_s_b1y, __pyx_n_s_t1_2, __pyx_n_s_c1x, __pyx_n_s_c1y, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3); if (unlikely(!__pyx_tuple__48)) __PYX_ERR(0, 701, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__48); - __Pyx_GIVEREF(__pyx_tuple__48); - __pyx_codeobj__49 = (PyObject*)__Pyx_PyCode_New(3, 0, 26, 0, CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__48, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitQuadraticAtT, 701, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__49)) __PYX_ERR(0, 701, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":728 - * - * - * def _splitCubicAtT(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - __pyx_tuple__50 = PyTuple_Pack(34, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d, __pyx_n_s_ts, __pyx_n_s_segments, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_i, __pyx_n_s_t1, __pyx_n_s_t2, __pyx_n_s_delta, __pyx_n_s_delta_2, __pyx_n_s_delta_3, __pyx_n_s_t1_2, __pyx_n_s_t1_3, __pyx_n_s_a1x, __pyx_n_s_a1y, __pyx_n_s_b1x, __pyx_n_s_b1y, __pyx_n_s_c1x, __pyx_n_s_c1y, __pyx_n_s_d1x, __pyx_n_s_d1y, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4); if (unlikely(!__pyx_tuple__50)) __PYX_ERR(0, 728, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__50); - __Pyx_GIVEREF(__pyx_tuple__50); - __pyx_codeobj__51 = (PyObject*)__Pyx_PyCode_New(4, 0, 34, 0, CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__50, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitCubicAtT, 728, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__51)) __PYX_ERR(0, 728, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":778 - * d1=cython.complex, - * ) - * def _splitCubicAtTC(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - __pyx_tuple__52 = PyTuple_Pack(21, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d, __pyx_n_s_ts, __pyx_n_s_t1, __pyx_n_s_t2, __pyx_n_s_delta, __pyx_n_s_delta_2, __pyx_n_s_delta_3, __pyx_n_s_a1, __pyx_n_s_b1, __pyx_n_s_c1, __pyx_n_s_d1, __pyx_n_s_i, __pyx_n_s_t1_2, __pyx_n_s_t1_3, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4); if (unlikely(!__pyx_tuple__52)) __PYX_ERR(0, 778, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__52); - __Pyx_GIVEREF(__pyx_tuple__52); - __pyx_codeobj__3 = (PyObject*)__Pyx_PyCode_New(4, 0, 21, 0, CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__52, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_splitCubicAtTC_2, 778, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__3)) __PYX_ERR(0, 778, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":808 - * - * - * def solveQuadratic(a, b, c, sqrt=sqrt): # <<<<<<<<<<<<<< - * """Solve a quadratic equation. - * - */ - __pyx_tuple__53 = PyTuple_Pack(7, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_sqrt, __pyx_n_s_roots, __pyx_n_s_DD, __pyx_n_s_rDD); if (unlikely(!__pyx_tuple__53)) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__53); - __Pyx_GIVEREF(__pyx_tuple__53); - __pyx_codeobj__54 = (PyObject*)__Pyx_PyCode_New(4, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__53, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_solveQuadratic, 808, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__54)) __PYX_ERR(0, 808, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":841 - * - * - * def solveCubic(a, b, c, d): # <<<<<<<<<<<<<< - * """Solve a cubic equation. - * - */ - __pyx_tuple__55 = PyTuple_Pack(19, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d, __pyx_n_s_a1, __pyx_n_s_a2, __pyx_n_s_a3, __pyx_n_s_Q, __pyx_n_s_R, __pyx_n_s_R2, __pyx_n_s_Q3, __pyx_n_s_R2_Q3, __pyx_n_s_x, __pyx_n_s_theta, __pyx_n_s_rQ2, __pyx_n_s_a1_3, __pyx_n_s_x0, __pyx_n_s_x1, __pyx_n_s_x2); if (unlikely(!__pyx_tuple__55)) __PYX_ERR(0, 841, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__55); - __Pyx_GIVEREF(__pyx_tuple__55); - __pyx_codeobj__56 = (PyObject*)__Pyx_PyCode_New(4, 0, 19, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__55, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_solveCubic, 841, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__56)) __PYX_ERR(0, 841, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":938 - * - * - * def calcQuadraticParameters(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - __pyx_tuple__57 = PyTuple_Pack(13, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_x2, __pyx_n_s_y2, __pyx_n_s_x3, __pyx_n_s_y3, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_ax, __pyx_n_s_ay); if (unlikely(!__pyx_tuple__57)) __PYX_ERR(0, 938, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__57); - __Pyx_GIVEREF(__pyx_tuple__57); - __pyx_codeobj__58 = (PyObject*)__Pyx_PyCode_New(3, 0, 13, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__57, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcQuadraticParameters, 938, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__58)) __PYX_ERR(0, 938, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":949 - * - * - * def calcCubicParameters(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - __pyx_tuple__59 = PyTuple_Pack(18, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_x2, __pyx_n_s_y2, __pyx_n_s_x3, __pyx_n_s_y3, __pyx_n_s_x4, __pyx_n_s_y4, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_ax, __pyx_n_s_ay); if (unlikely(!__pyx_tuple__59)) __PYX_ERR(0, 949, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__59); - __Pyx_GIVEREF(__pyx_tuple__59); - __pyx_codeobj__60 = (PyObject*)__Pyx_PyCode_New(4, 0, 18, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__59, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcCubicParameters, 949, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__60)) __PYX_ERR(0, 949, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":981 - * - * - * def calcQuadraticPoints(a, b, c): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - __pyx_tuple__61 = PyTuple_Pack(15, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_x1, __pyx_n_s_y1, __pyx_n_s_x2, __pyx_n_s_y2, __pyx_n_s_x3, __pyx_n_s_y3); if (unlikely(!__pyx_tuple__61)) __PYX_ERR(0, 981, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__61); - __Pyx_GIVEREF(__pyx_tuple__61); - __pyx_codeobj__62 = (PyObject*)__Pyx_PyCode_New(3, 0, 15, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__61, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcQuadraticPoints, 981, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__62)) __PYX_ERR(0, 981, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":994 - * - * - * def calcCubicPoints(a, b, c, d): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - __pyx_tuple__63 = PyTuple_Pack(20, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_d, __pyx_n_s_ax, __pyx_n_s_ay, __pyx_n_s_bx, __pyx_n_s_by, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_dx, __pyx_n_s_dy, __pyx_n_s_x1, __pyx_n_s_y1, __pyx_n_s_x2, __pyx_n_s_y2, __pyx_n_s_x3, __pyx_n_s_y3, __pyx_n_s_x4, __pyx_n_s_y4); if (unlikely(!__pyx_tuple__63)) __PYX_ERR(0, 994, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__63); - __Pyx_GIVEREF(__pyx_tuple__63); - __pyx_codeobj__64 = (PyObject*)__Pyx_PyCode_New(4, 0, 20, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__63, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_calcCubicPoints, 994, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__64)) __PYX_ERR(0, 994, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1033 - * - * - * def linePointAtT(pt1, pt2, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a line. - * - */ - __pyx_tuple__65 = PyTuple_Pack(3, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_t); if (unlikely(!__pyx_tuple__65)) __PYX_ERR(0, 1033, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__65); - __Pyx_GIVEREF(__pyx_tuple__65); - __pyx_codeobj__66 = (PyObject*)__Pyx_PyCode_New(3, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__65, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_linePointAtT, 1033, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__66)) __PYX_ERR(0, 1033, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1046 - * - * - * def quadraticPointAtT(pt1, pt2, pt3, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a quadratic curve. - * - */ - __pyx_tuple__67 = PyTuple_Pack(6, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_t, __pyx_n_s_x, __pyx_n_s_y); if (unlikely(!__pyx_tuple__67)) __PYX_ERR(0, 1046, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__67); - __Pyx_GIVEREF(__pyx_tuple__67); - __pyx_codeobj__68 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__67, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_quadraticPointAtT, 1046, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__68)) __PYX_ERR(0, 1046, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1061 - * - * - * def cubicPointAtT(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - __pyx_tuple__69 = PyTuple_Pack(10, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_t, __pyx_n_s_t2, __pyx_n_s_1_t, __pyx_n_s_1_t_2, __pyx_n_s_x, __pyx_n_s_y); if (unlikely(!__pyx_tuple__69)) __PYX_ERR(0, 1061, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__69); - __Pyx_GIVEREF(__pyx_tuple__69); - __pyx_codeobj__70 = (PyObject*)__Pyx_PyCode_New(5, 0, 10, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__69, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_cubicPointAtT, 1061, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__70)) __PYX_ERR(0, 1061, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1096 - * ) - * @cython.locals(t2=cython.double, _1_t=cython.double, _1_t_2=cython.double) - * def cubicPointAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - __pyx_tuple__71 = PyTuple_Pack(8, __pyx_n_s_pt1, __pyx_n_s_pt2, __pyx_n_s_pt3, __pyx_n_s_pt4, __pyx_n_s_t, __pyx_n_s_t2, __pyx_n_s_1_t, __pyx_n_s_1_t_2); if (unlikely(!__pyx_tuple__71)) __PYX_ERR(0, 1096, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__71); - __Pyx_GIVEREF(__pyx_tuple__71); - __pyx_codeobj__72 = (PyObject*)__Pyx_PyCode_New(5, 0, 8, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__71, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_cubicPointAtTC, 1096, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__72)) __PYX_ERR(0, 1096, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1112 - * - * - * def segmentPointAtT(seg, t): # <<<<<<<<<<<<<< - * if len(seg) == 2: - * return linePointAtT(*seg, t) - */ - __pyx_tuple__73 = PyTuple_Pack(2, __pyx_n_s_seg, __pyx_n_s_t); if (unlikely(!__pyx_tuple__73)) __PYX_ERR(0, 1112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__73); - __Pyx_GIVEREF(__pyx_tuple__73); - __pyx_codeobj__74 = (PyObject*)__Pyx_PyCode_New(2, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__73, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_segmentPointAtT, 1112, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__74)) __PYX_ERR(0, 1112, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1127 - * - * - * def _line_t_of_pt(s, e, pt): # <<<<<<<<<<<<<< - * sx, sy = s - * ex, ey = e - */ - __pyx_tuple__75 = PyTuple_Pack(9, __pyx_n_s_s, __pyx_n_s_e, __pyx_n_s_pt, __pyx_n_s_sx, __pyx_n_s_sy, __pyx_n_s_ex, __pyx_n_s_ey, __pyx_n_s_px, __pyx_n_s_py); if (unlikely(!__pyx_tuple__75)) __PYX_ERR(0, 1127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__75); - __Pyx_GIVEREF(__pyx_tuple__75); - __pyx_codeobj__76 = (PyObject*)__Pyx_PyCode_New(3, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__75, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_line_t_of_pt, 1127, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__76)) __PYX_ERR(0, 1127, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1141 - * - * - * def _both_points_are_on_same_side_of_origin(a, b, origin): # <<<<<<<<<<<<<< - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) - */ - __pyx_tuple__77 = PyTuple_Pack(5, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_origin, __pyx_n_s_xDiff, __pyx_n_s_yDiff); if (unlikely(!__pyx_tuple__77)) __PYX_ERR(0, 1141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__77); - __Pyx_GIVEREF(__pyx_tuple__77); - __pyx_codeobj__78 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__77, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_both_points_are_on_same_side_of, 1141, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__78)) __PYX_ERR(0, 1141, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1147 - * - * - * def lineLineIntersections(s1, e1, s2, e2): # <<<<<<<<<<<<<< - * """Finds intersections between two line segments. - * - */ - __pyx_tuple__79 = PyTuple_Pack(17, __pyx_n_s_s1, __pyx_n_s_e1, __pyx_n_s_s2, __pyx_n_s_e2, __pyx_n_s_s1x, __pyx_n_s_s1y, __pyx_n_s_e1x, __pyx_n_s_e1y, __pyx_n_s_s2x, __pyx_n_s_s2y, __pyx_n_s_e2x, __pyx_n_s_e2y, __pyx_n_s_x, __pyx_n_s_slope34, __pyx_n_s_y, __pyx_n_s_pt, __pyx_n_s_slope12); if (unlikely(!__pyx_tuple__79)) __PYX_ERR(0, 1147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__79); - __Pyx_GIVEREF(__pyx_tuple__79); - __pyx_codeobj__80 = (PyObject*)__Pyx_PyCode_New(4, 0, 17, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__79, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_lineLineIntersections, 1147, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__80)) __PYX_ERR(0, 1147, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1225 - * - * - * def _alignment_transformation(segment): # <<<<<<<<<<<<<< - * # Returns a transformation which aligns a segment horizontally at the - * # origin. Apply this transformation to curves and root-find to find - */ - __pyx_tuple__81 = PyTuple_Pack(4, __pyx_n_s_segment, __pyx_n_s_start, __pyx_n_s_end, __pyx_n_s_angle); if (unlikely(!__pyx_tuple__81)) __PYX_ERR(0, 1225, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__81); - __Pyx_GIVEREF(__pyx_tuple__81); - __pyx_codeobj__82 = (PyObject*)__Pyx_PyCode_New(1, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__81, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_alignment_transformation, 1225, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__82)) __PYX_ERR(0, 1225, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1235 - * - * - * def _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - */ - __pyx_tuple__83 = PyTuple_Pack(10, __pyx_n_s_curve, __pyx_n_s_line, __pyx_n_s_aligned_curve, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_intersections, __pyx_n_s_d, __pyx_n_s_genexpr, __pyx_n_s_genexpr); if (unlikely(!__pyx_tuple__83)) __PYX_ERR(0, 1235, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__83); - __Pyx_GIVEREF(__pyx_tuple__83); - __pyx_codeobj__84 = (PyObject*)__Pyx_PyCode_New(2, 0, 10, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__83, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_curve_line_intersections_t, 1235, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__84)) __PYX_ERR(0, 1235, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1248 - * - * - * def curveLineIntersections(curve, line): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a line. - * - */ - __pyx_tuple__85 = PyTuple_Pack(7, __pyx_n_s_curve, __pyx_n_s_line, __pyx_n_s_pointFinder, __pyx_n_s_intersections, __pyx_n_s_t, __pyx_n_s_pt, __pyx_n_s_line_t); if (unlikely(!__pyx_tuple__85)) __PYX_ERR(0, 1248, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__85); - __Pyx_GIVEREF(__pyx_tuple__85); - __pyx_codeobj__86 = (PyObject*)__Pyx_PyCode_New(2, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__85, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_curveLineIntersections, 1248, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__86)) __PYX_ERR(0, 1248, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1286 - * - * - * def _curve_bounds(c): # <<<<<<<<<<<<<< - * if len(c) == 3: - * return calcQuadraticBounds(*c) - */ - __pyx_tuple__87 = PyTuple_Pack(1, __pyx_n_s_c); if (unlikely(!__pyx_tuple__87)) __PYX_ERR(0, 1286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__87); - __Pyx_GIVEREF(__pyx_tuple__87); - __pyx_codeobj__88 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__87, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_curve_bounds, 1286, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__88)) __PYX_ERR(0, 1286, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1294 - * - * - * def _split_segment_at_t(c, t): # <<<<<<<<<<<<<< - * if len(c) == 2: - * s, e = c - */ - __pyx_tuple__89 = PyTuple_Pack(5, __pyx_n_s_c, __pyx_n_s_t, __pyx_n_s_s, __pyx_n_s_e, __pyx_n_s_midpoint); if (unlikely(!__pyx_tuple__89)) __PYX_ERR(0, 1294, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__89); - __Pyx_GIVEREF(__pyx_tuple__89); - __pyx_codeobj__90 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__89, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_split_segment_at_t, 1294, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__90)) __PYX_ERR(0, 1294, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ - __pyx_tuple__92 = PyTuple_Pack(25, __pyx_n_s_curve1, __pyx_n_s_curve2, __pyx_n_s_precision, __pyx_n_s_range1, __pyx_n_s_range2, __pyx_n_s_bounds1, __pyx_n_s_bounds2, __pyx_n_s_intersects, __pyx_n_s__91, __pyx_n_s_midpoint, __pyx_n_s_midpoint, __pyx_n_s_c11, __pyx_n_s_c12, __pyx_n_s_c11_range, __pyx_n_s_c12_range, __pyx_n_s_c21, __pyx_n_s_c22, __pyx_n_s_c21_range, __pyx_n_s_c22_range, __pyx_n_s_found, __pyx_n_s_unique_key, __pyx_n_s_seen, __pyx_n_s_unique_values, __pyx_n_s_ts, __pyx_n_s_key); if (unlikely(!__pyx_tuple__92)) __PYX_ERR(0, 1306, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__92); - __Pyx_GIVEREF(__pyx_tuple__92); - __pyx_codeobj__93 = (PyObject*)__Pyx_PyCode_New(5, 0, 25, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__92, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_curve_curve_intersections_t, 1306, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__93)) __PYX_ERR(0, 1306, __pyx_L1_error) - __pyx_tuple__94 = PyTuple_Pack(3, ((PyObject*)__pyx_float_1eneg_3), ((PyObject *)Py_None), ((PyObject *)Py_None)); if (unlikely(!__pyx_tuple__94)) __PYX_ERR(0, 1306, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__94); - __Pyx_GIVEREF(__pyx_tuple__94); - - /* "fontTools/misc/bezierTools.py":1373 - * - * - * def curveCurveIntersections(curve1, curve2): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a curve. - * - */ - __pyx_tuple__95 = PyTuple_Pack(4, __pyx_n_s_curve1, __pyx_n_s_curve2, __pyx_n_s_intersection_ts, __pyx_n_s_ts); if (unlikely(!__pyx_tuple__95)) __PYX_ERR(0, 1373, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__95); - __Pyx_GIVEREF(__pyx_tuple__95); - __pyx_codeobj__96 = (PyObject*)__Pyx_PyCode_New(2, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__95, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_curveCurveIntersections, 1373, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__96)) __PYX_ERR(0, 1373, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1401 - * - * - * def segmentSegmentIntersections(seg1, seg2): # <<<<<<<<<<<<<< - * """Finds intersections between two segments. - * - */ - __pyx_tuple__97 = PyTuple_Pack(5, __pyx_n_s_seg1, __pyx_n_s_seg2, __pyx_n_s_swapped, __pyx_n_s_intersections, __pyx_n_s_i); if (unlikely(!__pyx_tuple__97)) __PYX_ERR(0, 1401, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__97); - __Pyx_GIVEREF(__pyx_tuple__97); - __pyx_codeobj__98 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__97, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_segmentSegmentIntersections, 1401, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__98)) __PYX_ERR(0, 1401, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1449 - * - * - * def _segmentrepr(obj): # <<<<<<<<<<<<<< - * """ - * >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]]) - */ - __pyx_tuple__99 = PyTuple_Pack(4, __pyx_n_s_obj, __pyx_n_s_it, __pyx_n_s_genexpr, __pyx_n_s_genexpr); if (unlikely(!__pyx_tuple__99)) __PYX_ERR(0, 1449, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__99); - __Pyx_GIVEREF(__pyx_tuple__99); - __pyx_codeobj__100 = (PyObject*)__Pyx_PyCode_New(1, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__99, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_segmentrepr, 1449, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__100)) __PYX_ERR(0, 1449, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":1462 - * - * - * def printSegments(segments): # <<<<<<<<<<<<<< - * """Helper for the doctests, displaying each segment in a list of - * segments on a single line as a tuple. - */ - __pyx_tuple__101 = PyTuple_Pack(2, __pyx_n_s_segments, __pyx_n_s_segment); if (unlikely(!__pyx_tuple__101)) __PYX_ERR(0, 1462, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__101); - __Pyx_GIVEREF(__pyx_tuple__101); - __pyx_codeobj__102 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__101, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Lib_fontTools_misc_bezierTools_p, __pyx_n_s_printSegments, 1462, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__102)) __PYX_ERR(0, 1462, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_0_0 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_float_0_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_0_5 = PyFloat_FromDouble(0.5); if (unlikely(!__pyx_float_0_5)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_1_0 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_float_1_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_2_0 = PyFloat_FromDouble(2.0); if (unlikely(!__pyx_float_2_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_3_0 = PyFloat_FromDouble(3.0); if (unlikely(!__pyx_float_3_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_4_0 = PyFloat_FromDouble(4.0); if (unlikely(!__pyx_float_4_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_9_0 = PyFloat_FromDouble(9.0); if (unlikely(!__pyx_float_9_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_1eneg_3 = PyFloat_FromDouble(1e-3); if (unlikely(!__pyx_float_1eneg_3)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_27_0 = PyFloat_FromDouble(27.0); if (unlikely(!__pyx_float_27_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_54_0 = PyFloat_FromDouble(54.0); if (unlikely(!__pyx_float_54_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_0_005 = PyFloat_FromDouble(0.005); if (unlikely(!__pyx_float_0_005)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_0_125 = PyFloat_FromDouble(0.125); if (unlikely(!__pyx_float_0_125)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_1eneg_10 = PyFloat_FromDouble(1e-10); if (unlikely(!__pyx_float_1eneg_10)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_neg_2_0 = PyFloat_FromDouble(-2.0); if (unlikely(!__pyx_float_neg_2_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_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_3 = PyInt_FromLong(3); if (unlikely(!__pyx_int_3)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_6 = PyInt_FromLong(6); if (unlikely(!__pyx_int_6)) __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 ---*/ - __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 ---*/ - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic) < 0) __PYX_ERR(0, 507, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct__splitQuadratic; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr) < 0) __PYX_ERR(0, 546, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_1_genexpr; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic) < 0) __PYX_ERR(0, 552, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_2_splitCubic; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr) < 0) __PYX_ERR(0, 583, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_3_genexpr; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC) < 0) __PYX_ERR(0, 647, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_4_splitCubicAtTC; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC) < 0) __PYX_ERR(0, 778, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_5__splitCubicAtTC; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t) < 0) __PYX_ERR(0, 1235, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_6__curve_line_intersections_t; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr) < 0) __PYX_ERR(0, 1245, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_7_genexpr; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t) < 0) __PYX_ERR(0, 1306, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_8__curve_curve_intersections_t; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr) < 0) __PYX_ERR(0, 1449, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_9__segmentrepr; - if (PyType_Ready(&__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr) < 0) __PYX_ERR(0, 1459, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr.tp_dictoffset && __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr = &__pyx_type_9fontTools_4misc_11bezierTools___pyx_scope_struct_10_genexpr; - __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 initbezierTools(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC initbezierTools(void) -#else -__Pyx_PyMODINIT_FUNC PyInit_bezierTools(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit_bezierTools(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_bezierTools(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - 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; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - 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 'bezierTools' 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_bezierTools(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(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - PyEval_InitThreads(); - #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("bezierTools", __pyx_methods, __pyx_k_fontTools_misc_bezierTools_py_to, 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_fontTools__misc__bezierTools) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __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, "fontTools.misc.bezierTools")) { - if (unlikely(PyDict_SetItemString(modules, "fontTools.misc.bezierTools", __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 - - /* "fontTools/misc/bezierTools.py":5 - * """ - * - * from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea # <<<<<<<<<<<<<< - * from fontTools.misc.transform import Identity - * import math - */ - __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_calcBounds); - __Pyx_GIVEREF(__pyx_n_s_calcBounds); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_calcBounds); - __Pyx_INCREF(__pyx_n_s_sectRect); - __Pyx_GIVEREF(__pyx_n_s_sectRect); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_sectRect); - __Pyx_INCREF(__pyx_n_s_rectArea); - __Pyx_GIVEREF(__pyx_n_s_rectArea); - PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_s_rectArea); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_fontTools_misc_arrayTools, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_calcBounds); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcBounds, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_sectRect); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_sectRect, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_rectArea); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_rectArea, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":6 - * - * from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea - * from fontTools.misc.transform import Identity # <<<<<<<<<<<<<< - * import math - * from collections import namedtuple - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_Identity); - __Pyx_GIVEREF(__pyx_n_s_Identity); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_Identity); - __pyx_t_1 = __Pyx_Import(__pyx_n_s_fontTools_misc_transform, __pyx_t_2, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_Identity); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_Identity, __pyx_t_2) < 0) __PYX_ERR(0, 6, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":7 - * from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea - * from fontTools.misc.transform import Identity - * import math # <<<<<<<<<<<<<< - * from collections import namedtuple - * - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_math, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_math, __pyx_t_1) < 0) __PYX_ERR(0, 7, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":8 - * from fontTools.misc.transform import Identity - * import math - * from collections import namedtuple # <<<<<<<<<<<<<< - * - * try: - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_namedtuple); - __Pyx_GIVEREF(__pyx_n_s_namedtuple); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_namedtuple); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_collections, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_namedtuple); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_namedtuple, __pyx_t_1) < 0) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":10 - * from collections import namedtuple - * - * try: # <<<<<<<<<<<<<< - * import cython - * - */ - { - __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:*/ { - - /* "fontTools/misc/bezierTools.py":13 - * import cython - * - * COMPILED = cython.compiled # <<<<<<<<<<<<<< - * except (AttributeError, ImportError): - * # if cython not installed, use mock module with no-op decorators and types - */ - if (PyDict_SetItem(__pyx_d, __pyx_n_s_COMPILED, Py_True) < 0) __PYX_ERR(0, 13, __pyx_L2_error) - - /* "fontTools/misc/bezierTools.py":10 - * from collections import namedtuple - * - * try: # <<<<<<<<<<<<<< - * import cython - * - */ - } - __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_L7_try_end; - __pyx_L2_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":14 - * - * COMPILED = cython.compiled - * except (AttributeError, ImportError): # <<<<<<<<<<<<<< - * # if cython not installed, use mock module with no-op decorators and types - * from fontTools.misc import cython - */ - __pyx_t_6 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_AttributeError) || __Pyx_PyErr_ExceptionMatches(__pyx_builtin_ImportError); - if (__pyx_t_6) { - __Pyx_AddTraceback("fontTools.misc.bezierTools", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_2, &__pyx_t_1, &__pyx_t_7) < 0) __PYX_ERR(0, 14, __pyx_L4_except_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_7); - - /* "fontTools/misc/bezierTools.py":16 - * except (AttributeError, ImportError): - * # if cython not installed, use mock module with no-op decorators and types - * from fontTools.misc import cython # <<<<<<<<<<<<<< - * - * COMPILED = False - */ - __pyx_t_8 = PyList_New(1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 16, __pyx_L4_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_n_s_cython); - __Pyx_GIVEREF(__pyx_n_s_cython); - PyList_SET_ITEM(__pyx_t_8, 0, __pyx_n_s_cython); - __pyx_t_9 = __Pyx_Import(__pyx_n_s_fontTools_misc, __pyx_t_8, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 16, __pyx_L4_except_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_ImportFrom(__pyx_t_9, __pyx_n_s_cython); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 16, __pyx_L4_except_error) - __Pyx_GOTREF(__pyx_t_8); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_cython, __pyx_t_8) < 0) __PYX_ERR(0, 16, __pyx_L4_except_error) - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "fontTools/misc/bezierTools.py":18 - * from fontTools.misc import cython - * - * COMPILED = False # <<<<<<<<<<<<<< - * - * - */ - if (PyDict_SetItem(__pyx_d, __pyx_n_s_COMPILED, Py_False) < 0) __PYX_ERR(0, 18, __pyx_L4_except_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L3_exception_handled; - } - goto __pyx_L4_except_error; - __pyx_L4_except_error:; - - /* "fontTools/misc/bezierTools.py":10 - * from collections import namedtuple - * - * try: # <<<<<<<<<<<<<< - * import cython - * - */ - __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_L3_exception_handled:; - __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); - __pyx_L7_try_end:; - } - - /* "fontTools/misc/bezierTools.py":21 - * - * - * Intersection = namedtuple("Intersection", ["pt", "t1", "t2"]) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_namedtuple); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 21, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_pt); - __Pyx_GIVEREF(__pyx_n_u_pt); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_pt); - __Pyx_INCREF(__pyx_n_u_t1); - __Pyx_GIVEREF(__pyx_n_u_t1); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_u_t1); - __Pyx_INCREF(__pyx_n_u_t2); - __Pyx_GIVEREF(__pyx_n_u_t2); - PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_u_t2); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 21, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_u_Intersection); - __Pyx_GIVEREF(__pyx_n_u_Intersection); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_n_u_Intersection); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s_Intersection, __pyx_t_1) < 0) __PYX_ERR(0, 21, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":24 - * - * - * __all__ = [ # <<<<<<<<<<<<<< - * "approximateCubicArcLength", - * "approximateCubicArcLengthC", - */ - __pyx_t_1 = PyList_New(28); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_approximateCubicArcLength); - __Pyx_GIVEREF(__pyx_n_u_approximateCubicArcLength); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_approximateCubicArcLength); - __Pyx_INCREF(__pyx_n_u_approximateCubicArcLengthC); - __Pyx_GIVEREF(__pyx_n_u_approximateCubicArcLengthC); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_u_approximateCubicArcLengthC); - __Pyx_INCREF(__pyx_n_u_approximateQuadraticArcLength); - __Pyx_GIVEREF(__pyx_n_u_approximateQuadraticArcLength); - PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_u_approximateQuadraticArcLength); - __Pyx_INCREF(__pyx_n_u_approximateQuadraticArcLengthC); - __Pyx_GIVEREF(__pyx_n_u_approximateQuadraticArcLengthC); - PyList_SET_ITEM(__pyx_t_1, 3, __pyx_n_u_approximateQuadraticArcLengthC); - __Pyx_INCREF(__pyx_n_u_calcCubicArcLength); - __Pyx_GIVEREF(__pyx_n_u_calcCubicArcLength); - PyList_SET_ITEM(__pyx_t_1, 4, __pyx_n_u_calcCubicArcLength); - __Pyx_INCREF(__pyx_n_u_calcCubicArcLengthC); - __Pyx_GIVEREF(__pyx_n_u_calcCubicArcLengthC); - PyList_SET_ITEM(__pyx_t_1, 5, __pyx_n_u_calcCubicArcLengthC); - __Pyx_INCREF(__pyx_n_u_calcQuadraticArcLength); - __Pyx_GIVEREF(__pyx_n_u_calcQuadraticArcLength); - PyList_SET_ITEM(__pyx_t_1, 6, __pyx_n_u_calcQuadraticArcLength); - __Pyx_INCREF(__pyx_n_u_calcQuadraticArcLengthC); - __Pyx_GIVEREF(__pyx_n_u_calcQuadraticArcLengthC); - PyList_SET_ITEM(__pyx_t_1, 7, __pyx_n_u_calcQuadraticArcLengthC); - __Pyx_INCREF(__pyx_n_u_calcCubicBounds); - __Pyx_GIVEREF(__pyx_n_u_calcCubicBounds); - PyList_SET_ITEM(__pyx_t_1, 8, __pyx_n_u_calcCubicBounds); - __Pyx_INCREF(__pyx_n_u_calcQuadraticBounds); - __Pyx_GIVEREF(__pyx_n_u_calcQuadraticBounds); - PyList_SET_ITEM(__pyx_t_1, 9, __pyx_n_u_calcQuadraticBounds); - __Pyx_INCREF(__pyx_n_u_splitLine); - __Pyx_GIVEREF(__pyx_n_u_splitLine); - PyList_SET_ITEM(__pyx_t_1, 10, __pyx_n_u_splitLine); - __Pyx_INCREF(__pyx_n_u_splitQuadratic); - __Pyx_GIVEREF(__pyx_n_u_splitQuadratic); - PyList_SET_ITEM(__pyx_t_1, 11, __pyx_n_u_splitQuadratic); - __Pyx_INCREF(__pyx_n_u_splitCubic); - __Pyx_GIVEREF(__pyx_n_u_splitCubic); - PyList_SET_ITEM(__pyx_t_1, 12, __pyx_n_u_splitCubic); - __Pyx_INCREF(__pyx_n_u_splitQuadraticAtT_2); - __Pyx_GIVEREF(__pyx_n_u_splitQuadraticAtT_2); - PyList_SET_ITEM(__pyx_t_1, 13, __pyx_n_u_splitQuadraticAtT_2); - __Pyx_INCREF(__pyx_n_u_splitCubicAtT_2); - __Pyx_GIVEREF(__pyx_n_u_splitCubicAtT_2); - PyList_SET_ITEM(__pyx_t_1, 14, __pyx_n_u_splitCubicAtT_2); - __Pyx_INCREF(__pyx_n_u_splitCubicAtTC); - __Pyx_GIVEREF(__pyx_n_u_splitCubicAtTC); - PyList_SET_ITEM(__pyx_t_1, 15, __pyx_n_u_splitCubicAtTC); - __Pyx_INCREF(__pyx_n_u_splitCubicIntoTwoAtTC); - __Pyx_GIVEREF(__pyx_n_u_splitCubicIntoTwoAtTC); - PyList_SET_ITEM(__pyx_t_1, 16, __pyx_n_u_splitCubicIntoTwoAtTC); - __Pyx_INCREF(__pyx_n_u_solveQuadratic); - __Pyx_GIVEREF(__pyx_n_u_solveQuadratic); - PyList_SET_ITEM(__pyx_t_1, 17, __pyx_n_u_solveQuadratic); - __Pyx_INCREF(__pyx_n_u_solveCubic); - __Pyx_GIVEREF(__pyx_n_u_solveCubic); - PyList_SET_ITEM(__pyx_t_1, 18, __pyx_n_u_solveCubic); - __Pyx_INCREF(__pyx_n_u_quadraticPointAtT); - __Pyx_GIVEREF(__pyx_n_u_quadraticPointAtT); - PyList_SET_ITEM(__pyx_t_1, 19, __pyx_n_u_quadraticPointAtT); - __Pyx_INCREF(__pyx_n_u_cubicPointAtT); - __Pyx_GIVEREF(__pyx_n_u_cubicPointAtT); - PyList_SET_ITEM(__pyx_t_1, 20, __pyx_n_u_cubicPointAtT); - __Pyx_INCREF(__pyx_n_u_cubicPointAtTC); - __Pyx_GIVEREF(__pyx_n_u_cubicPointAtTC); - PyList_SET_ITEM(__pyx_t_1, 21, __pyx_n_u_cubicPointAtTC); - __Pyx_INCREF(__pyx_n_u_linePointAtT); - __Pyx_GIVEREF(__pyx_n_u_linePointAtT); - PyList_SET_ITEM(__pyx_t_1, 22, __pyx_n_u_linePointAtT); - __Pyx_INCREF(__pyx_n_u_segmentPointAtT); - __Pyx_GIVEREF(__pyx_n_u_segmentPointAtT); - PyList_SET_ITEM(__pyx_t_1, 23, __pyx_n_u_segmentPointAtT); - __Pyx_INCREF(__pyx_n_u_lineLineIntersections); - __Pyx_GIVEREF(__pyx_n_u_lineLineIntersections); - PyList_SET_ITEM(__pyx_t_1, 24, __pyx_n_u_lineLineIntersections); - __Pyx_INCREF(__pyx_n_u_curveLineIntersections); - __Pyx_GIVEREF(__pyx_n_u_curveLineIntersections); - PyList_SET_ITEM(__pyx_t_1, 25, __pyx_n_u_curveLineIntersections); - __Pyx_INCREF(__pyx_n_u_curveCurveIntersections); - __Pyx_GIVEREF(__pyx_n_u_curveCurveIntersections); - PyList_SET_ITEM(__pyx_t_1, 26, __pyx_n_u_curveCurveIntersections); - __Pyx_INCREF(__pyx_n_u_segmentSegmentIntersections); - __Pyx_GIVEREF(__pyx_n_u_segmentSegmentIntersections); - PyList_SET_ITEM(__pyx_t_1, 27, __pyx_n_u_segmentSegmentIntersections); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_t_1) < 0) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":56 - * - * - * def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_1calcCubicArcLength, 0, __pyx_n_s_calcCubicArcLength, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__11)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_1, __pyx_tuple__12); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcCubicArcLength, __pyx_t_1) < 0) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":75 - * - * - * def _split_cubic_into_two(p0, p1, p2, p3): # <<<<<<<<<<<<<< - * mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - * deriv3 = (p3 + p2 - p1 - p0) * 0.125 - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_3_split_cubic_into_two, 0, __pyx_n_s_split_cubic_into_two, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__14)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 75, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_split_cubic_into_two, __pyx_t_1) < 0) __PYX_ERR(0, 75, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":92 - * ) - * @cython.locals(mult=cython.double, arch=cython.double, box=cython.double) - * def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3): # <<<<<<<<<<<<<< - * arch = abs(p0 - p3) - * box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3) - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_5_calcCubicArcLengthCRecurse, 0, __pyx_n_s_calcCubicArcLengthCRecurse, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__16)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcCubicArcLengthCRecurse, __pyx_t_1) < 0) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":115 - * mult=cython.double, - * ) - * def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005): # <<<<<<<<<<<<<< - * """Calculates the arc length for a cubic Bezier segment. - * - */ - __pyx_t_1 = PyFloat_FromDouble(((double)0.005)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __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_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_7calcCubicArcLengthC, 0, __pyx_n_s_calcCubicArcLengthC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__18)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_1, __pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcCubicArcLengthC, __pyx_t_1) < 0) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":129 - * - * - * epsilonDigits = 6 # <<<<<<<<<<<<<< - * epsilon = 1e-10 - * - */ - if (PyDict_SetItem(__pyx_d, __pyx_n_s_epsilonDigits, __pyx_int_6) < 0) __PYX_ERR(0, 129, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":130 - * - * epsilonDigits = 6 - * epsilon = 1e-10 # <<<<<<<<<<<<<< - * - * - */ - if (PyDict_SetItem(__pyx_d, __pyx_n_s_epsilon, __pyx_float_1eneg_10) < 0) __PYX_ERR(0, 130, __pyx_L1_error) - - /* "fontTools/misc/bezierTools.py":151 - * - * - * def calcQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_9calcQuadraticArcLength, 0, __pyx_n_s_calcQuadraticArcLength, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__20)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 151, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcQuadraticArcLength, __pyx_t_1) < 0) __PYX_ERR(0, 151, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":205 - * Len=cython.double, - * ) - * def calcQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_11calcQuadraticArcLengthC, 0, __pyx_n_s_calcQuadraticArcLengthC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__22)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 205, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcQuadraticArcLengthC, __pyx_t_1) < 0) __PYX_ERR(0, 205, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":237 - * - * - * def approximateQuadraticArcLength(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_13approximateQuadraticArcLength, 0, __pyx_n_s_approximateQuadraticArcLength, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__24)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_approximateQuadraticArcLength, __pyx_t_1) < 0) __PYX_ERR(0, 237, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":265 - * v2=cython.double, - * ) - * def approximateQuadraticArcLengthC(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the arc length for a quadratic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_15approximateQuadraticArcLengthC, 0, __pyx_n_s_approximateQuadraticArcLengthC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__26)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 265, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_approximateQuadraticArcLengthC, __pyx_t_1) < 0) __PYX_ERR(0, 265, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":298 - * - * - * def calcQuadraticBounds(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_17calcQuadraticBounds, 0, __pyx_n_s_calcQuadraticBounds, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__28)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 298, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcQuadraticBounds, __pyx_t_1) < 0) __PYX_ERR(0, 298, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":332 - * - * - * def approximateCubicArcLength(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_19approximateCubicArcLength, 0, __pyx_n_s_approximateCubicArcLength, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__30)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 332, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_approximateCubicArcLength, __pyx_t_1) < 0) __PYX_ERR(0, 332, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":376 - * v4=cython.double, - * ) - * def approximateCubicArcLengthC(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Approximates the arc length for a cubic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_21approximateCubicArcLengthC, 0, __pyx_n_s_approximateCubicArcLengthC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__32)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 376, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_approximateCubicArcLengthC, __pyx_t_1) < 0) __PYX_ERR(0, 376, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":412 - * - * - * def calcCubicBounds(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * """Calculates the bounding rectangle for a quadratic Bezier segment. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_23calcCubicBounds, 0, __pyx_n_s_calcCubicBounds, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__34)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 412, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcCubicBounds, __pyx_t_1) < 0) __PYX_ERR(0, 412, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":450 - * - * - * def splitLine(pt1, pt2, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a line at a given coordinate. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_25splitLine, 0, __pyx_n_s_splitLine, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__36)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 450, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitLine, __pyx_t_1) < 0) __PYX_ERR(0, 450, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":507 - * - * - * def splitQuadratic(pt1, pt2, pt3, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at a given coordinate. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_27splitQuadratic, 0, __pyx_n_s_splitQuadratic, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__38)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 507, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitQuadratic, __pyx_t_1) < 0) __PYX_ERR(0, 507, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":552 - * - * - * def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at a given coordinate. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_29splitCubic, 0, __pyx_n_s_splitCubic, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__40)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 552, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitCubic, __pyx_t_1) < 0) __PYX_ERR(0, 552, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":589 - * - * - * def splitQuadraticAtT(pt1, pt2, pt3, *ts): # <<<<<<<<<<<<<< - * """Split a quadratic Bezier curve at one or more values of t. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_31splitQuadraticAtT, 0, __pyx_n_s_splitQuadraticAtT_2, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__42)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 589, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitQuadraticAtT_2, __pyx_t_1) < 0) __PYX_ERR(0, 589, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":613 - * - * - * def splitCubicAtT(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_33splitCubicAtT, 0, __pyx_n_s_splitCubicAtT_2, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__44)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 613, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitCubicAtT_2, __pyx_t_1) < 0) __PYX_ERR(0, 613, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":647 - * d=cython.complex, - * ) - * def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at one or more values of t. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_35splitCubicAtTC, 0, __pyx_n_s_splitCubicAtTC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj_)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 647, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitCubicAtTC, __pyx_t_1) < 0) __PYX_ERR(0, 647, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":675 - * t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.double - * ) - * def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Split a cubic Bezier curve at t. - * - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_38splitCubicIntoTwoAtTC, 0, __pyx_n_s_splitCubicIntoTwoAtTC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__47)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 675, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitCubicIntoTwoAtTC, __pyx_t_1) < 0) __PYX_ERR(0, 675, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":701 - * - * - * def _splitQuadraticAtT(a, b, c, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * segments = [] - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_40_splitQuadraticAtT, 0, __pyx_n_s_splitQuadraticAtT, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__49)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 701, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitQuadraticAtT, __pyx_t_1) < 0) __PYX_ERR(0, 701, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":728 - * - * - * def _splitCubicAtT(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_42_splitCubicAtT, 0, __pyx_n_s_splitCubicAtT, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__51)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 728, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitCubicAtT, __pyx_t_1) < 0) __PYX_ERR(0, 728, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":778 - * d1=cython.complex, - * ) - * def _splitCubicAtTC(a, b, c, d, *ts): # <<<<<<<<<<<<<< - * ts = list(ts) - * ts.insert(0, 0.0) - */ - __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_44_splitCubicAtTC, 0, __pyx_n_s_splitCubicAtTC_2, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__3)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 778, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_splitCubicAtTC_2, __pyx_t_1) < 0) __PYX_ERR(0, 778, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "fontTools/misc/bezierTools.py":805 - * # - * - * from math import sqrt, acos, cos, pi # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = PyList_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_sqrt); - __Pyx_GIVEREF(__pyx_n_s_sqrt); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_sqrt); - __Pyx_INCREF(__pyx_n_s_acos); - __Pyx_GIVEREF(__pyx_n_s_acos); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_acos); - __Pyx_INCREF(__pyx_n_s_cos); - __Pyx_GIVEREF(__pyx_n_s_cos); - PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_s_cos); - __Pyx_INCREF(__pyx_n_s_pi); - __Pyx_GIVEREF(__pyx_n_s_pi); - PyList_SET_ITEM(__pyx_t_1, 3, __pyx_n_s_pi); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_math, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_sqrt, __pyx_t_1) < 0) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_acos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_acos, __pyx_t_1) < 0) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_cos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_cos, __pyx_t_1) < 0) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_pi); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pi, __pyx_t_1) < 0) __PYX_ERR(0, 805, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":808 - * - * - * def solveQuadratic(a, b, c, sqrt=sqrt): # <<<<<<<<<<<<<< - * """Solve a quadratic equation. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_47solveQuadratic, 0, __pyx_n_s_solveQuadratic, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__54)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (!__Pyx_CyFunction_InitDefaults(__pyx_t_2, sizeof(__pyx_defaults), 1)) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_t_2)->__pyx_arg_sqrt = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __Pyx_CyFunction_SetDefaultsGetter(__pyx_t_2, __pyx_pf_9fontTools_4misc_11bezierTools_94__defaults__); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_solveQuadratic, __pyx_t_2) < 0) __PYX_ERR(0, 808, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":841 - * - * - * def solveCubic(a, b, c, d): # <<<<<<<<<<<<<< - * """Solve a cubic equation. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_49solveCubic, 0, __pyx_n_s_solveCubic, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__56)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 841, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_solveCubic, __pyx_t_2) < 0) __PYX_ERR(0, 841, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":938 - * - * - * def calcQuadraticParameters(pt1, pt2, pt3): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_51calcQuadraticParameters, 0, __pyx_n_s_calcQuadraticParameters, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__58)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 938, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcQuadraticParameters, __pyx_t_2) < 0) __PYX_ERR(0, 938, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":949 - * - * - * def calcCubicParameters(pt1, pt2, pt3, pt4): # <<<<<<<<<<<<<< - * x2, y2 = pt2 - * x3, y3 = pt3 - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_53calcCubicParameters, 0, __pyx_n_s_calcCubicParameters, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__60)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 949, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcCubicParameters, __pyx_t_2) < 0) __PYX_ERR(0, 949, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":981 - * - * - * def calcQuadraticPoints(a, b, c): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_55calcQuadraticPoints, 0, __pyx_n_s_calcQuadraticPoints, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__62)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 981, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcQuadraticPoints, __pyx_t_2) < 0) __PYX_ERR(0, 981, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":994 - * - * - * def calcCubicPoints(a, b, c, d): # <<<<<<<<<<<<<< - * ax, ay = a - * bx, by = b - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_57calcCubicPoints, 0, __pyx_n_s_calcCubicPoints, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__64)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 994, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_calcCubicPoints, __pyx_t_2) < 0) __PYX_ERR(0, 994, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1033 - * - * - * def linePointAtT(pt1, pt2, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a line. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_59linePointAtT, 0, __pyx_n_s_linePointAtT, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__66)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1033, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_linePointAtT, __pyx_t_2) < 0) __PYX_ERR(0, 1033, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1046 - * - * - * def quadraticPointAtT(pt1, pt2, pt3, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a quadratic curve. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_61quadraticPointAtT, 0, __pyx_n_s_quadraticPointAtT, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__68)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1046, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_quadraticPointAtT, __pyx_t_2) < 0) __PYX_ERR(0, 1046, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1061 - * - * - * def cubicPointAtT(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_63cubicPointAtT, 0, __pyx_n_s_cubicPointAtT, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__70)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1061, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_cubicPointAtT, __pyx_t_2) < 0) __PYX_ERR(0, 1061, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1096 - * ) - * @cython.locals(t2=cython.double, _1_t=cython.double, _1_t_2=cython.double) - * def cubicPointAtTC(pt1, pt2, pt3, pt4, t): # <<<<<<<<<<<<<< - * """Finds the point at time `t` on a cubic curve. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_65cubicPointAtTC, 0, __pyx_n_s_cubicPointAtTC, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__72)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1096, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_cubicPointAtTC, __pyx_t_2) < 0) __PYX_ERR(0, 1096, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1112 - * - * - * def segmentPointAtT(seg, t): # <<<<<<<<<<<<<< - * if len(seg) == 2: - * return linePointAtT(*seg, t) - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_67segmentPointAtT, 0, __pyx_n_s_segmentPointAtT, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__74)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_segmentPointAtT, __pyx_t_2) < 0) __PYX_ERR(0, 1112, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1127 - * - * - * def _line_t_of_pt(s, e, pt): # <<<<<<<<<<<<<< - * sx, sy = s - * ex, ey = e - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_69_line_t_of_pt, 0, __pyx_n_s_line_t_of_pt, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__76)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_line_t_of_pt, __pyx_t_2) < 0) __PYX_ERR(0, 1127, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1141 - * - * - * def _both_points_are_on_same_side_of_origin(a, b, origin): # <<<<<<<<<<<<<< - * xDiff = (a[0] - origin[0]) * (b[0] - origin[0]) - * yDiff = (a[1] - origin[1]) * (b[1] - origin[1]) - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_71_both_points_are_on_same_side_of_origin, 0, __pyx_n_s_both_points_are_on_same_side_of, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__78)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_both_points_are_on_same_side_of, __pyx_t_2) < 0) __PYX_ERR(0, 1141, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1147 - * - * - * def lineLineIntersections(s1, e1, s2, e2): # <<<<<<<<<<<<<< - * """Finds intersections between two line segments. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_73lineLineIntersections, 0, __pyx_n_s_lineLineIntersections, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__80)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_lineLineIntersections, __pyx_t_2) < 0) __PYX_ERR(0, 1147, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1225 - * - * - * def _alignment_transformation(segment): # <<<<<<<<<<<<<< - * # Returns a transformation which aligns a segment horizontally at the - * # origin. Apply this transformation to curves and root-find to find - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_75_alignment_transformation, 0, __pyx_n_s_alignment_transformation, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__82)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1225, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_alignment_transformation, __pyx_t_2) < 0) __PYX_ERR(0, 1225, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1235 - * - * - * def _curve_line_intersections_t(curve, line): # <<<<<<<<<<<<<< - * aligned_curve = _alignment_transformation(line).transformPoints(curve) - * if len(curve) == 3: - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_77_curve_line_intersections_t, 0, __pyx_n_s_curve_line_intersections_t, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__84)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1235, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_curve_line_intersections_t, __pyx_t_2) < 0) __PYX_ERR(0, 1235, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1248 - * - * - * def curveLineIntersections(curve, line): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a line. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_79curveLineIntersections, 0, __pyx_n_s_curveLineIntersections, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__86)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1248, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_curveLineIntersections, __pyx_t_2) < 0) __PYX_ERR(0, 1248, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1286 - * - * - * def _curve_bounds(c): # <<<<<<<<<<<<<< - * if len(c) == 3: - * return calcQuadraticBounds(*c) - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_81_curve_bounds, 0, __pyx_n_s_curve_bounds, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__88)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_curve_bounds, __pyx_t_2) < 0) __PYX_ERR(0, 1286, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1294 - * - * - * def _split_segment_at_t(c, t): # <<<<<<<<<<<<<< - * if len(c) == 2: - * s, e = c - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_83_split_segment_at_t, 0, __pyx_n_s_split_segment_at_t, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__90)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1294, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_split_segment_at_t, __pyx_t_2) < 0) __PYX_ERR(0, 1294, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1306 - * - * - * def _curve_curve_intersections_t( # <<<<<<<<<<<<<< - * curve1, curve2, precision=1e-3, range1=None, range2=None - * ): - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_85_curve_curve_intersections_t, 0, __pyx_n_s_curve_curve_intersections_t, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__93)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1306, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_tuple__94); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_curve_curve_intersections_t, __pyx_t_2) < 0) __PYX_ERR(0, 1306, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1373 - * - * - * def curveCurveIntersections(curve1, curve2): # <<<<<<<<<<<<<< - * """Finds intersections between a curve and a curve. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_87curveCurveIntersections, 0, __pyx_n_s_curveCurveIntersections, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__96)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1373, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_curveCurveIntersections, __pyx_t_2) < 0) __PYX_ERR(0, 1373, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1401 - * - * - * def segmentSegmentIntersections(seg1, seg2): # <<<<<<<<<<<<<< - * """Finds intersections between two segments. - * - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_89segmentSegmentIntersections, 0, __pyx_n_s_segmentSegmentIntersections, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__98)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1401, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_segmentSegmentIntersections, __pyx_t_2) < 0) __PYX_ERR(0, 1401, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1449 - * - * - * def _segmentrepr(obj): # <<<<<<<<<<<<<< - * """ - * >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]]) - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_91_segmentrepr, 0, __pyx_n_s_segmentrepr, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__100)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1449, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_segmentrepr, __pyx_t_2) < 0) __PYX_ERR(0, 1449, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1462 - * - * - * def printSegments(segments): # <<<<<<<<<<<<<< - * """Helper for the doctests, displaying each segment in a list of - * segments on a single line as a tuple. - */ - __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_4misc_11bezierTools_93printSegments, 0, __pyx_n_s_printSegments, NULL, __pyx_n_s_fontTools_misc_bezierTools, __pyx_d, ((PyObject *)__pyx_codeobj__102)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1462, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_printSegments, __pyx_t_2) < 0) __PYX_ERR(0, 1462, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1470 - * - * - * if __name__ == "__main__": # <<<<<<<<<<<<<< - * import sys - * import doctest - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1470, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_10 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_n_u_main, Py_EQ)); if (unlikely(__pyx_t_10 < 0)) __PYX_ERR(0, 1470, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_10) { - - /* "fontTools/misc/bezierTools.py":1471 - * - * if __name__ == "__main__": - * import sys # <<<<<<<<<<<<<< - * import doctest - * - */ - __pyx_t_2 = __Pyx_Import(__pyx_n_s_sys, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1471, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_sys, __pyx_t_2) < 0) __PYX_ERR(0, 1471, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1472 - * if __name__ == "__main__": - * import sys - * import doctest # <<<<<<<<<<<<<< - * - * sys.exit(doctest.testmod().failed) - */ - __pyx_t_2 = __Pyx_Import(__pyx_n_s_doctest, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1472, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_doctest, __pyx_t_2) < 0) __PYX_ERR(0, 1472, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1474 - * import doctest - * - * sys.exit(doctest.testmod().failed) # <<<<<<<<<<<<<< - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_sys); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_exit); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_doctest); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_testmod); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_failed); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "fontTools/misc/bezierTools.py":1470 - * - * - * if __name__ == "__main__": # <<<<<<<<<<<<<< - * import sys - * import doctest - */ - } - - /* "fontTools/misc/bezierTools.py":1 - * # -*- coding: utf-8 -*- # <<<<<<<<<<<<<< - * """fontTools.misc.bezierTools.py -- tools for working with Bezier path segments. - * """ - */ - __pyx_t_2 = __Pyx_PyDict_NewPresized(15); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_calcQuadraticArcLength_line_151, __pyx_kp_u_Calculates_the_arc_length_for_a) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_calcQuadraticBounds_line_298, __pyx_kp_u_Calculates_the_bounding_rectangl) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_approximateCubicArcLength_line_3, __pyx_kp_u_Approximates_the_arc_length_for) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_calcCubicBounds_line_412, __pyx_kp_u_Calculates_the_bounding_rectangl_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_splitLine_line_450, __pyx_kp_u_Split_a_line_at_a_given_coordina) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_splitQuadratic_line_507, __pyx_kp_u_Split_a_quadratic_Bezier_curve_a) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_splitCubic_line_552, __pyx_kp_u_Split_a_cubic_Bezier_curve_at_a) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_splitQuadraticAtT_line_589, __pyx_kp_u_Split_a_quadratic_Bezier_curve_a_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_splitCubicAtT_line_613, __pyx_kp_u_Split_a_cubic_Bezier_curve_at_on) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_solveCubic_line_841, __pyx_kp_u_Solve_a_cubic_equation_Solves_a) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_lineLineIntersections_line_1147, __pyx_kp_u_Finds_intersections_between_two) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_curveLineIntersections_line_1248, __pyx_kp_u_Finds_intersections_between_a_cu) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_curveCurveIntersections_line_137, __pyx_kp_u_Finds_intersections_between_a_cu_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_segmentSegmentIntersections_line, __pyx_kp_u_Finds_intersections_between_two_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_2, __pyx_kp_u_segmentrepr_line_1449, __pyx_kp_u_segmentrepr_1_2_3_2_3_4_0_1_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init fontTools.misc.bezierTools", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init fontTools.misc.bezierTools"); - } - __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; -} - -/* 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; -} - -/* 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); -} - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = Py_TYPE(func)->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 - -/* 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 - -/* 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 - -/* 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"); -} - -/* IterFinish */ -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -/* UnpackItemEndCheck */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } - return __Pyx_IterFinish(); -} - -/* PyIntBinop */ -#if !CYTHON_COMPILING_IN_PYPY -#if PY_MAJOR_VERSION < 3 || CYTHON_USE_PYLONG_INTERNALS -#define __Pyx_PyInt_TrueDivideObjC_ZeroDivisionError(operand)\ - if (unlikely(zerodivision_check && ((operand) == 0))) {\ - PyErr_SetString(PyExc_ZeroDivisionError, "integer division by zero");\ - return NULL;\ - } -#endif -static PyObject* __Pyx_PyInt_TrueDivideObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { - (void)inplace; - (void)zerodivision_check; - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long a = PyInt_AS_LONG(op1); - __Pyx_PyInt_TrueDivideObjC_ZeroDivisionError(b) - if (8 * sizeof(long) <= 53 || likely(labs(a) <= ((PY_LONG_LONG)1 << 53))) { - return PyFloat_FromDouble((double)a / (double)b); - } - return PyInt_Type.tp_as_number->nb_true_divide(op1, op2); - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a, x; - 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 && 1 * PyLong_SHIFT < 53) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT && 1 * PyLong_SHIFT < 53) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT && 2 * PyLong_SHIFT < 53) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT && 2 * PyLong_SHIFT < 53) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT && 3 * PyLong_SHIFT < 53) { - 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; - } - CYTHON_FALLTHROUGH; - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT && 3 * PyLong_SHIFT < 53) { - 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; - } - CYTHON_FALLTHROUGH; - default: return PyLong_Type.tp_as_number->nb_true_divide(op1, op2); - } - } - __Pyx_PyInt_TrueDivideObjC_ZeroDivisionError(b) - if ((8 * sizeof(long) <= 53 || likely(labs(a) <= ((PY_LONG_LONG)1 << 53))) - || __Pyx_sst_abs(size) <= 52 / PyLong_SHIFT) { - return PyFloat_FromDouble((double)a / (double)b); - } - return PyLong_Type.tp_as_number->nb_true_divide(op1, op2); - return PyLong_FromLong(x); - - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - double result; - if (unlikely(zerodivision_check && b == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division by zero"); - return NULL; - } - PyFPE_START_PROTECT("divide", return NULL) - result = ((double)a) / (double)b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); - } - return (inplace ? PyNumber_InPlaceTrueDivide : PyNumber_TrueDivide)(op1, op2); -} -#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 (__Pyx_PyFastCFunction_Check(func)) { - 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 - -/* 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 - -/* WriteUnraisableException */ -static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, - CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, - int full_traceback, CYTHON_UNUSED int nogil) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_PyThreadState_declare -#ifdef WITH_THREAD - PyGILState_STATE state; - if (nogil) - state = PyGILState_Ensure(); - else state = (PyGILState_STATE)0; -#endif - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - if (full_traceback) { - Py_XINCREF(old_exc); - Py_XINCREF(old_val); - Py_XINCREF(old_tb); - __Pyx_ErrRestore(old_exc, old_val, old_tb); - PyErr_PrintEx(1); - } - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } -#ifdef WITH_THREAD - if (nogil) - PyGILState_Release(state); -#endif -} - -/* PyIntCompare */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_NeObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED long inplace) { - if (op1 == op2) { - Py_RETURN_FALSE; - } - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long a = PyInt_AS_LONG(op1); - if (a != b) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - int unequal; - unsigned long uintval; - Py_ssize_t size = Py_SIZE(op1); - const digit* digits = ((PyLongObject*)op1)->ob_digit; - if (intval == 0) { - if (size != 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } else if (intval < 0) { - if (size >= 0) - Py_RETURN_TRUE; - intval = -intval; - size = -size; - } else { - if (size <= 0) - Py_RETURN_TRUE; - } - uintval = (unsigned long) intval; -#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 4)) { - unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif -#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 3)) { - unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif -#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 2)) { - unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif -#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 1)) { - unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif - unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); - if (unequal != 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - if ((double)a != (double)b) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } - return ( - PyObject_RichCompare(op1, op2, Py_NE)); -} - -/* 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 = NULL; - 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 - -/* PyIntCompare */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED long inplace) { - if (op1 == op2) { - Py_RETURN_TRUE; - } - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long a = PyInt_AS_LONG(op1); - if (a == b) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - int unequal; - unsigned long uintval; - Py_ssize_t size = Py_SIZE(op1); - const digit* digits = ((PyLongObject*)op1)->ob_digit; - if (intval == 0) { - if (size == 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } else if (intval < 0) { - if (size >= 0) - Py_RETURN_FALSE; - intval = -intval; - size = -size; - } else { - if (size <= 0) - Py_RETURN_FALSE; - } - uintval = (unsigned long) intval; -#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 4)) { - unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif -#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 3)) { - unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif -#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 2)) { - unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif -#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 - if (uintval >> (PyLong_SHIFT * 1)) { - unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) - | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); - } else -#endif - unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); - if (unequal == 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - if ((double)a == (double)b) Py_RETURN_TRUE; else Py_RETURN_FALSE; - } - return ( - PyObject_RichCompare(op1, op2, Py_EQ)); -} - -/* None */ -static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname) { - PyErr_Format(PyExc_NameError, "free variable '%s' referenced before assignment in enclosing scope", varname); -} - -/* FetchCommonType */ -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { - PyObject* fake_module; - PyTypeObject* cached_type = NULL; - fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); - if (!fake_module) return NULL; - Py_INCREF(fake_module); - cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); - if (cached_type) { - if (!PyType_Check((PyObject*)cached_type)) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s is not a type object", - type->tp_name); - goto bad; - } - if (cached_type->tp_basicsize != type->tp_basicsize) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s has the wrong size, try recompiling", - type->tp_name); - goto bad; - } - } else { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; - PyErr_Clear(); - if (PyType_Ready(type) < 0) goto bad; - if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) - goto bad; - Py_INCREF(type); - cached_type = type; - } -done: - Py_DECREF(fake_module); - return cached_type; -bad: - Py_XDECREF(cached_type); - cached_type = NULL; - goto done; -} - -/* 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_FAST_THREAD_STATE - 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); - } -#else - 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); -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* 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 - -/* 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 - -/* PyObjectGetMethod */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { - PyObject *attr; -#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr; - descrgetfunc f = NULL; - PyObject **dictptr, *dict; - int meth_found = 0; - assert (*method == NULL); - if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { - attr = __Pyx_PyObject_GetAttrStr(obj, name); - goto try_unpack; - } - if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { - return 0; - } - descr = _PyType_Lookup(tp, name); - if (likely(descr != NULL)) { - Py_INCREF(descr); -#if PY_MAJOR_VERSION >= 3 - #ifdef __Pyx_CyFunction_USED - if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) - #else - if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type))) - #endif -#else - #ifdef __Pyx_CyFunction_USED - if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) - #else - if (likely(PyFunction_Check(descr))) - #endif -#endif - { - meth_found = 1; - } else { - f = Py_TYPE(descr)->tp_descr_get; - if (f != NULL && PyDescr_IsData(descr)) { - attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto try_unpack; - } - } - } - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr != NULL && (dict = *dictptr) != NULL) { - Py_INCREF(dict); - attr = __Pyx_PyDict_GetItemStr(dict, name); - if (attr != NULL) { - Py_INCREF(attr); - Py_DECREF(dict); - Py_XDECREF(descr); - goto try_unpack; - } - Py_DECREF(dict); - } - if (meth_found) { - *method = descr; - return 1; - } - if (f != NULL) { - attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto try_unpack; - } - if (descr != NULL) { - *method = descr; - return 0; - } - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(name)); -#endif - return 0; -#else - attr = __Pyx_PyObject_GetAttrStr(obj, name); - goto try_unpack; -#endif -try_unpack: -#if CYTHON_UNPACK_METHODS - if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { - PyObject *function = PyMethod_GET_FUNCTION(attr); - Py_INCREF(function); - Py_DECREF(attr); - *method = function; - return 1; - } -#endif - *method = attr; - return 0; -} - -/* PyObjectCallMethod1 */ -static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { - PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); - Py_DECREF(method); - return result; -} -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { - PyObject *method = NULL, *result; - int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); - if (likely(is_method)) { - result = __Pyx_PyObject_Call2Args(method, obj, arg); - Py_DECREF(method); - return result; - } - if (unlikely(!method)) return NULL; - return __Pyx__PyObject_CallMethod1(method, arg); -} - -/* CoroutineBase */ -#include -#include -#if PY_VERSION_HEX >= 0x030b00a6 - #ifndef Py_BUILD_CORE - #define Py_BUILD_CORE 1 - #endif - #include "internal/pycore_frame.h" -#endif -#define __Pyx_Coroutine_Undelegate(gen) Py_CLEAR((gen)->yieldfrom) -static int __Pyx_PyGen__FetchStopIterationValue(CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject **pvalue) { - PyObject *et, *ev, *tb; - PyObject *value = NULL; - __Pyx_ErrFetch(&et, &ev, &tb); - if (!et) { - Py_XDECREF(tb); - Py_XDECREF(ev); - Py_INCREF(Py_None); - *pvalue = Py_None; - return 0; - } - if (likely(et == PyExc_StopIteration)) { - if (!ev) { - Py_INCREF(Py_None); - value = Py_None; - } -#if PY_VERSION_HEX >= 0x030300A0 - else if (Py_TYPE(ev) == (PyTypeObject*)PyExc_StopIteration) { - value = ((PyStopIterationObject *)ev)->value; - Py_INCREF(value); - Py_DECREF(ev); - } -#endif - else if (unlikely(PyTuple_Check(ev))) { - if (PyTuple_GET_SIZE(ev) >= 1) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - value = PyTuple_GET_ITEM(ev, 0); - Py_INCREF(value); -#else - value = PySequence_ITEM(ev, 0); -#endif - } else { - Py_INCREF(Py_None); - value = Py_None; - } - Py_DECREF(ev); - } - else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { - value = ev; - } - if (likely(value)) { - Py_XDECREF(tb); - Py_DECREF(et); - *pvalue = value; - return 0; - } - } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { - __Pyx_ErrRestore(et, ev, tb); - return -1; - } - PyErr_NormalizeException(&et, &ev, &tb); - if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { - __Pyx_ErrRestore(et, ev, tb); - return -1; - } - Py_XDECREF(tb); - Py_DECREF(et); -#if PY_VERSION_HEX >= 0x030300A0 - value = ((PyStopIterationObject *)ev)->value; - Py_INCREF(value); - Py_DECREF(ev); -#else - { - PyObject* args = __Pyx_PyObject_GetAttrStr(ev, __pyx_n_s_args); - Py_DECREF(ev); - if (likely(args)) { - value = PySequence_GetItem(args, 0); - Py_DECREF(args); - } - if (unlikely(!value)) { - __Pyx_ErrRestore(NULL, NULL, NULL); - Py_INCREF(Py_None); - value = Py_None; - } - } -#endif - *pvalue = value; - return 0; -} -static CYTHON_INLINE -void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { - PyObject *t, *v, *tb; - t = exc_state->exc_type; - v = exc_state->exc_value; - tb = exc_state->exc_traceback; - exc_state->exc_type = NULL; - exc_state->exc_value = NULL; - exc_state->exc_traceback = NULL; - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); -} -#define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) -static void __Pyx__Coroutine_AlreadyRunningError(CYTHON_UNUSED __pyx_CoroutineObject *gen) { - const char *msg; - if ((0)) { - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { - msg = "coroutine already executing"; - #endif - #ifdef __Pyx_AsyncGen_USED - } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { - msg = "async generator already executing"; - #endif - } else { - msg = "generator already executing"; - } - PyErr_SetString(PyExc_ValueError, msg); -} -#define __Pyx_Coroutine_NotStartedError(gen) (__Pyx__Coroutine_NotStartedError(gen), (PyObject*)NULL) -static void __Pyx__Coroutine_NotStartedError(CYTHON_UNUSED PyObject *gen) { - const char *msg; - if ((0)) { - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_Coroutine_Check(gen)) { - msg = "can't send non-None value to a just-started coroutine"; - #endif - #ifdef __Pyx_AsyncGen_USED - } else if (__Pyx_AsyncGen_CheckExact(gen)) { - msg = "can't send non-None value to a just-started async generator"; - #endif - } else { - msg = "can't send non-None value to a just-started generator"; - } - PyErr_SetString(PyExc_TypeError, msg); -} -#define __Pyx_Coroutine_AlreadyTerminatedError(gen, value, closing) (__Pyx__Coroutine_AlreadyTerminatedError(gen, value, closing), (PyObject*)NULL) -static void __Pyx__Coroutine_AlreadyTerminatedError(CYTHON_UNUSED PyObject *gen, PyObject *value, CYTHON_UNUSED int closing) { - #ifdef __Pyx_Coroutine_USED - if (!closing && __Pyx_Coroutine_Check(gen)) { - PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); - } else - #endif - if (value) { - #ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(gen)) - PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration); - else - #endif - PyErr_SetNone(PyExc_StopIteration); - } -} -static -PyObject *__Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, int closing) { - __Pyx_PyThreadState_declare - PyThreadState *tstate; - __Pyx_ExcInfoStruct *exc_state; - PyObject *retval; - assert(!self->is_running); - if (unlikely(self->resume_label == 0)) { - if (unlikely(value && value != Py_None)) { - return __Pyx_Coroutine_NotStartedError((PyObject*)self); - } - } - if (unlikely(self->resume_label == -1)) { - return __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); - } -#if CYTHON_FAST_THREAD_STATE - __Pyx_PyThreadState_assign - tstate = __pyx_tstate; -#else - tstate = __Pyx_PyThreadState_Current; -#endif - exc_state = &self->gi_exc_state; - if (exc_state->exc_type) { - #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON - #else - if (exc_state->exc_traceback) { - PyTracebackObject *tb = (PyTracebackObject *) exc_state->exc_traceback; - PyFrameObject *f = tb->tb_frame; - assert(f->f_back == NULL); - #if PY_VERSION_HEX >= 0x030B00A1 - f->f_back = PyThreadState_GetFrame(tstate); - #else - Py_XINCREF(tstate->frame); - f->f_back = tstate->frame; - #endif - } - #endif - } -#if CYTHON_USE_EXC_INFO_STACK - exc_state->previous_item = tstate->exc_info; - tstate->exc_info = exc_state; -#else - if (exc_state->exc_type) { - __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); - } else { - __Pyx_Coroutine_ExceptionClear(exc_state); - __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); - } -#endif - self->is_running = 1; - retval = self->body((PyObject *) self, tstate, value); - self->is_running = 0; -#if CYTHON_USE_EXC_INFO_STACK - exc_state = &self->gi_exc_state; - tstate->exc_info = exc_state->previous_item; - exc_state->previous_item = NULL; - __Pyx_Coroutine_ResetFrameBackpointer(exc_state); -#endif - return retval; -} -static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { - PyObject *exc_tb = exc_state->exc_traceback; - if (likely(exc_tb)) { -#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON -#else - PyTracebackObject *tb = (PyTracebackObject *) exc_tb; - PyFrameObject *f = tb->tb_frame; - Py_CLEAR(f->f_back); -#endif - } -} -static CYTHON_INLINE -PyObject *__Pyx_Coroutine_MethodReturn(CYTHON_UNUSED PyObject* gen, PyObject *retval) { - if (unlikely(!retval)) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (!__Pyx_PyErr_Occurred()) { - PyObject *exc = PyExc_StopIteration; - #ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(gen)) - exc = __Pyx_PyExc_StopAsyncIteration; - #endif - __Pyx_PyErr_SetNone(exc); - } - } - return retval; -} -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) -static CYTHON_INLINE -PyObject *__Pyx_PyGen_Send(PyGenObject *gen, PyObject *arg) { -#if PY_VERSION_HEX <= 0x030A00A1 - return _PyGen_Send(gen, arg); -#else - PyObject *result; - if (PyIter_Send((PyObject*)gen, arg ? arg : Py_None, &result) == PYGEN_RETURN) { - if (PyAsyncGen_CheckExact(gen)) { - assert(result == Py_None); - PyErr_SetNone(PyExc_StopAsyncIteration); - } - else if (result == Py_None) { - PyErr_SetNone(PyExc_StopIteration); - } - else { - _PyGen_SetStopIterationValue(result); - } - Py_CLEAR(result); - } - return result; -#endif -} -#endif -static CYTHON_INLINE -PyObject *__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen) { - PyObject *ret; - PyObject *val = NULL; - __Pyx_Coroutine_Undelegate(gen); - __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); - ret = __Pyx_Coroutine_SendEx(gen, val, 0); - Py_XDECREF(val); - return ret; -} -static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { - PyObject *retval; - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; - PyObject *yf = gen->yieldfrom; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - PyObject *ret; - gen->is_running = 1; - #ifdef __Pyx_Generator_USED - if (__Pyx_Generator_CheckExact(yf)) { - ret = __Pyx_Coroutine_Send(yf, value); - } else - #endif - #ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(yf)) { - ret = __Pyx_Coroutine_Send(yf, value); - } else - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_PyAsyncGenASend_CheckExact(yf)) { - ret = __Pyx_async_gen_asend_send(yf, value); - } else - #endif - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) - if (PyGen_CheckExact(yf)) { - ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); - } else - #endif - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03050000 && defined(PyCoro_CheckExact) && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) - if (PyCoro_CheckExact(yf)) { - ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); - } else - #endif - { - if (value == Py_None) - ret = Py_TYPE(yf)->tp_iternext(yf); - else - ret = __Pyx_PyObject_CallMethod1(yf, __pyx_n_s_send, value); - } - gen->is_running = 0; - if (likely(ret)) { - return ret; - } - retval = __Pyx_Coroutine_FinishDelegation(gen); - } else { - retval = __Pyx_Coroutine_SendEx(gen, value, 0); - } - return __Pyx_Coroutine_MethodReturn(self, retval); -} -static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { - PyObject *retval = NULL; - int err = 0; - #ifdef __Pyx_Generator_USED - if (__Pyx_Generator_CheckExact(yf)) { - retval = __Pyx_Coroutine_Close(yf); - if (!retval) - return -1; - } else - #endif - #ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(yf)) { - retval = __Pyx_Coroutine_Close(yf); - if (!retval) - return -1; - } else - if (__Pyx_CoroutineAwait_CheckExact(yf)) { - retval = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf, NULL); - if (!retval) - return -1; - } else - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_PyAsyncGenASend_CheckExact(yf)) { - retval = __Pyx_async_gen_asend_close(yf, NULL); - } else - if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { - retval = __Pyx_async_gen_athrow_close(yf, NULL); - } else - #endif - { - PyObject *meth; - gen->is_running = 1; - meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_close); - if (unlikely(!meth)) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_WriteUnraisable(yf); - } - PyErr_Clear(); - } else { - retval = PyObject_CallFunction(meth, NULL); - Py_DECREF(meth); - if (!retval) - err = -1; - } - gen->is_running = 0; - } - Py_XDECREF(retval); - return err; -} -static PyObject *__Pyx_Generator_Next(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; - PyObject *yf = gen->yieldfrom; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - PyObject *ret; - gen->is_running = 1; - #ifdef __Pyx_Generator_USED - if (__Pyx_Generator_CheckExact(yf)) { - ret = __Pyx_Generator_Next(yf); - } else - #endif - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) - if (PyGen_CheckExact(yf)) { - ret = __Pyx_PyGen_Send((PyGenObject*)yf, NULL); - } else - #endif - #ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(yf)) { - ret = __Pyx_Coroutine_Send(yf, Py_None); - } else - #endif - ret = Py_TYPE(yf)->tp_iternext(yf); - gen->is_running = 0; - if (likely(ret)) { - return ret; - } - return __Pyx_Coroutine_FinishDelegation(gen); - } - return __Pyx_Coroutine_SendEx(gen, Py_None, 0); -} -static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, CYTHON_UNUSED PyObject *arg) { - return __Pyx_Coroutine_Close(self); -} -static PyObject *__Pyx_Coroutine_Close(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - PyObject *retval, *raised_exception; - PyObject *yf = gen->yieldfrom; - int err = 0; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - Py_INCREF(yf); - err = __Pyx_Coroutine_CloseIter(gen, yf); - __Pyx_Coroutine_Undelegate(gen); - Py_DECREF(yf); - } - if (err == 0) - PyErr_SetNone(PyExc_GeneratorExit); - retval = __Pyx_Coroutine_SendEx(gen, NULL, 1); - if (unlikely(retval)) { - const char *msg; - Py_DECREF(retval); - if ((0)) { - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_Coroutine_Check(self)) { - msg = "coroutine ignored GeneratorExit"; - #endif - #ifdef __Pyx_AsyncGen_USED - } else if (__Pyx_AsyncGen_CheckExact(self)) { -#if PY_VERSION_HEX < 0x03060000 - msg = "async generator ignored GeneratorExit - might require Python 3.6+ finalisation (PEP 525)"; -#else - msg = "async generator ignored GeneratorExit"; -#endif - #endif - } else { - msg = "generator ignored GeneratorExit"; - } - PyErr_SetString(PyExc_RuntimeError, msg); - return NULL; - } - raised_exception = PyErr_Occurred(); - if (likely(!raised_exception || __Pyx_PyErr_GivenExceptionMatches2(raised_exception, PyExc_GeneratorExit, PyExc_StopIteration))) { - if (raised_exception) PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - return NULL; -} -static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, - PyObject *args, int close_on_genexit) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - PyObject *yf = gen->yieldfrom; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - PyObject *ret; - Py_INCREF(yf); - if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { - int err = __Pyx_Coroutine_CloseIter(gen, yf); - Py_DECREF(yf); - __Pyx_Coroutine_Undelegate(gen); - if (err < 0) - return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); - goto throw_here; - } - gen->is_running = 1; - if (0 - #ifdef __Pyx_Generator_USED - || __Pyx_Generator_CheckExact(yf) - #endif - #ifdef __Pyx_Coroutine_USED - || __Pyx_Coroutine_Check(yf) - #endif - ) { - ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { - ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); - #endif - } else { - PyObject *meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_throw); - if (unlikely(!meth)) { - Py_DECREF(yf); - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { - gen->is_running = 0; - return NULL; - } - PyErr_Clear(); - __Pyx_Coroutine_Undelegate(gen); - gen->is_running = 0; - goto throw_here; - } - if (likely(args)) { - ret = PyObject_CallObject(meth, args); - } else { - ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL); - } - Py_DECREF(meth); - } - gen->is_running = 0; - Py_DECREF(yf); - if (!ret) { - ret = __Pyx_Coroutine_FinishDelegation(gen); - } - return __Pyx_Coroutine_MethodReturn(self, ret); - } -throw_here: - __Pyx_Raise(typ, val, tb, NULL); - return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); -} -static PyObject *__Pyx_Coroutine_Throw(PyObject *self, PyObject *args) { - PyObject *typ; - PyObject *val = NULL; - PyObject *tb = NULL; - if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb)) - return NULL; - return __Pyx__Coroutine_Throw(self, typ, val, tb, args, 1); -} -static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { - Py_VISIT(exc_state->exc_type); - Py_VISIT(exc_state->exc_value); - Py_VISIT(exc_state->exc_traceback); - return 0; -} -static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { - Py_VISIT(gen->closure); - Py_VISIT(gen->classobj); - Py_VISIT(gen->yieldfrom); - return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); -} -static int __Pyx_Coroutine_clear(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - Py_CLEAR(gen->closure); - Py_CLEAR(gen->classobj); - Py_CLEAR(gen->yieldfrom); - __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); -#ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(self)) { - Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); - } -#endif - Py_CLEAR(gen->gi_code); - Py_CLEAR(gen->gi_frame); - Py_CLEAR(gen->gi_name); - Py_CLEAR(gen->gi_qualname); - Py_CLEAR(gen->gi_modulename); - return 0; -} -static void __Pyx_Coroutine_dealloc(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - PyObject_GC_UnTrack(gen); - if (gen->gi_weakreflist != NULL) - PyObject_ClearWeakRefs(self); - if (gen->resume_label >= 0) { - PyObject_GC_Track(self); -#if PY_VERSION_HEX >= 0x030400a1 && CYTHON_USE_TP_FINALIZE - if (PyObject_CallFinalizerFromDealloc(self)) -#else - Py_TYPE(gen)->tp_del(self); - if (Py_REFCNT(self) > 0) -#endif - { - return; - } - PyObject_GC_UnTrack(self); - } -#ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(self)) { - /* We have to handle this case for asynchronous generators - right here, because this code has to be between UNTRACK - and GC_Del. */ - Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); - } -#endif - __Pyx_Coroutine_clear(self); - PyObject_GC_Del(gen); -} -static void __Pyx_Coroutine_del(PyObject *self) { - PyObject *error_type, *error_value, *error_traceback; - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - __Pyx_PyThreadState_declare - if (gen->resume_label < 0) { - return; - } -#if !CYTHON_USE_TP_FINALIZE - assert(self->ob_refcnt == 0); - __Pyx_SET_REFCNT(self, 1); -#endif - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); -#ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(self)) { - __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; - PyObject *finalizer = agen->ag_finalizer; - if (finalizer && !agen->ag_closed) { - PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); - if (unlikely(!res)) { - PyErr_WriteUnraisable(self); - } else { - Py_DECREF(res); - } - __Pyx_ErrRestore(error_type, error_value, error_traceback); - return; - } - } -#endif - if (unlikely(gen->resume_label == 0 && !error_value)) { -#ifdef __Pyx_Coroutine_USED -#ifdef __Pyx_Generator_USED - if (!__Pyx_Generator_CheckExact(self)) -#endif - { - PyObject_GC_UnTrack(self); -#if PY_MAJOR_VERSION >= 3 || defined(PyErr_WarnFormat) - if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) - PyErr_WriteUnraisable(self); -#else - {PyObject *msg; - char *cmsg; - #if CYTHON_COMPILING_IN_PYPY - msg = NULL; - cmsg = (char*) "coroutine was never awaited"; - #else - char *cname; - PyObject *qualname; - qualname = gen->gi_qualname; - cname = PyString_AS_STRING(qualname); - msg = PyString_FromFormat("coroutine '%.50s' was never awaited", cname); - if (unlikely(!msg)) { - PyErr_Clear(); - cmsg = (char*) "coroutine was never awaited"; - } else { - cmsg = PyString_AS_STRING(msg); - } - #endif - if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, cmsg, 1) < 0)) - PyErr_WriteUnraisable(self); - Py_XDECREF(msg);} -#endif - PyObject_GC_Track(self); - } -#endif - } else { - PyObject *res = __Pyx_Coroutine_Close(self); - if (unlikely(!res)) { - if (PyErr_Occurred()) - PyErr_WriteUnraisable(self); - } else { - Py_DECREF(res); - } - } - __Pyx_ErrRestore(error_type, error_value, error_traceback); -#if !CYTHON_USE_TP_FINALIZE - assert(Py_REFCNT(self) > 0); - if (--self->ob_refcnt == 0) { - return; - } - { - Py_ssize_t refcnt = Py_REFCNT(self); - _Py_NewReference(self); - __Pyx_SET_REFCNT(self, refcnt); - } -#if CYTHON_COMPILING_IN_CPYTHON - assert(PyType_IS_GC(Py_TYPE(self)) && - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - _Py_DEC_REFTOTAL; -#endif -#ifdef COUNT_ALLOCS - --Py_TYPE(self)->tp_frees; - --Py_TYPE(self)->tp_allocs; -#endif -#endif -} -static PyObject * -__Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) -{ - PyObject *name = self->gi_name; - if (unlikely(!name)) name = Py_None; - Py_INCREF(name); - return name; -} -static int -__Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else - if (unlikely(value == NULL || !PyString_Check(value))) -#endif - { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = self->gi_name; - Py_INCREF(value); - self->gi_name = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) -{ - PyObject *name = self->gi_qualname; - if (unlikely(!name)) name = Py_None; - Py_INCREF(name); - return name; -} -static int -__Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else - if (unlikely(value == NULL || !PyString_Check(value))) -#endif - { - PyErr_SetString(PyExc_TypeError, - "__qualname__ must be set to a string object"); - return -1; - } - tmp = self->gi_qualname; - Py_INCREF(value); - self->gi_qualname = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_Coroutine_get_frame(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) -{ - PyObject *frame = self->gi_frame; - if (!frame) { - if (unlikely(!self->gi_code)) { - Py_RETURN_NONE; - } - frame = (PyObject *) PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ - (PyCodeObject*) self->gi_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (unlikely(!frame)) - return NULL; - self->gi_frame = frame; - } - Py_INCREF(frame); - return frame; -} -static __pyx_CoroutineObject *__Pyx__Coroutine_New( - PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name) { - __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); - if (unlikely(!gen)) - return NULL; - return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); -} -static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( - __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name) { - gen->body = body; - gen->closure = closure; - Py_XINCREF(closure); - gen->is_running = 0; - gen->resume_label = 0; - gen->classobj = NULL; - gen->yieldfrom = NULL; - gen->gi_exc_state.exc_type = NULL; - gen->gi_exc_state.exc_value = NULL; - gen->gi_exc_state.exc_traceback = NULL; -#if CYTHON_USE_EXC_INFO_STACK - gen->gi_exc_state.previous_item = NULL; -#endif - gen->gi_weakreflist = NULL; - Py_XINCREF(qualname); - gen->gi_qualname = qualname; - Py_XINCREF(name); - gen->gi_name = name; - Py_XINCREF(module_name); - gen->gi_modulename = module_name; - Py_XINCREF(code); - gen->gi_code = code; - gen->gi_frame = NULL; - PyObject_GC_Track(gen); - return gen; -} - -/* 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 - -/* PatchModuleWithCoroutine */ -static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code) { -#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - int result; - PyObject *globals, *result_obj; - globals = PyDict_New(); if (unlikely(!globals)) goto ignore; - result = PyDict_SetItemString(globals, "_cython_coroutine_type", - #ifdef __Pyx_Coroutine_USED - (PyObject*)__pyx_CoroutineType); - #else - Py_None); - #endif - if (unlikely(result < 0)) goto ignore; - result = PyDict_SetItemString(globals, "_cython_generator_type", - #ifdef __Pyx_Generator_USED - (PyObject*)__pyx_GeneratorType); - #else - Py_None); - #endif - if (unlikely(result < 0)) goto ignore; - if (unlikely(PyDict_SetItemString(globals, "_module", module) < 0)) goto ignore; - if (unlikely(PyDict_SetItemString(globals, "__builtins__", __pyx_b) < 0)) goto ignore; - result_obj = PyRun_String(py_code, Py_file_input, globals, globals); - if (unlikely(!result_obj)) goto ignore; - Py_DECREF(result_obj); - Py_DECREF(globals); - return module; -ignore: - Py_XDECREF(globals); - PyErr_WriteUnraisable(module); - if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch module with custom type", 1) < 0)) { - Py_DECREF(module); - module = NULL; - } -#else - py_code++; -#endif - return module; -} - -/* PatchGeneratorABC */ -#ifndef CYTHON_REGISTER_ABCS -#define CYTHON_REGISTER_ABCS 1 -#endif -#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) -static PyObject* __Pyx_patch_abc_module(PyObject *module); -static PyObject* __Pyx_patch_abc_module(PyObject *module) { - module = __Pyx_Coroutine_patch_module( - module, "" -"if _cython_generator_type is not None:\n" -" try: Generator = _module.Generator\n" -" except AttributeError: pass\n" -" else: Generator.register(_cython_generator_type)\n" -"if _cython_coroutine_type is not None:\n" -" try: Coroutine = _module.Coroutine\n" -" except AttributeError: pass\n" -" else: Coroutine.register(_cython_coroutine_type)\n" - ); - return module; -} -#endif -static int __Pyx_patch_abc(void) { -#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - static int abc_patched = 0; - if (CYTHON_REGISTER_ABCS && !abc_patched) { - PyObject *module; - module = PyImport_ImportModule((PY_MAJOR_VERSION >= 3) ? "collections.abc" : "collections"); - if (!module) { - PyErr_WriteUnraisable(NULL); - if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, - ((PY_MAJOR_VERSION >= 3) ? - "Cython module failed to register with collections.abc module" : - "Cython module failed to register with collections module"), 1) < 0)) { - return -1; - } - } else { - module = __Pyx_patch_abc_module(module); - abc_patched = 1; - if (unlikely(!module)) - return -1; - Py_DECREF(module); - } - module = PyImport_ImportModule("backports_abc"); - if (module) { - module = __Pyx_patch_abc_module(module); - Py_XDECREF(module); - } - if (!module) { - PyErr_Clear(); - } - } -#else - if ((0)) __Pyx_Coroutine_patch_module(NULL, NULL); -#endif - return 0; -} - -/* Generator */ -static PyMethodDef __pyx_Generator_methods[] = { - {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, - (char*) PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, - {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS, - (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, - {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, - (char*) PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, - {0, 0, 0, 0} -}; -static PyMemberDef __pyx_Generator_memberlist[] = { - {(char *) "gi_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL}, - {(char*) "gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, - (char*) PyDoc_STR("object being iterated by 'yield from', or None")}, - {(char*) "gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, - {0, 0, 0, 0, 0} -}; -static PyGetSetDef __pyx_Generator_getsets[] = { - {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, - (char*) PyDoc_STR("name of the generator"), 0}, - {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, - (char*) PyDoc_STR("qualified name of the generator"), 0}, - {(char *) "gi_frame", (getter)__Pyx_Coroutine_get_frame, NULL, - (char*) PyDoc_STR("Frame of the generator"), 0}, - {0, 0, 0, 0, 0} -}; -static PyTypeObject __pyx_GeneratorType_type = { - PyVarObject_HEAD_INIT(0, 0) - "generator", - sizeof(__pyx_CoroutineObject), - 0, - (destructor) __Pyx_Coroutine_dealloc, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, - 0, - (traverseproc) __Pyx_Coroutine_traverse, - 0, - 0, - offsetof(__pyx_CoroutineObject, gi_weakreflist), - 0, - (iternextfunc) __Pyx_Generator_Next, - __pyx_Generator_methods, - __pyx_Generator_memberlist, - __pyx_Generator_getsets, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, -#if CYTHON_USE_TP_FINALIZE - 0, -#else - __Pyx_Coroutine_del, -#endif - 0, -#if CYTHON_USE_TP_FINALIZE - __Pyx_Coroutine_del, -#elif PY_VERSION_HEX >= 0x030400a1 - 0, -#endif -#if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, -#endif -#if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, -#endif -#if PY_VERSION_HEX >= 0x030C0000 - 0, -#endif -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, -#endif -}; -static int __pyx_Generator_init(void) { - __pyx_GeneratorType_type.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter; - __pyx_GeneratorType = __Pyx_FetchCommonType(&__pyx_GeneratorType_type); - if (unlikely(!__pyx_GeneratorType)) { - return -1; - } - return 0; -} - -/* GeneratorYieldFrom */ -static void __PyxPyIter_CheckErrorAndDecref(PyObject *source) { - PyErr_Format(PyExc_TypeError, - "iter() returned non-iterator of type '%.100s'", - Py_TYPE(source)->tp_name); - Py_DECREF(source); -} -static CYTHON_INLINE PyObject* __Pyx_Generator_Yield_From(__pyx_CoroutineObject *gen, PyObject *source) { - PyObject *source_gen, *retval; -#ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(source)) { - Py_INCREF(source); - source_gen = source; - retval = __Pyx_Generator_Next(source); - } else -#endif - { -#if CYTHON_USE_TYPE_SLOTS - if (likely(Py_TYPE(source)->tp_iter)) { - source_gen = Py_TYPE(source)->tp_iter(source); - if (unlikely(!source_gen)) - return NULL; - if (unlikely(!PyIter_Check(source_gen))) { - __PyxPyIter_CheckErrorAndDecref(source_gen); - return NULL; - } - } else -#endif - { - source_gen = PyObject_GetIter(source); - if (unlikely(!source_gen)) - return NULL; - } -#if CYTHON_USE_TYPE_SLOTS - retval = Py_TYPE(source_gen)->tp_iternext(source_gen); -#else - retval = PyIter_Next(source_gen); -#endif - } - if (likely(retval)) { - gen->yieldfrom = source_gen; - return retval; - } - Py_DECREF(source_gen); - return NULL; -} - -/* append */ -static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x) { - if (likely(PyList_CheckExact(L))) { - if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return -1; - } else { - PyObject* retval = __Pyx_PyObject_CallMethod1(L, __pyx_n_s_append, x); - if (unlikely(!retval)) - return -1; - Py_DECREF(retval); - } - return 0; -} - -/* PyIntBinop */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { - (void)inplace; - (void)zerodivision_check; - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long x; - long a = PyInt_AS_LONG(op1); - x = (long)((unsigned long)a + b); - if (likely((x^a) >= 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 - -/* py_abs */ -#if CYTHON_USE_PYLONG_INTERNALS -static PyObject *__Pyx_PyLong_AbsNeg(PyObject *n) { - if (likely(Py_SIZE(n) == -1)) { - return PyLong_FromLong(((PyLongObject*)n)->ob_digit[0]); - } -#if CYTHON_COMPILING_IN_CPYTHON - { - PyObject *copy = _PyLong_Copy((PyLongObject*)n); - if (likely(copy)) { - __Pyx_SET_SIZE(copy, -Py_SIZE(copy)); - } - return copy; - } -#else - return PyNumber_Negative(n); -#endif -} -#endif - -/* PyFloatBinop */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyFloat_TrueDivideObjC(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check) { - const double b = floatval; - double a, result; - (void)inplace; - (void)zerodivision_check; - if (likely(PyFloat_CheckExact(op1))) { - a = PyFloat_AS_DOUBLE(op1); - - } else - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - a = (double) PyInt_AS_LONG(op1); - - } else - #endif - if (likely(PyLong_CheckExact(op1))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - switch (size) { - case 0: a = 0.0; break; - case -1: a = -(double) digits[0]; break; - case 1: a = (double) digits[0]; break; - case -2: - case 2: - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (1 * PyLong_SHIFT < 53))) { - a = (double) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - if ((8 * sizeof(unsigned long) < 53) || (2 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { - if (size == -2) - a = -a; - break; - } - } - CYTHON_FALLTHROUGH; - case -3: - case 3: - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (2 * PyLong_SHIFT < 53))) { - a = (double) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - if ((8 * sizeof(unsigned long) < 53) || (3 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { - if (size == -3) - a = -a; - break; - } - } - CYTHON_FALLTHROUGH; - case -4: - case 4: - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (3 * PyLong_SHIFT < 53))) { - a = (double) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - if ((8 * sizeof(unsigned long) < 53) || (4 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { - if (size == -4) - a = -a; - break; - } - } - CYTHON_FALLTHROUGH; - default: - #else - { - #endif - a = PyLong_AsDouble(op1); - if (unlikely(a == -1.0 && PyErr_Occurred())) return NULL; - - } - } else { - return (inplace ? PyNumber_InPlaceTrueDivide : PyNumber_TrueDivide)(op1, op2); - } - - PyFPE_START_PROTECT("divide", return NULL) - result = a / b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); -} -#endif - -/* PyFloatBinop */ - #if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyFloat_EqObjC(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check) { - const double b = floatval; - double a; - (void)inplace; - (void)zerodivision_check; - if (op1 == op2) { - Py_RETURN_TRUE; - } - if (likely(PyFloat_CheckExact(op1))) { - a = PyFloat_AS_DOUBLE(op1); - - } else - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - a = (double) PyInt_AS_LONG(op1); - - } else - #endif - if (likely(PyLong_CheckExact(op1))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - switch (size) { - case 0: a = 0.0; break; - case -1: a = -(double) digits[0]; break; - case 1: a = (double) digits[0]; break; - case -2: - case 2: - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (1 * PyLong_SHIFT < 53))) { - a = (double) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - if ((8 * sizeof(unsigned long) < 53) || (2 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { - if (size == -2) - a = -a; - break; - } - } - CYTHON_FALLTHROUGH; - case -3: - case 3: - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (2 * PyLong_SHIFT < 53))) { - a = (double) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - if ((8 * sizeof(unsigned long) < 53) || (3 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { - if (size == -3) - a = -a; - break; - } - } - CYTHON_FALLTHROUGH; - case -4: - case 4: - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (3 * PyLong_SHIFT < 53))) { - a = (double) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - if ((8 * sizeof(unsigned long) < 53) || (4 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { - if (size == -4) - a = -a; - break; - } - } - CYTHON_FALLTHROUGH; - default: - #else - { - #endif - return ( - PyFloat_Type.tp_richcompare(op2, op1, Py_EQ)); - } - } else { - return ( - PyObject_RichCompare(op1, op2, Py_EQ)); - } - if (a == b) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } -} -#endif - -/* RaiseNoneIterError */ - static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* PyIntBinop */ - #if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_SubtractCObj(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { - (void)inplace; - (void)zerodivision_check; - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op2))) { - const long a = intval; - long x; - long b = PyInt_AS_LONG(op2); - x = (long)((unsigned long)a - b); - if (likely((x^a) >= 0 || (x^~b) >= 0)) - return PyInt_FromLong(x); - return PyLong_Type.tp_as_number->nb_subtract(op1, op2); - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op2))) { - const long a = intval; - long b, x; -#ifdef HAVE_LONG_LONG - const PY_LONG_LONG lla = intval; - PY_LONG_LONG llb, llx; -#endif - const digit* digits = ((PyLongObject*)op2)->ob_digit; - const Py_ssize_t size = Py_SIZE(op2); - if (likely(__Pyx_sst_abs(size) <= 1)) { - b = likely(size) ? digits[0] : 0; - if (size == -1) b = -b; - } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - b = -(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) { - llb = -(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) { - b = (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) { - llb = (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) { - b = -(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) { - llb = -(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) { - b = (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) { - llb = (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) { - b = -(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) { - llb = -(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) { - b = (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) { - llb = (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_subtract(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(op2)) { - const long a = intval; - double b = PyFloat_AS_DOUBLE(op2); - double result; - PyFPE_START_PROTECT("subtract", return NULL) - result = ((double)a) - (double)b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); - } - return (inplace ? PyNumber_InPlaceSubtract : PyNumber_Subtract)(op1, op2); -} -#endif - -/* CythonFunctionShared */ - #include -static PyObject * -__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) -{ - if (unlikely(op->func_doc == NULL)) { - if (op->func.m_ml->ml_doc) { -#if PY_MAJOR_VERSION >= 3 - op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); -#else - op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); -#endif - if (unlikely(op->func_doc == NULL)) - return NULL; - } else { - Py_INCREF(Py_None); - return Py_None; - } - } - Py_INCREF(op->func_doc); - return op->func_doc; -} -static int -__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp = op->func_doc; - if (value == NULL) { - value = Py_None; - } - Py_INCREF(value); - op->func_doc = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - if (unlikely(op->func_name == NULL)) { -#if PY_MAJOR_VERSION >= 3 - op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); -#else - op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); -#endif - if (unlikely(op->func_name == NULL)) - return NULL; - } - Py_INCREF(op->func_name); - return op->func_name; -} -static int -__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else - if (unlikely(value == NULL || !PyString_Check(value))) -#endif - { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = op->func_name; - Py_INCREF(value); - op->func_name = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - Py_INCREF(op->func_qualname); - return op->func_qualname; -} -static int -__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else - if (unlikely(value == NULL || !PyString_Check(value))) -#endif - { - PyErr_SetString(PyExc_TypeError, - "__qualname__ must be set to a string object"); - return -1; - } - tmp = op->func_qualname; - Py_INCREF(value); - op->func_qualname = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) -{ - PyObject *self; - self = m->func_closure; - if (self == NULL) - self = Py_None; - Py_INCREF(self); - return self; -} -static PyObject * -__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - if (unlikely(op->func_dict == NULL)) { - op->func_dict = PyDict_New(); - if (unlikely(op->func_dict == NULL)) - return NULL; - } - Py_INCREF(op->func_dict); - return op->func_dict; -} -static int -__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; - if (unlikely(value == NULL)) { - PyErr_SetString(PyExc_TypeError, - "function's dictionary may not be deleted"); - return -1; - } - if (unlikely(!PyDict_Check(value))) { - PyErr_SetString(PyExc_TypeError, - "setting function's dictionary to a non-dict"); - return -1; - } - tmp = op->func_dict; - Py_INCREF(value); - op->func_dict = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - Py_INCREF(op->func_globals); - return op->func_globals; -} -static PyObject * -__Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - Py_INCREF(Py_None); - return Py_None; -} -static PyObject * -__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - PyObject* result = (op->func_code) ? op->func_code : Py_None; - Py_INCREF(result); - return result; -} -static int -__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { - int result = 0; - PyObject *res = op->defaults_getter((PyObject *) op); - if (unlikely(!res)) - return -1; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - op->defaults_tuple = PyTuple_GET_ITEM(res, 0); - Py_INCREF(op->defaults_tuple); - op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); - Py_INCREF(op->defaults_kwdict); - #else - op->defaults_tuple = PySequence_ITEM(res, 0); - if (unlikely(!op->defaults_tuple)) result = -1; - else { - op->defaults_kwdict = PySequence_ITEM(res, 1); - if (unlikely(!op->defaults_kwdict)) result = -1; - } - #endif - Py_DECREF(res); - return result; -} -static int -__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { - PyObject* tmp; - if (!value) { - value = Py_None; - } else if (value != Py_None && !PyTuple_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__defaults__ must be set to a tuple object"); - return -1; - } - Py_INCREF(value); - tmp = op->defaults_tuple; - op->defaults_tuple = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { - PyObject* result = op->defaults_tuple; - if (unlikely(!result)) { - if (op->defaults_getter) { - if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; - result = op->defaults_tuple; - } else { - result = Py_None; - } - } - Py_INCREF(result); - return result; -} -static int -__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { - PyObject* tmp; - if (!value) { - value = Py_None; - } else if (value != Py_None && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__kwdefaults__ must be set to a dict object"); - return -1; - } - Py_INCREF(value); - tmp = op->defaults_kwdict; - op->defaults_kwdict = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { - PyObject* result = op->defaults_kwdict; - if (unlikely(!result)) { - if (op->defaults_getter) { - if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; - result = op->defaults_kwdict; - } else { - result = Py_None; - } - } - Py_INCREF(result); - return result; -} -static int -__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { - PyObject* tmp; - if (!value || value == Py_None) { - value = NULL; - } else if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__annotations__ must be set to a dict object"); - return -1; - } - Py_XINCREF(value); - tmp = op->func_annotations; - op->func_annotations = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { - PyObject* result = op->func_annotations; - if (unlikely(!result)) { - result = PyDict_New(); - if (unlikely(!result)) return NULL; - op->func_annotations = result; - } - Py_INCREF(result); - return result; -} -static PyGetSetDef __pyx_CyFunction_getsets[] = { - {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, - {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, - {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, - {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, - {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, - {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, - {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, - {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, - {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, - {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, - {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, - {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, - {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, - {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, - {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, - {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, - {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, - {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, - {0, 0, 0, 0, 0} -}; -static PyMemberDef __pyx_CyFunction_members[] = { - {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), PY_WRITE_RESTRICTED, 0}, - {0, 0, 0, 0, 0} -}; -static PyObject * -__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) -{ -#if PY_MAJOR_VERSION >= 3 - Py_INCREF(m->func_qualname); - return m->func_qualname; -#else - return PyString_FromString(m->func.m_ml->ml_name); -#endif -} -static PyMethodDef __pyx_CyFunction_methods[] = { - {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, - {0, 0, 0, 0} -}; -#if PY_VERSION_HEX < 0x030500A0 -#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) -#else -#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func.m_weakreflist) -#endif -static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, - PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { - if (unlikely(op == NULL)) - return NULL; - op->flags = flags; - __Pyx_CyFunction_weakreflist(op) = NULL; - op->func.m_ml = ml; - op->func.m_self = (PyObject *) op; - Py_XINCREF(closure); - op->func_closure = closure; - Py_XINCREF(module); - op->func.m_module = module; - op->func_dict = NULL; - op->func_name = NULL; - Py_INCREF(qualname); - op->func_qualname = qualname; - op->func_doc = NULL; - op->func_classobj = NULL; - op->func_globals = globals; - Py_INCREF(op->func_globals); - Py_XINCREF(code); - op->func_code = code; - op->defaults_pyobjects = 0; - op->defaults_size = 0; - op->defaults = NULL; - op->defaults_tuple = NULL; - op->defaults_kwdict = NULL; - op->defaults_getter = NULL; - op->func_annotations = NULL; - return (PyObject *) op; -} -static int -__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) -{ - Py_CLEAR(m->func_closure); - Py_CLEAR(m->func.m_module); - Py_CLEAR(m->func_dict); - Py_CLEAR(m->func_name); - Py_CLEAR(m->func_qualname); - Py_CLEAR(m->func_doc); - Py_CLEAR(m->func_globals); - Py_CLEAR(m->func_code); - Py_CLEAR(m->func_classobj); - Py_CLEAR(m->defaults_tuple); - Py_CLEAR(m->defaults_kwdict); - Py_CLEAR(m->func_annotations); - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); - int i; - for (i = 0; i < m->defaults_pyobjects; i++) - Py_XDECREF(pydefaults[i]); - PyObject_Free(m->defaults); - m->defaults = NULL; - } - return 0; -} -static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) -{ - if (__Pyx_CyFunction_weakreflist(m) != NULL) - PyObject_ClearWeakRefs((PyObject *) m); - __Pyx_CyFunction_clear(m); - PyObject_GC_Del(m); -} -static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) -{ - PyObject_GC_UnTrack(m); - __Pyx__CyFunction_dealloc(m); -} -static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) -{ - Py_VISIT(m->func_closure); - Py_VISIT(m->func.m_module); - Py_VISIT(m->func_dict); - Py_VISIT(m->func_name); - Py_VISIT(m->func_qualname); - Py_VISIT(m->func_doc); - Py_VISIT(m->func_globals); - Py_VISIT(m->func_code); - Py_VISIT(m->func_classobj); - Py_VISIT(m->defaults_tuple); - Py_VISIT(m->defaults_kwdict); - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); - int i; - for (i = 0; i < m->defaults_pyobjects; i++) - Py_VISIT(pydefaults[i]); - } - return 0; -} -static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) -{ -#if PY_MAJOR_VERSION < 3 - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { - Py_INCREF(func); - return func; - } - if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); - return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); - } - if (obj == Py_None) - obj = NULL; -#endif - return __Pyx_PyMethod_New(func, obj, type); -} -static PyObject* -__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) -{ -#if PY_MAJOR_VERSION >= 3 - return PyUnicode_FromFormat("", - op->func_qualname, (void *)op); -#else - return PyString_FromFormat("", - PyString_AsString(op->func_qualname), (void *)op); -#endif -} -static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { - PyCFunctionObject* f = (PyCFunctionObject*)func; - PyCFunction meth = f->m_ml->ml_meth; - Py_ssize_t size; - switch (f->m_ml->ml_flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { - case METH_VARARGS: - if (likely(kw == NULL || PyDict_Size(kw) == 0)) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: - return (*(PyCFunctionWithKeywords)(void*)meth)(self, arg, kw); - case METH_NOARGS: - if (likely(kw == NULL || PyDict_Size(kw) == 0)) { - size = PyTuple_GET_SIZE(arg); - if (likely(size == 0)) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - case METH_O: - if (likely(kw == NULL || PyDict_Size(kw) == 0)) { - size = PyTuple_GET_SIZE(arg); - if (likely(size == 1)) { - PyObject *result, *arg0; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - arg0 = PyTuple_GET_ITEM(arg, 0); - #else - arg0 = PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; - #endif - result = (*meth)(self, arg0); - #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) - Py_DECREF(arg0); - #endif - return result; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "__Pyx_CyFunction_Call. METH_OLDARGS is no " - "longer supported!"); - return NULL; - } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; -} -static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - return __Pyx_CyFunction_CallMethod(func, ((PyCFunctionObject*)func)->m_self, arg, kw); -} -static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { - PyObject *result; - __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; - if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { - Py_ssize_t argc; - PyObject *new_args; - PyObject *self; - argc = PyTuple_GET_SIZE(args); - new_args = PyTuple_GetSlice(args, 1, argc); - if (unlikely(!new_args)) - return NULL; - self = PyTuple_GetItem(args, 0); - if (unlikely(!self)) { - Py_DECREF(new_args); -#if PY_MAJOR_VERSION > 2 - PyErr_Format(PyExc_TypeError, - "unbound method %.200S() needs an argument", - cyfunc->func_qualname); -#else - PyErr_SetString(PyExc_TypeError, - "unbound method needs an argument"); -#endif - return NULL; - } - result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); - Py_DECREF(new_args); - } else { - result = __Pyx_CyFunction_Call(func, args, kw); - } - return result; -} -static PyTypeObject __pyx_CyFunctionType_type = { - PyVarObject_HEAD_INIT(0, 0) - "cython_function_or_method", - sizeof(__pyx_CyFunctionObject), - 0, - (destructor) __Pyx_CyFunction_dealloc, - 0, - 0, - 0, -#if PY_MAJOR_VERSION < 3 - 0, -#else - 0, -#endif - (reprfunc) __Pyx_CyFunction_repr, - 0, - 0, - 0, - 0, - __Pyx_CyFunction_CallAsMethod, - 0, - 0, - 0, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, - 0, - (traverseproc) __Pyx_CyFunction_traverse, - (inquiry) __Pyx_CyFunction_clear, - 0, -#if PY_VERSION_HEX < 0x030500A0 - offsetof(__pyx_CyFunctionObject, func_weakreflist), -#else - offsetof(PyCFunctionObject, m_weakreflist), -#endif - 0, - 0, - __pyx_CyFunction_methods, - __pyx_CyFunction_members, - __pyx_CyFunction_getsets, - 0, - 0, - __Pyx_CyFunction_descr_get, - 0, - offsetof(__pyx_CyFunctionObject, func_dict), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, -#if PY_VERSION_HEX >= 0x030400a1 - 0, -#endif -#if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, -#endif -#if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, -#endif -#if PY_VERSION_HEX >= 0x030C0000 - 0, -#endif -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, -#endif -}; -static int __pyx_CyFunction_init(void) { - __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); - if (unlikely(__pyx_CyFunctionType == NULL)) { - return -1; - } - return 0; -} -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults = PyObject_Malloc(size); - if (unlikely(!m->defaults)) - return PyErr_NoMemory(); - memset(m->defaults, 0, size); - m->defaults_pyobjects = pyobjects; - m->defaults_size = size; - return m->defaults; -} -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_tuple = tuple; - Py_INCREF(tuple); -} -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_kwdict = dict; - Py_INCREF(dict); -} -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->func_annotations = dict; - Py_INCREF(dict); -} - -/* CythonFunction */ - static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, - PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { - PyObject *op = __Pyx_CyFunction_Init( - PyObject_GC_New(__pyx_CyFunctionObject, __pyx_CyFunctionType), - ml, flags, qualname, closure, module, globals, code - ); - if (likely(op)) { - PyObject_GC_Track(op); - } - return op; -} - -/* pyfrozenset_new */ - static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { - if (it) { - PyObject* result; -#if CYTHON_COMPILING_IN_PYPY - PyObject* args; - args = PyTuple_Pack(1, it); - if (unlikely(!args)) - return NULL; - result = PyObject_Call((PyObject*)&PyFrozenSet_Type, args, NULL); - Py_DECREF(args); - return result; -#else - if (PyFrozenSet_CheckExact(it)) { - Py_INCREF(it); - return it; - } - result = PyFrozenSet_New(it); - if (unlikely(!result)) - return NULL; - if ((PY_VERSION_HEX >= 0x031000A1) || likely(PySet_GET_SIZE(result))) - return result; - Py_DECREF(result); -#endif - } -#if CYTHON_USE_TYPE_SLOTS - return PyFrozenSet_Type.tp_new(&PyFrozenSet_Type, __pyx_empty_tuple, NULL); -#else - return PyObject_Call((PyObject*)&PyFrozenSet_Type, __pyx_empty_tuple, NULL); -#endif -} - -/* PySetContains */ - static int __Pyx_PySet_ContainsUnhashable(PyObject *set, PyObject *key) { - int result = -1; - if (PySet_Check(key) && PyErr_ExceptionMatches(PyExc_TypeError)) { - PyObject *tmpkey; - PyErr_Clear(); - tmpkey = __Pyx_PyFrozenSet_New(key); - if (tmpkey != NULL) { - result = PySet_Contains(set, tmpkey); - Py_DECREF(tmpkey); - } - } - return result; -} -static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq) { - int result = PySet_Contains(set, key); - if (unlikely(result < 0)) { - result = __Pyx_PySet_ContainsUnhashable(set, key); - } - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* 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 - -/* 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; -} - -/* 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; -} - -/* 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; -} - -/* 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_VERSION_HEX < 0x030B0000) - 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 -} - -/* PyObjectCallNoArg */ - #if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, NULL, 0); - } -#endif -#if defined(__Pyx_CyFunction_USED) && defined(NDEBUG) - if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) -#else - if (likely(PyCFunction_Check(func))) -#endif - { - if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { - return __Pyx_PyObject_CallMethO(func, NULL); - } - } - return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); -} -#endif - -/* CLineInTraceback */ - #ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_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; - (void) 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" -#if PY_VERSION_HEX >= 0x030b00a6 - #ifndef Py_BUILD_CORE - #define Py_BUILD_CORE 1 - #endif - #include "internal/pycore_frame.h" -#endif -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = NULL; - PyObject *py_funcname = NULL; - #if PY_MAJOR_VERSION < 3 - PyObject *py_srcfile = NULL; - py_srcfile = PyString_FromString(filename); - if (!py_srcfile) goto bad; - #endif - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - if (!py_funcname) goto bad; - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - if (!py_funcname) goto bad; - funcname = PyUnicode_AsUTF8(py_funcname); - if (!funcname) goto bad; - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - if (!py_funcname) goto bad; - #endif - } - #if PY_MAJOR_VERSION < 3 - 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); - #else - py_code = PyCode_NewEmpty(filename, funcname, py_line); - #endif - Py_XDECREF(py_funcname); // XDECREF since it's only set on Py3 if cline - return py_code; -bad: - Py_XDECREF(py_funcname); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_srcfile); - #endif - 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; - PyObject *ptype, *pvalue, *ptraceback; - 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) { - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) { - /* If the code object creation fails, then we should clear the - fetched exception references and propagate the new exception */ - Py_XDECREF(ptype); - Py_XDECREF(pvalue); - Py_XDECREF(ptraceback); - goto bad; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - __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); -} - -/* FromPy */ - static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject* o) { - Py_complex cval; -#if !CYTHON_COMPILING_IN_PYPY - if (PyComplex_CheckExact(o)) - cval = ((PyComplexObject *)o)->cval; - else -#endif - cval = PyComplex_AsCComplex(o); - return __pyx_t_double_complex_from_parts( - (double)cval.real, - (double)cval.imag); -} - -/* Declarations */ - #if CYTHON_CCOMPLEX - #ifdef __cplusplus - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - return ::std::complex< double >(x, y); - } - #else - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - return x + y*(__pyx_t_double_complex)_Complex_I; - } - #endif -#else - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - __pyx_t_double_complex z; - z.real = x; - z.imag = y; - return z; - } -#endif - -/* Arithmetic */ - #if CYTHON_CCOMPLEX -#else - static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - return (a.real == b.real) && (a.imag == b.imag); - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real + b.real; - z.imag = a.imag + b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real - b.real; - z.imag = a.imag - b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real * b.real - a.imag * b.imag; - z.imag = a.real * b.imag + a.imag * b.real; - return z; - } - #if 1 - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - if (b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); - } else if (fabs(b.real) >= fabs(b.imag)) { - if (b.real == 0 && b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); - } else { - double r = b.imag / b.real; - double s = (double)(1.0) / (b.real + b.imag * r); - return __pyx_t_double_complex_from_parts( - (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); - } - } else { - double r = b.real / b.imag; - double s = (double)(1.0) / (b.imag + b.real * r); - return __pyx_t_double_complex_from_parts( - (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); - } - } - #else - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - if (b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); - } else { - double denom = b.real * b.real + b.imag * b.imag; - return __pyx_t_double_complex_from_parts( - (a.real * b.real + a.imag * b.imag) / denom, - (a.imag * b.real - a.real * b.imag) / denom); - } - } - #endif - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { - __pyx_t_double_complex z; - z.real = -a.real; - z.imag = -a.imag; - return z; - } - static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { - return (a.real == 0) && (a.imag == 0); - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { - __pyx_t_double_complex z; - z.real = a.real; - z.imag = -a.imag; - return z; - } - #if 1 - static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { - #if !defined(HAVE_HYPOT) || defined(_MSC_VER) - return sqrt(z.real*z.real + z.imag*z.imag); - #else - return hypot(z.real, z.imag); - #endif - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - double r, lnr, theta, z_r, z_theta; - if (b.imag == 0 && b.real == (int)b.real) { - if (b.real < 0) { - double denom = a.real * a.real + a.imag * a.imag; - a.real = a.real / denom; - a.imag = -a.imag / denom; - b.real = -b.real; - } - switch ((int)b.real) { - case 0: - z.real = 1; - z.imag = 0; - return z; - case 1: - return a; - case 2: - return __Pyx_c_prod_double(a, a); - case 3: - z = __Pyx_c_prod_double(a, a); - return __Pyx_c_prod_double(z, a); - case 4: - z = __Pyx_c_prod_double(a, a); - return __Pyx_c_prod_double(z, z); - } - } - if (a.imag == 0) { - if (a.real == 0) { - return a; - } else if ((b.imag == 0) && (a.real >= 0)) { - z.real = pow(a.real, b.real); - z.imag = 0; - return z; - } else if (a.real > 0) { - r = a.real; - theta = 0; - } else { - r = -a.real; - theta = atan2(0.0, -1.0); - } - } else { - r = __Pyx_c_abs_double(a); - theta = atan2(a.imag, a.real); - } - lnr = log(r); - z_r = exp(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cos(z_theta); - z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - 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); - } -} - -/* 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;\ - } - -/* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - 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 && PY_VERSION_HEX < 0x030C00A7 - 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 int __Pyx_PyInt_As_int(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - 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 && PY_VERSION_HEX < 0x030C00A7 - 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; -} - -/* 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 '9'); - break; - } - if (rt_from_call[i] != ctversion[i]) { - same = 0; - break; - } - } - if (!same) { - char rtversion[5] = {'\0'}; - char message[200]; - for (i=0; i<4; ++i) { - if (rt_from_call[i] == '.') { - if (found_dot) break; - found_dot = 1; - } else if (rt_from_call[i] < '0' || rt_from_call[i] > '9') { - break; - } - rtversion[i] = rt_from_call[i]; - } - 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 Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { - if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { - return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); -#if PY_MAJOR_VERSION < 3 - } else if (likely(PyInt_CheckExact(o))) { - return PyInt_AS_LONG(o); -#endif - } else { - Py_ssize_t ival; - PyObject *x; - x = PyNumber_Index(o); - if (!x) return -1; - ival = PyInt_AsLong(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/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/dockerfile-d67bbd50.js b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/dockerfile-d67bbd50.js deleted file mode 100644 index 5405cd3af19be5d8cb56dbb55aefa442653e888a..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/dockerfile-d67bbd50.js +++ /dev/null @@ -1,2 +0,0 @@ -function c(n){a(n,"start");var t={},e=n.languageData||{},s=!1;for(var l in n)if(l!=e&&n.hasOwnProperty(l))for(var u=t[l]=[],o=n[l],r=0;r2&&o.token&&typeof o.token!="string"){e.pending=[];for(var g=2;g-1)return null;var l=e.indent.length-1,u=n[e.state];n:for(;;){for(var o=0;o None: - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a lock with the correct implementation. - """ - self._backend = sniffio.current_async_library() - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio, requires the 'trio' package to be installed." - ) - self._trio_lock = trio.Lock() - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - self._anyio_lock = anyio.Lock() - - async def __aenter__(self) -> "AsyncLock": - if not self._backend: - self.setup() - - if self._backend == "trio": - await self._trio_lock.acquire() - else: - await self._anyio_lock.acquire() - - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - if self._backend == "trio": - self._trio_lock.release() - else: - self._anyio_lock.release() - - -class AsyncEvent: - def __init__(self) -> None: - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a lock with the correct implementation. - """ - self._backend = sniffio.current_async_library() - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - self._trio_event = trio.Event() - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - self._anyio_event = anyio.Event() - - def set(self) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - self._trio_event.set() - else: - self._anyio_event.set() - - async def wait(self, timeout: Optional[float] = None) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - - trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} - timeout_or_inf = float("inf") if timeout is None else timeout - with map_exceptions(trio_exc_map): - with trio.fail_after(timeout_or_inf): - await self._trio_event.wait() - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - - anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} - with map_exceptions(anyio_exc_map): - with anyio.fail_after(timeout): - await self._anyio_event.wait() - - -class AsyncSemaphore: - def __init__(self, bound: int) -> None: - self._bound = bound - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a semaphore with the correct implementation. - """ - self._backend = sniffio.current_async_library() - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - - self._trio_semaphore = trio.Semaphore( - initial_value=self._bound, max_value=self._bound - ) - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - - self._anyio_semaphore = anyio.Semaphore( - initial_value=self._bound, max_value=self._bound - ) - - async def acquire(self) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - await self._trio_semaphore.acquire() - else: - await self._anyio_semaphore.acquire() - - async def release(self) -> None: - if self._backend == "trio": - self._trio_semaphore.release() - else: - self._anyio_semaphore.release() - - -class AsyncShieldCancellation: - # For certain portions of our codebase where we're dealing with - # closing connections during exception handling we want to shield - # the operation from being cancelled. - # - # with AsyncShieldCancellation(): - # ... # clean-up operations, shielded from cancellation. - - def __init__(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a shielded scope with the correct implementation. - """ - self._backend = sniffio.current_async_library() - - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - - self._trio_shield = trio.CancelScope(shield=True) - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - - self._anyio_shield = anyio.CancelScope(shield=True) - - def __enter__(self) -> "AsyncShieldCancellation": - if self._backend == "trio": - self._trio_shield.__enter__() - else: - self._anyio_shield.__enter__() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - if self._backend == "trio": - self._trio_shield.__exit__(exc_type, exc_value, traceback) - else: - self._anyio_shield.__exit__(exc_type, exc_value, traceback) - - -# Our thread-based synchronization primitives... - - -class Lock: - def __init__(self) -> None: - self._lock = threading.Lock() - - def __enter__(self) -> "Lock": - self._lock.acquire() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - self._lock.release() - - -class Event: - def __init__(self) -> None: - self._event = threading.Event() - - def set(self) -> None: - self._event.set() - - def wait(self, timeout: Optional[float] = None) -> None: - if not self._event.wait(timeout=timeout): - raise PoolTimeout() # pragma: nocover - - -class Semaphore: - def __init__(self, bound: int) -> None: - self._semaphore = threading.Semaphore(value=bound) - - def acquire(self) -> None: - self._semaphore.acquire() - - def release(self) -> None: - self._semaphore.release() - - -class ShieldCancellation: - # Thread-synchronous codebases don't support cancellation semantics. - # We have this class because we need to mirror the async and sync - # cases within our package, but it's just a no-op. - def __enter__(self) -> "ShieldCancellation": - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - pass diff --git a/spaces/DataScienceEngineering/README/README.md b/spaces/DataScienceEngineering/README/README.md deleted file mode 100644 index 7dcffee917955e904edd130b39543b643c2dbc20..0000000000000000000000000000000000000000 --- a/spaces/DataScienceEngineering/README/README.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: README -emoji: 😻 -colorFrom: green -colorTo: yellow -sdk: static -pinned: false ---- - -🔥Start Here! - -# App Development with ChatGPT and Huggingface - 101 -1. Sign up and try ChatGPT with these two URLs: https://chat.openai.com/chat and https://platform.openai.com/playground. __Exercise__: Register for a free ChatGPT account today! -2. ChatGPT was built using Machine Learning models like Transformers, the most downloaded SDK on Github: https://github.com/huggingface/transformers. __Exercise__: Register for a free Github account today! -3. By using ChatGPT and https://Huggingface.co together you can write AI programs very quickly for Streamlit, Gradio, Docker, and HTML5. __Exercise__: Register for a free Huggingface account today! - -__Join__ organization classroom with this link: https://huggingface.co/organizations/DataScienceEngineering/share/GkxeINHFzHQaJyMRsAVoKJZTSyBrUeUYGV to learn more. \ No newline at end of file diff --git a/spaces/ElainaFanBoy/MusicGen/audiocraft/quantization/__init__.py b/spaces/ElainaFanBoy/MusicGen/audiocraft/quantization/__init__.py deleted file mode 100644 index 836d6eb518978480c6b95d6f29ce4f84a9428793..0000000000000000000000000000000000000000 --- a/spaces/ElainaFanBoy/MusicGen/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/Epitech/AIoT/app.py b/spaces/Epitech/AIoT/app.py deleted file mode 100644 index d524e6eef77802d03d1d7a8c76ba6bcfbf0d1e8b..0000000000000000000000000000000000000000 --- a/spaces/Epitech/AIoT/app.py +++ /dev/null @@ -1,51 +0,0 @@ -import streamlit as st -import pandas as pd -import sklearn -import pickle - -loaded_model = pickle.load(open("finalized_model.sav", 'rb')) - - -def main(): - st.image('img.jpg') - st.title("⚙️🔩 Engine prediction ⚙️🔩") - st.warning("Our Machine Learning algorithm predicts whether the elements of a machine work consistently\n\n") - - with st.form(key='columns_in_form'): - c1, c2, c3 = st.columns(3) - with c1: - airTemperature = st.slider("Air temperature [K]", 0, 1500, 750) - with c2: - processTemperatire = st.slider( - "Process temperature [K]", 0, 1500, 750) - with c3: - rotationSpeed = st.slider( - "Rotational speed [rpm]", 0, 1500, 750) - submitButton1 = st.form_submit_button(label='Save') - with st.form(key='columns_in_form2'): - c1, c2, c3, c4 = st.columns(4) - with c1: - toolWear = st.slider("Tool wear [min]", 0, 1500, 750) - with c2: - typeL = st.select_slider('Type_L', options=[0, 1]) - with c3: - typeM = st.select_slider('Type_M', options=[0, 1]) - with c4: - torqueNm = st.slider('Torque [Nm]', 0,300,150) - submitButton2 = st.form_submit_button(label='Calculate') - if (submitButton2): - d = {'Air temperature [K]': airTemperature, 'Process temperature [K]': processTemperatire, - 'Rotational speed [rpm]': rotationSpeed, "Torque [Nm]": torqueNm, "Tool wear [min]": toolWear, "Type_L": typeL, "Type_M": typeM} - ser = pd.Series(data=d, index=['Air temperature [K]', 'Process temperature [K]', - 'Rotational speed [rpm]', 'Torque [Nm]', 'Tool wear [min]', 'Type_L', 'Type_M']) - - res = loaded_model.predict([ser]) - if (res[0] == 0): - st.success("The machine is in good condition") - else: - st.error("The machine seems to have problems") - - - -if __name__ == '__main__': - main() diff --git a/spaces/EuroPython2022/clickbaitonator/README.md b/spaces/EuroPython2022/clickbaitonator/README.md deleted file mode 100644 index c3494dadac3f2458669f2fc25f1eb0e0d1367c49..0000000000000000000000000000000000000000 --- a/spaces/EuroPython2022/clickbaitonator/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Clickbaitonator -emoji: 💩 -colorFrom: purple -colorTo: yellow -sdk: gradio -sdk_version: 3.0.24 -app_file: app.py -pinned: false -license: afl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/FL33TW00D/whisper-turbo/index.html b/spaces/FL33TW00D/whisper-turbo/index.html deleted file mode 100644 index 4e8447bcd836ca76bf8835e4bb2b002f3dfd655e..0000000000000000000000000000000000000000 --- a/spaces/FL33TW00D/whisper-turbo/index.html +++ /dev/null @@ -1 +0,0 @@ -Whisper Turbo

Built by @fleetwood

\ No newline at end of file diff --git a/spaces/Fengbinbin/gpt-academic/request_llm/bridge_newbing.py b/spaces/Fengbinbin/gpt-academic/request_llm/bridge_newbing.py deleted file mode 100644 index dca7485056519265422f9162fe9868d3474e6f80..0000000000000000000000000000000000000000 --- a/spaces/Fengbinbin/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' + trimmed_format_exc() + '```' - 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/GodParticle69/minor_demo/README.md b/spaces/GodParticle69/minor_demo/README.md deleted file mode 100644 index 1f660ab24930be162e49d230fd2697053dedb1d8..0000000000000000000000000000000000000000 --- a/spaces/GodParticle69/minor_demo/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Minor Demo -emoji: 🏃 -colorFrom: purple -colorTo: purple -sdk: gradio -sdk_version: 3.15.0 -app_file: app.py -pinned: false -license: apache-2.0 -python_version: 3.7 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/mask_rcnn_hrnetv2p_w18_1x_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/mask_rcnn_hrnetv2p_w18_1x_coco.py deleted file mode 100644 index 82a5f464ed9b31ec6a513efc6a9fa20953cf1689..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/mask_rcnn_hrnetv2p_w18_1x_coco.py +++ /dev/null @@ -1,9 +0,0 @@ -_base_ = './mask_rcnn_hrnetv2p_w32_1x_coco.py' -model = dict( - pretrained='open-mmlab://msra/hrnetv2_w18', - backbone=dict( - extra=dict( - stage2=dict(num_channels=(18, 36)), - stage3=dict(num_channels=(18, 36, 72)), - stage4=dict(num_channels=(18, 36, 72, 144)))), - neck=dict(type='HRFPN', in_channels=[18, 36, 72, 144], out_channels=256)) diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/yolo/yolov3_d53_mstrain-416_273e_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/yolo/yolov3_d53_mstrain-416_273e_coco.py deleted file mode 100644 index d029b5cdd6b3dad09b16a6f2a23e66be684a6412..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/yolo/yolov3_d53_mstrain-416_273e_coco.py +++ /dev/null @@ -1,42 +0,0 @@ -_base_ = './yolov3_d53_mstrain-608_273e_coco.py' -# dataset settings -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), (416, 416)], 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=(416, 416), - 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( - train=dict(pipeline=train_pipeline), - val=dict(pipeline=test_pipeline), - test=dict(pipeline=test_pipeline)) diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/pspnet/pspnet_r18-d8_512x1024_80k_cityscapes.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/pspnet/pspnet_r18-d8_512x1024_80k_cityscapes.py deleted file mode 100644 index d914f93c023a6384e0e856b8608280cef589d5c6..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/pspnet/pspnet_r18-d8_512x1024_80k_cityscapes.py +++ /dev/null @@ -1,9 +0,0 @@ -_base_ = './pspnet_r50-d8_512x1024_80k_cityscapes.py' -model = dict( - pretrained='open-mmlab://resnet18_v1c', - backbone=dict(depth=18), - decode_head=dict( - in_channels=512, - channels=128, - ), - auxiliary_head=dict(in_channels=256, channels=64)) diff --git a/spaces/Hakim571/Food-Classification/README.md b/spaces/Hakim571/Food-Classification/README.md deleted file mode 100644 index f966b01aecd8cba84297c7d934e5dca50749ea52..0000000000000000000000000000000000000000 --- a/spaces/Hakim571/Food-Classification/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Food Detection -emoji: 👀 -colorFrom: blue -colorTo: gray -sdk: gradio -sdk_version: 3.32.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/m2m_100/install_dependecies.sh b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/m2m_100/install_dependecies.sh deleted file mode 100644 index 82a1054745264a56fbec4a8eb593884f8a42bd08..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/m2m_100/install_dependecies.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env bash -# 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. - - -CWD=`pwd` -INSTALL_PATH=$CWD/tokenizers/thirdparty - -MOSES=$INSTALL_PATH/mosesdecoder -if [ ! -d $MOSES ]; then - echo 'Cloning Moses github repository (for tokenization scripts)...' - git clone https://github.com/moses-smt/mosesdecoder.git $MOSES - cd $MOSES - # To deal with differences in handling ' vs " - git checkout 03578921cc1a03402 - cd - -fi - -WMT16_SCRIPTS=$INSTALL_PATH/wmt16-scripts -if [ ! -d $WMT16_SCRIPTS ]; then - echo 'Cloning Romanian tokenization scripts' - git clone https://github.com/rsennrich/wmt16-scripts.git $WMT16_SCRIPTS -fi - -KYTEA=$INSTALL_PATH/kytea -if [ ! -f $KYTEA/bin/kytea ]; then - git clone https://github.com/neubig/kytea.git $KYTEA - cd $KYTEA - autoreconf -i - ./configure --prefix=`pwd` - make - make install - cd .. -fi - -export MECAB=$INSTALL_PATH/mecab-0.996-ko-0.9.2 -if [ ! -f $MECAB/bin/mecab ]; then - cd $INSTALL_PATH - curl -LO https://bitbucket.org/eunjeon/mecab-ko/downloads/mecab-0.996-ko-0.9.2.tar.gz - tar zxfv mecab-0.996-ko-0.9.2.tar.gz - cd mecab-0.996-ko-0.9.2/ - ./configure --prefix=`pwd` - make - make install - - cd .. - curl -LO https://bitbucket.org/eunjeon/mecab-ko-dic/downloads/mecab-ko-dic-2.1.1-20180720.tar.gz - tar zxfv mecab-ko-dic-2.1.1-20180720.tar.gz - cd mecab-ko-dic-2.1.1-20180720/ - ./autogen.sh - ./configure --prefix=`pwd` --with-dicdir=$MECAB/lib/mecab/dic/mecab-ko-dic --with-mecab-config=$MECAB/bin/mecab-config - make - sh -c 'echo "dicdir=$MECAB/lib/mecab/dic/mecab-ko-dic" > $MECAB/etc/mecabrc' - make install - cd $CWD -fi - -INDIC_RESOURCES_PATH=$INSTALL_PATH/indic_nlp_resources -if [ ! -d $INDIC_RESOURCES_PATH ]; then - echo 'Cloning indic_nlp_resources' - git clone https://github.com/anoopkunchukuttan/indic_nlp_resources.git $INDIC_RESOURCES_PATH -fi - - -if [ ! -f $INSTALL_PATH/seg_my.py ]; then - cd $INSTALL_PATH - wget http://lotus.kuee.kyoto-u.ac.jp/WAT/my-en-data/wat2020.my-en.zip - unzip wat2020.my-en.zip - # switch to python3 - cat wat2020.my-en/myseg.py |sed 's/^sys.std/###sys.std/g' | sed 's/### sys/sys/g' | sed 's/unichr/chr/g' > seg_my.py - cd $CWD -fi - - -pip install pythainlp sacrebleu indic-nlp-library - diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/tests/test_transformer.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/tests/test_transformer.py deleted file mode 100644 index de5c5bdbd49692e63fb1cb50108a791304425dc1..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/tests/test_transformer.py +++ /dev/null @@ -1,65 +0,0 @@ -import argparse -import unittest -from typing import Any, Dict, Sequence - -import torch -from fairseq.models import transformer - -from tests.test_roberta import FakeTask - - -def mk_sample(tok: Sequence[int] = None, batch_size: int = 2) -> Dict[str, Any]: - if not tok: - tok = [10, 11, 12, 13, 14, 15, 2] - - batch = torch.stack([torch.tensor(tok, dtype=torch.long)] * batch_size) - sample = { - "net_input": { - "src_tokens": batch, - "prev_output_tokens": batch, - "src_lengths": torch.tensor( - [len(tok)] * batch_size, dtype=torch.long, device=batch.device - ), - }, - "target": batch[:, 1:], - } - return sample - - -def mk_transformer(**extra_args: Any): - overrides = { - # Use characteristics dimensions - "encoder_embed_dim": 12, - "encoder_ffn_embed_dim": 14, - "decoder_embed_dim": 12, - "decoder_ffn_embed_dim": 14, - # Disable dropout so we have comparable tests. - "dropout": 0, - "attention_dropout": 0, - "activation_dropout": 0, - "encoder_layerdrop": 0, - } - overrides.update(extra_args) - # Overrides the defaults from the parser - args = argparse.Namespace(**overrides) - transformer.tiny_architecture(args) - - torch.manual_seed(0) - task = FakeTask(args) - return transformer.TransformerModel.build_model(args, task) - - -class TransformerTestCase(unittest.TestCase): - def test_forward_backward(self): - model = mk_transformer(encoder_embed_dim=12, decoder_embed_dim=12) - sample = mk_sample() - o, _ = model.forward(**sample["net_input"]) - loss = o.sum() - loss.backward() - - def test_different_encoder_decoder_embed_dim(self): - model = mk_transformer(encoder_embed_dim=12, decoder_embed_dim=16) - sample = mk_sample() - o, _ = model.forward(**sample["net_input"]) - loss = o.sum() - loss.backward() diff --git a/spaces/HarryLee/eCommerceImageCaptioning/run_scripts/caption/evaluate_caption_base.sh b/spaces/HarryLee/eCommerceImageCaptioning/run_scripts/caption/evaluate_caption_base.sh deleted file mode 100644 index 587c4df54c633eb6f23284ab666962acce0f94b9..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/run_scripts/caption/evaluate_caption_base.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash - -# The port for communication. Note that if you want to run multiple tasks on the same machine, -# you need to specify different port numbers. -export MASTER_PORT=1091 - -user_dir=../../ofa_module -bpe_dir=../../utils/BPE - -data=../../dataset/caption_data/caption_test.tsv -path=../../checkpoints/caption_base_best.pt -result_path=../../results/caption -selected_cols=1,4,2 -split='test' - -CUDA_VISIBLE_DEVICES=4,5,6,7 python3 -m torch.distributed.launch --nproc_per_node=4 --master_port=${MASTER_PORT} ../../evaluate.py \ - ${data} \ - --path=${path} \ - --user-dir=${user_dir} \ - --task=caption \ - --batch-size=16 \ - --log-format=simple --log-interval=10 \ - --seed=7 \ - --gen-subset=${split} \ - --results-path=${result_path} \ - --beam=5 \ - --max-len-b=16 \ - --no-repeat-ngram-size=3 \ - --fp16 \ - --num-workers=0 \ - --model-overrides="{\"data\":\"${data}\",\"bpe_dir\":\"${bpe_dir}\",\"eval_cider\":False,\"selected_cols\":\"${selected_cols}\"}" - -python coco_eval.py ../../results/caption/test_predict.json ../../dataset/caption_data/test_caption_coco_format.json diff --git a/spaces/Hina4867/bingo/src/app/loading.css b/spaces/Hina4867/bingo/src/app/loading.css deleted file mode 100644 index eaaab6a86a228334c4eca3c5368ae6f0f593d405..0000000000000000000000000000000000000000 --- a/spaces/Hina4867/bingo/src/app/loading.css +++ /dev/null @@ -1,68 +0,0 @@ -::-webkit-scrollbar { - width: 10px; - height: 10px; - display: none; -} - -::-webkit-scrollbar-button:start:decrement, -::-webkit-scrollbar-button:end:increment { - height: 30px; - background-color: transparent; -} - -::-webkit-scrollbar-track-piece { - background-color: #3b3b3b; - -webkit-border-radius: 16px; -} - -::-webkit-scrollbar-thumb:vertical { - height: 50px; - background-color: #666; - border: 1px solid #eee; - -webkit-border-radius: 6px; -} - -/* loading start */ -.loading-spinner { - display: flex; - justify-content: center; - align-items: center; - height: 100vh; - opacity: 1; - transition: opacity .8s ease-out; -} - -.loading-spinner.hidden { - opacity: 0; -} - -.loading-spinner>div { - width: 30px; - height: 30px; - background: linear-gradient(90deg, #2870EA 10.79%, #1B4AEF 87.08%); - - border-radius: 100%; - display: inline-block; - animation: sk-bouncedelay 1.4s infinite ease-in-out both; -} - -.loading-spinner .bounce1 { - animation-delay: -0.32s; -} - -.loading-spinner .bounce2 { - animation-delay: -0.16s; -} - -@keyframes sk-bouncedelay { - - 0%, - 80%, - 100% { - transform: scale(0); - } - - 40% { - transform: scale(1.0); - } -} diff --git a/spaces/ICML2022/OFA/fairseq/examples/constrained_decoding/tok.py b/spaces/ICML2022/OFA/fairseq/examples/constrained_decoding/tok.py deleted file mode 100644 index b1f888a8c0d1b8ec7174859476cc3222456e0d2c..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/constrained_decoding/tok.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import sys - -import sacremoses - - -def main(args): - """Tokenizes, preserving tabs""" - mt = sacremoses.MosesTokenizer(lang=args.lang) - - def tok(s): - return mt.tokenize(s, return_str=True) - - for line in sys.stdin: - parts = list(map(tok, line.split("\t"))) - print(*parts, sep="\t", flush=True) - - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--lang", "-l", default="en") - parser.add_argument("--penn", "-p", action="store_true") - parser.add_argument("--fields", "-f", help="fields to tokenize") - args = parser.parse_args() - - main(args) diff --git a/spaces/ICML2022/OFA/fairseq/examples/laser/laser_src/laser_lstm.py b/spaces/ICML2022/OFA/fairseq/examples/laser/laser_src/laser_lstm.py deleted file mode 100644 index 10df90e002d5a7dd74a571dbc3b328c130c57a0a..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/laser/laser_src/laser_lstm.py +++ /dev/null @@ -1,585 +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 -import torch.nn as nn -import torch.nn.functional as F - -from fairseq import options, utils - -from fairseq.models import ( - FairseqEncoder, - FairseqIncrementalDecoder, - FairseqEncoderDecoderModel, - register_model, - register_model_architecture, -) - - -@register_model("laser_lstm") -class LSTMModel(FairseqEncoderDecoderModel): - def __init__(self, encoder, decoder): - super().__init__(encoder, decoder) - - def forward( - self, - src_tokens, - src_lengths, - prev_output_tokens=None, - tgt_tokens=None, - tgt_lengths=None, - target_language_id=None, - dataset_name="", - ): - assert target_language_id is not None - - src_encoder_out = self.encoder(src_tokens, src_lengths, dataset_name) - return self.decoder( - prev_output_tokens, src_encoder_out, lang_id=target_language_id - ) - - @staticmethod - def add_args(parser): - """Add model-specific arguments to the parser.""" - parser.add_argument( - "--dropout", - default=0.1, - type=float, - metavar="D", - help="dropout probability", - ) - parser.add_argument( - "--encoder-embed-dim", - type=int, - metavar="N", - help="encoder embedding dimension", - ) - parser.add_argument( - "--encoder-embed-path", - default=None, - type=str, - metavar="STR", - help="path to pre-trained encoder embedding", - ) - parser.add_argument( - "--encoder-hidden-size", type=int, metavar="N", help="encoder hidden size" - ) - parser.add_argument( - "--encoder-layers", type=int, metavar="N", help="number of encoder layers" - ) - parser.add_argument( - "--encoder-bidirectional", - action="store_true", - help="make all layers of encoder bidirectional", - ) - parser.add_argument( - "--decoder-embed-dim", - type=int, - metavar="N", - help="decoder embedding dimension", - ) - parser.add_argument( - "--decoder-embed-path", - default=None, - type=str, - metavar="STR", - help="path to pre-trained decoder embedding", - ) - parser.add_argument( - "--decoder-hidden-size", type=int, metavar="N", help="decoder hidden size" - ) - parser.add_argument( - "--decoder-layers", type=int, metavar="N", help="number of decoder layers" - ) - parser.add_argument( - "--decoder-out-embed-dim", - type=int, - metavar="N", - help="decoder output embedding dimension", - ) - parser.add_argument( - "--decoder-zero-init", - type=str, - metavar="BOOL", - help="initialize the decoder hidden/cell state to zero", - ) - parser.add_argument( - "--decoder-lang-embed-dim", - type=int, - metavar="N", - help="decoder language embedding dimension", - ) - parser.add_argument( - "--fixed-embeddings", - action="store_true", - help="keep embeddings fixed (ENCODER ONLY)", - ) # TODO Also apply to decoder embeddings? - - # Granular dropout settings (if not specified these default to --dropout) - parser.add_argument( - "--encoder-dropout-in", - type=float, - metavar="D", - help="dropout probability for encoder input embedding", - ) - parser.add_argument( - "--encoder-dropout-out", - type=float, - metavar="D", - help="dropout probability for encoder output", - ) - parser.add_argument( - "--decoder-dropout-in", - type=float, - metavar="D", - help="dropout probability for decoder input embedding", - ) - parser.add_argument( - "--decoder-dropout-out", - type=float, - metavar="D", - help="dropout probability for decoder output", - ) - - @classmethod - def build_model(cls, args, task): - """Build a new model instance.""" - # make sure that all args are properly defaulted (in case there are any new ones) - base_architecture(args) - - def load_pretrained_embedding_from_file(embed_path, dictionary, embed_dim): - num_embeddings = len(dictionary) - padding_idx = dictionary.pad() - embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) - embed_dict = utils.parse_embedding(embed_path) - utils.print_embed_overlap(embed_dict, dictionary) - return utils.load_embedding(embed_dict, dictionary, embed_tokens) - - pretrained_encoder_embed = None - if args.encoder_embed_path: - pretrained_encoder_embed = load_pretrained_embedding_from_file( - args.encoder_embed_path, task.source_dictionary, args.encoder_embed_dim - ) - pretrained_decoder_embed = None - if args.decoder_embed_path: - pretrained_decoder_embed = load_pretrained_embedding_from_file( - args.decoder_embed_path, task.target_dictionary, args.decoder_embed_dim - ) - - num_langs = task.num_tasks if hasattr(task, "num_tasks") else 0 - - encoder = LSTMEncoder( - dictionary=task.source_dictionary, - embed_dim=args.encoder_embed_dim, - hidden_size=args.encoder_hidden_size, - num_layers=args.encoder_layers, - dropout_in=args.encoder_dropout_in, - dropout_out=args.encoder_dropout_out, - bidirectional=args.encoder_bidirectional, - pretrained_embed=pretrained_encoder_embed, - fixed_embeddings=args.fixed_embeddings, - ) - decoder = LSTMDecoder( - dictionary=task.target_dictionary, - embed_dim=args.decoder_embed_dim, - hidden_size=args.decoder_hidden_size, - out_embed_dim=args.decoder_out_embed_dim, - num_layers=args.decoder_layers, - dropout_in=args.decoder_dropout_in, - dropout_out=args.decoder_dropout_out, - zero_init=options.eval_bool(args.decoder_zero_init), - encoder_embed_dim=args.encoder_embed_dim, - encoder_output_units=encoder.output_units, - pretrained_embed=pretrained_decoder_embed, - num_langs=num_langs, - lang_embed_dim=args.decoder_lang_embed_dim, - ) - return cls(encoder, decoder) - - -class LSTMEncoder(FairseqEncoder): - """LSTM encoder.""" - - def __init__( - self, - dictionary, - embed_dim=512, - hidden_size=512, - num_layers=1, - dropout_in=0.1, - dropout_out=0.1, - bidirectional=False, - left_pad=True, - pretrained_embed=None, - padding_value=0.0, - fixed_embeddings=False, - ): - super().__init__(dictionary) - self.num_layers = num_layers - self.dropout_in = dropout_in - self.dropout_out = dropout_out - self.bidirectional = bidirectional - self.hidden_size = hidden_size - - num_embeddings = len(dictionary) - self.padding_idx = dictionary.pad() - if pretrained_embed is None: - self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) - else: - self.embed_tokens = pretrained_embed - if fixed_embeddings: - self.embed_tokens.weight.requires_grad = False - - self.lstm = LSTM( - input_size=embed_dim, - hidden_size=hidden_size, - num_layers=num_layers, - dropout=self.dropout_out if num_layers > 1 else 0.0, - bidirectional=bidirectional, - ) - self.left_pad = left_pad - self.padding_value = padding_value - - self.output_units = hidden_size - if bidirectional: - self.output_units *= 2 - - def forward(self, src_tokens, src_lengths, dataset_name): - if self.left_pad: - # convert left-padding to right-padding - src_tokens = utils.convert_padding_direction( - src_tokens, - self.padding_idx, - left_to_right=True, - ) - - bsz, seqlen = src_tokens.size() - - # embed tokens - x = self.embed_tokens(src_tokens) - x = F.dropout(x, p=self.dropout_in, training=self.training) - - # B x T x C -> T x B x C - x = x.transpose(0, 1) - - # pack embedded source tokens into a PackedSequence - try: - packed_x = nn.utils.rnn.pack_padded_sequence(x, src_lengths.data.tolist()) - except BaseException: - raise Exception(f"Packing failed in dataset {dataset_name}") - - # apply LSTM - if self.bidirectional: - state_size = 2 * self.num_layers, bsz, self.hidden_size - else: - state_size = self.num_layers, bsz, self.hidden_size - h0 = x.data.new(*state_size).zero_() - c0 = x.data.new(*state_size).zero_() - packed_outs, (final_hiddens, final_cells) = self.lstm(packed_x, (h0, c0)) - - # unpack outputs and apply dropout - x, _ = nn.utils.rnn.pad_packed_sequence( - packed_outs, padding_value=self.padding_value - ) - x = F.dropout(x, p=self.dropout_out, training=self.training) - assert list(x.size()) == [seqlen, bsz, self.output_units] - - if self.bidirectional: - - def combine_bidir(outs): - return torch.cat( - [ - torch.cat([outs[2 * i], outs[2 * i + 1]], dim=0).view( - 1, bsz, self.output_units - ) - for i in range(self.num_layers) - ], - dim=0, - ) - - final_hiddens = combine_bidir(final_hiddens) - final_cells = combine_bidir(final_cells) - - encoder_padding_mask = src_tokens.eq(self.padding_idx).t() - - # Set padded outputs to -inf so they are not selected by max-pooling - padding_mask = src_tokens.eq(self.padding_idx).t().unsqueeze(-1) - if padding_mask.any(): - x = x.float().masked_fill_(padding_mask, float("-inf")).type_as(x) - - # Build the sentence embedding by max-pooling over the encoder outputs - sentemb = x.max(dim=0)[0] - - return { - "sentemb": sentemb, - "encoder_out": (x, final_hiddens, final_cells), - "encoder_padding_mask": encoder_padding_mask - if encoder_padding_mask.any() - else None, - } - - def reorder_encoder_out(self, encoder_out_dict, new_order): - encoder_out_dict["sentemb"] = encoder_out_dict["sentemb"].index_select( - 0, new_order - ) - encoder_out_dict["encoder_out"] = tuple( - eo.index_select(1, new_order) for eo in encoder_out_dict["encoder_out"] - ) - if encoder_out_dict["encoder_padding_mask"] is not None: - encoder_out_dict["encoder_padding_mask"] = encoder_out_dict[ - "encoder_padding_mask" - ].index_select(1, new_order) - return encoder_out_dict - - def max_positions(self): - """Maximum input length supported by the encoder.""" - return int(1e5) # an arbitrary large number - - -class LSTMDecoder(FairseqIncrementalDecoder): - """LSTM decoder.""" - - def __init__( - self, - dictionary, - embed_dim=512, - hidden_size=512, - out_embed_dim=512, - num_layers=1, - dropout_in=0.1, - dropout_out=0.1, - zero_init=False, - encoder_embed_dim=512, - encoder_output_units=512, - pretrained_embed=None, - num_langs=1, - lang_embed_dim=0, - ): - super().__init__(dictionary) - self.dropout_in = dropout_in - self.dropout_out = dropout_out - self.hidden_size = hidden_size - - num_embeddings = len(dictionary) - padding_idx = dictionary.pad() - if pretrained_embed is None: - self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) - else: - self.embed_tokens = pretrained_embed - - self.layers = nn.ModuleList( - [ - LSTMCell( - input_size=encoder_output_units + embed_dim + lang_embed_dim - if layer == 0 - else hidden_size, - hidden_size=hidden_size, - ) - for layer in range(num_layers) - ] - ) - if hidden_size != out_embed_dim: - self.additional_fc = Linear(hidden_size, out_embed_dim) - self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out) - - if zero_init: - self.sentemb2init = None - else: - self.sentemb2init = Linear( - encoder_output_units, 2 * num_layers * hidden_size - ) - - if lang_embed_dim == 0: - self.embed_lang = None - else: - self.embed_lang = nn.Embedding(num_langs, lang_embed_dim) - nn.init.uniform_(self.embed_lang.weight, -0.1, 0.1) - - def forward( - self, prev_output_tokens, encoder_out_dict, incremental_state=None, lang_id=0 - ): - sentemb = encoder_out_dict["sentemb"] - encoder_out = encoder_out_dict["encoder_out"] - - if incremental_state is not None: - prev_output_tokens = prev_output_tokens[:, -1:] - bsz, seqlen = prev_output_tokens.size() - - # get outputs from encoder - encoder_outs, _, _ = encoder_out[:3] - srclen = encoder_outs.size(0) - - # embed tokens - x = self.embed_tokens(prev_output_tokens) - x = F.dropout(x, p=self.dropout_in, training=self.training) - - # embed language identifier - if self.embed_lang is not None: - lang_ids = prev_output_tokens.data.new_full((bsz,), lang_id) - langemb = self.embed_lang(lang_ids) - # TODO Should we dropout here??? - - # B x T x C -> T x B x C - x = x.transpose(0, 1) - - # initialize previous states (or get from cache during incremental generation) - cached_state = utils.get_incremental_state( - self, incremental_state, "cached_state" - ) - if cached_state is not None: - prev_hiddens, prev_cells, input_feed = cached_state - else: - num_layers = len(self.layers) - if self.sentemb2init is None: - prev_hiddens = [ - x.data.new(bsz, self.hidden_size).zero_() for i in range(num_layers) - ] - prev_cells = [ - x.data.new(bsz, self.hidden_size).zero_() for i in range(num_layers) - ] - else: - init = self.sentemb2init(sentemb) - prev_hiddens = [ - init[:, (2 * i) * self.hidden_size : (2 * i + 1) * self.hidden_size] - for i in range(num_layers) - ] - prev_cells = [ - init[ - :, - (2 * i + 1) * self.hidden_size : (2 * i + 2) * self.hidden_size, - ] - for i in range(num_layers) - ] - input_feed = x.data.new(bsz, self.hidden_size).zero_() - - attn_scores = x.data.new(srclen, seqlen, bsz).zero_() - outs = [] - for j in range(seqlen): - if self.embed_lang is None: - input = torch.cat((x[j, :, :], sentemb), dim=1) - else: - input = torch.cat((x[j, :, :], sentemb, langemb), dim=1) - - for i, rnn in enumerate(self.layers): - # recurrent cell - hidden, cell = rnn(input, (prev_hiddens[i], prev_cells[i])) - - # hidden state becomes the input to the next layer - input = F.dropout(hidden, p=self.dropout_out, training=self.training) - - # save state for next time step - prev_hiddens[i] = hidden - prev_cells[i] = cell - - out = hidden - out = F.dropout(out, p=self.dropout_out, training=self.training) - - # input feeding - input_feed = out - - # save final output - outs.append(out) - - # cache previous states (no-op except during incremental generation) - utils.set_incremental_state( - self, - incremental_state, - "cached_state", - (prev_hiddens, prev_cells, input_feed), - ) - - # collect outputs across time steps - x = torch.cat(outs, dim=0).view(seqlen, bsz, self.hidden_size) - - # T x B x C -> B x T x C - x = x.transpose(1, 0) - - # srclen x tgtlen x bsz -> bsz x tgtlen x srclen - attn_scores = attn_scores.transpose(0, 2) - - # project back to size of vocabulary - if hasattr(self, "additional_fc"): - x = self.additional_fc(x) - x = F.dropout(x, p=self.dropout_out, training=self.training) - x = self.fc_out(x) - - return x, attn_scores - - def reorder_incremental_state(self, incremental_state, new_order): - super().reorder_incremental_state(incremental_state, new_order) - cached_state = utils.get_incremental_state( - self, incremental_state, "cached_state" - ) - if cached_state is None: - return - - def reorder_state(state): - if isinstance(state, list): - return [reorder_state(state_i) for state_i in state] - return state.index_select(0, new_order) - - new_state = tuple(map(reorder_state, cached_state)) - utils.set_incremental_state(self, incremental_state, "cached_state", new_state) - - def max_positions(self): - """Maximum output length supported by the decoder.""" - return int(1e5) # an arbitrary large number - - -def Embedding(num_embeddings, embedding_dim, padding_idx): - m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) - nn.init.uniform_(m.weight, -0.1, 0.1) - nn.init.constant_(m.weight[padding_idx], 0) - return m - - -def LSTM(input_size, hidden_size, **kwargs): - m = nn.LSTM(input_size, hidden_size, **kwargs) - for name, param in m.named_parameters(): - if "weight" in name or "bias" in name: - param.data.uniform_(-0.1, 0.1) - return m - - -def LSTMCell(input_size, hidden_size, **kwargs): - m = nn.LSTMCell(input_size, hidden_size, **kwargs) - for name, param in m.named_parameters(): - if "weight" in name or "bias" in name: - param.data.uniform_(-0.1, 0.1) - return m - - -def Linear(in_features, out_features, bias=True, dropout=0): - """Weight-normalized Linear layer (input: N x T x C)""" - m = nn.Linear(in_features, out_features, bias=bias) - m.weight.data.uniform_(-0.1, 0.1) - if bias: - m.bias.data.uniform_(-0.1, 0.1) - return m - - -@register_model_architecture("laser_lstm", "laser_lstm") -def base_architecture(args): - args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) - args.encoder_embed_path = getattr(args, "encoder_embed_path", None) - args.encoder_hidden_size = getattr( - args, "encoder_hidden_size", args.encoder_embed_dim - ) - args.encoder_layers = getattr(args, "encoder_layers", 1) - args.encoder_bidirectional = getattr(args, "encoder_bidirectional", False) - args.encoder_dropout_in = getattr(args, "encoder_dropout_in", args.dropout) - args.encoder_dropout_out = getattr(args, "encoder_dropout_out", args.dropout) - args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512) - args.decoder_embed_path = getattr(args, "decoder_embed_path", None) - args.decoder_hidden_size = getattr( - args, "decoder_hidden_size", args.decoder_embed_dim - ) - args.decoder_layers = getattr(args, "decoder_layers", 1) - args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512) - args.decoder_dropout_in = getattr(args, "decoder_dropout_in", args.dropout) - args.decoder_dropout_out = getattr(args, "decoder_dropout_out", args.dropout) - args.decoder_zero_init = getattr(args, "decoder_zero_init", "0") - args.decoder_lang_embed_dim = getattr(args, "decoder_lang_embed_dim", 0) - args.fixed_embeddings = getattr(args, "fixed_embeddings", False) diff --git a/spaces/ICML2022/OFA/fairseq/examples/speech_synthesis/__init__.py b/spaces/ICML2022/OFA/fairseq/examples/speech_synthesis/__init__.py deleted file mode 100644 index 6264236915a7269a4d920ee8213004374dd86a9a..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/speech_synthesis/__init__.py +++ /dev/null @@ -1,4 +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. diff --git a/spaces/ICML2022/OFA/fairseq/examples/textless_nlp/gslm/ulm/sample.py b/spaces/ICML2022/OFA/fairseq/examples/textless_nlp/gslm/ulm/sample.py deleted file mode 100644 index 77302a6894cacf07588cf34fb1e695dc519d7df5..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/textless_nlp/gslm/ulm/sample.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -u -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. -""" -Sample from a trained LM; hacked fairseq-interactive -""" -from collections import namedtuple -import os -import ast -import numpy as np - -from fairseq import checkpoint_utils, options, tasks, utils - -import tqdm - -Batch = namedtuple('Batch', 'ids src_tokens src_lengths') -Translation = namedtuple('Translation', 'src_str hypos pos_scores alignments') - - -def make_batches(lines, args, task, max_positions): - tokens = [ - task.source_dictionary.encode_line( - src_str, add_if_not_exist=False - ).long() - for src_str in lines - ] - lengths = [t.numel() for t in tokens] - itr = task.get_batch_iterator( - dataset=task.build_dataset_for_inference(tokens, lengths), - max_tokens=args.dataset.max_tokens, - max_sentences=args.dataset.batch_size, - max_positions=max_positions, - ignore_invalid_inputs=args.dataset.skip_invalid_size_inputs_valid_test - ).next_epoch_itr(shuffle=False) - for batch in itr: - yield Batch( - ids=batch['id'], - src_tokens=batch['net_input']['src_tokens'], src_lengths=batch['net_input']['src_lengths'], - ) - - -def main(args): - arg_prompts = args.prompts - arg_output = args.output - arg_debug = args.debug - arg_sample_size = args.samples_per_prompt - - try: - from fairseq.dataclass.utils import convert_namespace_to_omegaconf - args = convert_namespace_to_omegaconf(args) - except: - pass - - # if args.max_tokens is None and args.max_sentences is None: - if args.common.seed is not None: - np.random.seed(args.common.seed) - utils.set_torch_seed(args.common.seed) - - if args.generation.sampling: - args.generation.nbest = args.generation.beam = arg_sample_size - - task = tasks.setup_task(args.task) - - overrides = ast.literal_eval(args.common_eval.model_overrides) - - models, _model_args = checkpoint_utils.load_model_ensemble( - args.common_eval.path.split(os.pathsep), - arg_overrides=overrides, - task=task, - suffix=getattr(args, "checkpoint_suffix", ""), - ) - - # Set dictionaries - src_dict = task.source_dictionary - tgt_dict = task.target_dictionary - - # Optimize ensemble for generation - for model in models: - model.prepare_for_inference_(args) - model.cuda() - - # Load alignment dictionary for unknown word replacement - # (None if no unknown word replacement, empty if no path to align dictionary) - align_dict = utils.load_align_dict(args.generation.replace_unk) - - max_positions = utils.resolve_max_positions( - task.max_positions(), - *[model.max_positions() for model in models] - ) - - output_file = open(arg_output, 'w') - - with open(arg_prompts, 'r') as fin: - lines = fin.readlines() - - split = [x.split('|', 1) for x in lines] - seq_id = [x[0] for x in split] - prompts = [x[1] for x in split] - - if args.generation.prefix_size >= 0: - prompts = [' '.join(l.split()[:args.generation.prefix_size]) - for l in prompts] - - if arg_debug: - prompts = prompts[:10] - - generator = task.build_generator(models, args.generation) - - start_id = 0 - pbar = tqdm.tqdm(total=len(prompts)) - for batch in make_batches(prompts, args, task, max_positions): - src_tokens = batch.src_tokens - src_lengths = batch.src_lengths - src_tokens = src_tokens.cuda() - src_lengths = src_lengths.cuda() - - sample = { - 'net_input': { - 'src_tokens': src_tokens, - 'src_lengths': src_lengths, - }, - } - - results = [] - translations = task.inference_step(generator, models, sample) - for i, (id, hypos) in enumerate(zip(batch.ids.tolist(), translations)): - src_tokens_i = utils.strip_pad(src_tokens[i], tgt_dict.pad()) - results.append((i + start_id, src_tokens_i, hypos)) - - # sort output to match input order - for id, src_tokens, hypos in sorted(results, key=lambda x: x[0]): - if src_dict is not None: - src_str = src_dict.string( - src_tokens, args.common_eval.post_process) - - # Process top predictions - for hypo_id, hypo in enumerate(hypos): - _hypo_tokens, hypo_str, _alignment = utils.post_process_prediction( - hypo_tokens=hypo['tokens'].int().cpu(), - src_str=src_str, - alignment=hypo['alignment'], - align_dict=align_dict, - tgt_dict=tgt_dict, - remove_bpe=args.common_eval.post_process, - ) - - detok_hypo_str = hypo_str - utterance = detok_hypo_str - print(f'{seq_id[id]}__{hypo_id}|{utterance}', file=output_file) - pbar.update(1) - start_id += len(results) - - # output_file.close() - - -def cli_main(): - parser = options.get_interactive_generation_parser() - parser.add_argument('--prompts', type=str, default=None, required=True) - parser.add_argument('--output', type=str, default=None, required=True) - parser.add_argument('--debug', action='store_true') - parser.add_argument('--samples-per-prompt', type=int, default=1) - - args = options.parse_args_and_arch(parser) - - np.random.seed(args.seed) - utils.set_torch_seed(args.seed) - - main(args) - - -if __name__ == '__main__': - cli_main() diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/criterions/label_smoothed_cross_entropy_latency_augmented.py b/spaces/ICML2022/OFA/fairseq/fairseq/criterions/label_smoothed_cross_entropy_latency_augmented.py deleted file mode 100644 index 223a16f740c10b58ea45a0390814363e7b5f68b8..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/criterions/label_smoothed_cross_entropy_latency_augmented.py +++ /dev/null @@ -1,233 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass, field -import torch -from fairseq import metrics, utils -from fairseq.criterions import register_criterion -from fairseq.criterions.label_smoothed_cross_entropy import ( - LabelSmoothedCrossEntropyCriterion, - LabelSmoothedCrossEntropyCriterionConfig -) - -try: - from simuleval.metrics.latency import ( - AverageLagging, - AverageProportion, - DifferentiableAverageLagging - ) - LATENCY_METRICS = { - "average_lagging": AverageLagging, - "average_proportion": AverageProportion, - "differentiable_average_lagging": DifferentiableAverageLagging, - } -except ImportError: - LATENCY_METRICS = None - - -@dataclass -class LabelSmoothedCrossEntropyCriterionLatencyAugmentConfig( - LabelSmoothedCrossEntropyCriterionConfig -): - latency_avg_weight: float = field( - default=0.0, - metadata={"help": "weight fot average latency loss."}, - ) - latency_var_weight: float = field( - default=0.0, - metadata={"help": "weight fot variance latency loss."}, - ) - latency_avg_type: str = field( - default="differentiable_average_lagging", - metadata={"help": "latency type for average loss"}, - ) - latency_var_type: str = field( - default="variance_delay", - metadata={"help": "latency typ for variance loss"}, - ) - latency_gather_method: str = field( - default="weighted_average", - metadata={"help": "method to gather latency loss for all heads"}, - ) - latency_update_after: int = field( - default=0, - metadata={"help": "Add latency loss after certain steps"}, - ) - -@register_criterion( - "latency_augmented_label_smoothed_cross_entropy", - dataclass=LabelSmoothedCrossEntropyCriterionLatencyAugmentConfig -) -class LatencyAugmentedLabelSmoothedCrossEntropyCriterion( - LabelSmoothedCrossEntropyCriterion -): - def __init__( - self, - task, - sentence_avg, - label_smoothing, - ignore_prefix_size, - report_accuracy, - latency_avg_weight, - latency_var_weight, - latency_avg_type, - latency_var_type, - latency_gather_method, - latency_update_after, - ): - super().__init__( - task, sentence_avg, label_smoothing, ignore_prefix_size, report_accuracy - ) - assert LATENCY_METRICS is not None, "Please make sure SimulEval is installed." - - self.latency_avg_weight = latency_avg_weight - self.latency_var_weight = latency_var_weight - self.latency_avg_type = latency_avg_type - self.latency_var_type = latency_var_type - self.latency_gather_method = latency_gather_method - self.latency_update_after = latency_update_after - - def forward(self, model, sample, reduce=True): - net_output = model(**sample["net_input"]) - # 1. Compute cross entropy loss - loss, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce) - - # 2. Compute cross latency loss - latency_loss, expected_latency, expected_delays_var = self.compute_latency_loss( - model, sample, net_output - ) - - if self.latency_update_after > 0: - num_updates = getattr(model.decoder, "num_updates", None) - assert num_updates is not None, ( - "model.decoder doesn't have attribute 'num_updates'" - ) - if num_updates <= self.latency_update_after: - latency_loss = 0 - - loss += latency_loss - - sample_size = ( - sample["target"].size(0) if self.sentence_avg else sample["ntokens"] - ) - - logging_output = { - "loss": loss.data, - "nll_loss": nll_loss.data, - "ntokens": sample["ntokens"], - "nsentences": sample["target"].size(0), - "sample_size": sample_size, - "latency": expected_latency, - "delays_var": expected_delays_var, - "latency_loss": latency_loss, - } - - if self.report_accuracy: - n_correct, total = self.compute_accuracy(model, net_output, sample) - logging_output["n_correct"] = utils.item(n_correct.data) - logging_output["total"] = utils.item(total.data) - return loss, sample_size, logging_output - - def compute_latency_loss(self, model, sample, net_output): - assert ( - net_output[-1].encoder_padding_mask is None - or not net_output[-1].encoder_padding_mask[:, 0].any() - ), ( - "Only right padding on source is supported." - ) - # 1. Obtain the expected alignment - alpha_list = [item["alpha"] for item in net_output[1].attn_list] - num_layers = len(alpha_list) - bsz, num_heads, tgt_len, src_len = alpha_list[0].size() - - # bsz * num_layers * num_heads, tgt_len, src_len - alpha_all = torch.cat(alpha_list, dim=1).view(-1, tgt_len, src_len) - - # 2 compute expected delays - # bsz * num_heads * num_layers, tgt_len, src_len for MMA - steps = ( - torch.arange(1, 1 + src_len) - .unsqueeze(0) - .unsqueeze(1) - .expand_as(alpha_all) - .type_as(alpha_all) - ) - - expected_delays = torch.sum(steps * alpha_all, dim=-1) - - target_padding_mask = ( - model.get_targets(sample, net_output) - .eq(self.padding_idx) - .unsqueeze(1) - .expand(bsz, num_layers * num_heads, tgt_len) - .contiguous() - .view(-1, tgt_len) - ) - - src_lengths = ( - sample["net_input"]["src_lengths"] - .unsqueeze(1) - .expand(bsz, num_layers * num_heads) - .contiguous() - .view(-1) - ) - expected_latency = LATENCY_METRICS[self.latency_avg_type]( - expected_delays, src_lengths, None, - target_padding_mask=target_padding_mask - ) - - # 2.1 average expected latency of heads - # bsz, num_layers * num_heads - expected_latency = expected_latency.view(bsz, -1) - if self.latency_gather_method == "average": - # bsz * tgt_len - expected_latency = expected_delays.mean(dim=1) - elif self.latency_gather_method == "weighted_average": - weights = torch.nn.functional.softmax(expected_latency, dim=1) - expected_latency = torch.sum(expected_latency * weights, dim=1) - elif self.latency_gather_method == "max": - expected_latency = expected_latency.max(dim=1)[0] - else: - raise NotImplementedError - - expected_latency = expected_latency.sum() - avg_loss = self.latency_avg_weight * expected_latency - - # 2.2 variance of expected delays - expected_delays_var = ( - expected_delays.view(bsz, -1, tgt_len).var(dim=1).mean(dim=1) - ) - expected_delays_var = expected_delays_var.sum() - var_loss = self.latency_avg_weight * expected_delays_var - - # 3. Final loss - latency_loss = avg_loss + var_loss - - return latency_loss, expected_latency, expected_delays_var - - @classmethod - def reduce_metrics(cls, logging_outputs) -> None: - super().reduce_metrics(logging_outputs) - latency = sum( - log.get("latency", 0) for log in logging_outputs - ) - delays_var = sum( - log.get("delays_var", 0) for log in logging_outputs - ) - latency_loss = sum( - log.get("latency_loss", 0) for log in logging_outputs - ) - nsentences = sum(log.get("nsentences", 0) for log in logging_outputs) - metrics.log_scalar( - "latency", latency.float() / nsentences, nsentences, round=3 - ) - metrics.log_scalar( - "delays_var", delays_var / nsentences, - nsentences, round=3 - ) - metrics.log_scalar( - "latency_loss", latency_loss / nsentences, - nsentences, round=3 - ) diff --git a/spaces/ICML2022/resefa/models/stylegan2_generator.py b/spaces/ICML2022/resefa/models/stylegan2_generator.py deleted file mode 100644 index 331ea320464912601e74bebb6432e0d7c09b6642..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/resefa/models/stylegan2_generator.py +++ /dev/null @@ -1,1394 +0,0 @@ -# python3.7 -"""Contains the implementation of generator described in StyleGAN2. - -Compared to that of StyleGAN, the generator in StyleGAN2 mainly introduces style -demodulation, adds skip connections, increases model size, and disables -progressive growth. This script ONLY supports config F in the original paper. - -Paper: https://arxiv.org/pdf/1912.04958.pdf - -Official TensorFlow implementation: https://github.com/NVlabs/stylegan2 -""" - -import numpy as np - -import torch -import torch.nn as nn - -from third_party.stylegan2_official_ops import fma -from third_party.stylegan2_official_ops import bias_act -from third_party.stylegan2_official_ops import upfirdn2d -from third_party.stylegan2_official_ops import conv2d_gradfix -from .utils.ops import all_gather - -__all__ = ['StyleGAN2Generator'] - -# Resolutions allowed. -_RESOLUTIONS_ALLOWED = [8, 16, 32, 64, 128, 256, 512, 1024] - -# Architectures allowed. -_ARCHITECTURES_ALLOWED = ['resnet', 'skip', 'origin'] - -# pylint: disable=missing-function-docstring - -class StyleGAN2Generator(nn.Module): - """Defines the generator network in StyleGAN2. - - NOTE: The synthesized images are with `RGB` channel order and pixel range - [-1, 1]. - - Settings for the mapping network: - - (1) z_dim: Dimension of the input latent space, Z. (default: 512) - (2) w_dim: Dimension of the output latent space, W. (default: 512) - (3) repeat_w: Repeat w-code for different layers. (default: True) - (4) normalize_z: Whether to normalize the z-code. (default: True) - (5) mapping_layers: Number of layers of the mapping network. (default: 8) - (6) mapping_fmaps: Number of hidden channels of the mapping network. - (default: 512) - (7) mapping_use_wscale: Whether to use weight scaling for the mapping - network. (default: True) - (8) mapping_wscale_gain: The factor to control weight scaling for the - mapping network (default: 1.0) - (9) mapping_lr_mul: Learning rate multiplier for the mapping network. - (default: 0.01) - - Settings for conditional generation: - - (1) label_dim: Dimension of the additional label for conditional generation. - In one-hot conditioning case, it is equal to the number of classes. If - set to 0, conditioning training will be disabled. (default: 0) - (2) embedding_dim: Dimension of the embedding space, if needed. - (default: 512) - (3) embedding_bias: Whether to add bias to embedding learning. - (default: True) - (4) embedding_use_wscale: Whether to use weight scaling for embedding - learning. (default: True) - (5) embedding_wscale_gain: The factor to control weight scaling for - embedding. (default: 1.0) - (6) embedding_lr_mul: Learning rate multiplier for the embedding learning. - (default: 1.0) - (7) normalize_embedding: Whether to normalize the embedding. (default: True) - (8) normalize_embedding_latent: Whether to normalize the embedding together - with the latent. (default: False) - - Settings for the synthesis network: - - (1) resolution: The resolution of the output image. (default: -1) - (2) init_res: The initial resolution to start with convolution. (default: 4) - (3) image_channels: Number of channels of the output image. (default: 3) - (4) final_tanh: Whether to use `tanh` to control the final pixel range. - (default: False) - (5) const_input: Whether to use a constant in the first convolutional layer. - (default: True) - (6) architecture: Type of architecture. Support `origin`, `skip`, and - `resnet`. (default: `skip`) - (7) demodulate: Whether to perform style demodulation. (default: True) - (8) use_wscale: Whether to use weight scaling. (default: True) - (9) wscale_gain: The factor to control weight scaling. (default: 1.0) - (10) lr_mul: Learning rate multiplier for the synthesis network. - (default: 1.0) - (11) noise_type: Type of noise added to the convolutional results at each - layer. (default: `spatial`) - (12) fmaps_base: Factor to control number of feature maps for each layer. - (default: 32 << 10) - (13) fmaps_max: Maximum number of feature maps in each layer. (default: 512) - (14) filter_kernel: Kernel used for filtering (e.g., downsampling). - (default: (1, 3, 3, 1)) - (15) conv_clamp: A threshold to clamp the output of convolution layers to - avoid overflow under FP16 training. (default: None) - (16) eps: A small value to avoid divide overflow. (default: 1e-8) - - Runtime settings: - - (1) w_moving_decay: Decay factor for updating `w_avg`, which is used for - training only. Set `None` to disable. (default: None) - (2) sync_w_avg: Synchronizing the stats of `w_avg` across replicas. If set - as `True`, the stats will be more accurate, yet the speed maybe a little - bit slower. (default: False) - (3) style_mixing_prob: Probability to perform style mixing as a training - regularization. Set `None` to disable. (default: None) - (4) trunc_psi: Truncation psi, set `None` to disable. (default: None) - (5) trunc_layers: Number of layers to perform truncation. (default: None) - (6) noise_mode: Mode of the layer-wise noise. Support `none`, `random`, - `const`. (default: `const`) - (7) fused_modulate: Whether to fuse `style_modulate` and `conv2d` together. - (default: False) - (8) fp16_res: Layers at resolution higher than (or equal to) this field will - use `float16` precision for computation. This is merely used for - acceleration. If set as `None`, all layers will use `float32` by - default. (default: None) - (9) impl: Implementation mode of some particular ops, e.g., `filtering`, - `bias_act`, etc. `cuda` means using the official CUDA implementation - from StyleGAN2, while `ref` means using the native PyTorch ops. - (default: `cuda`) - """ - - def __init__(self, - # Settings for mapping network. - z_dim=512, - w_dim=512, - repeat_w=True, - normalize_z=True, - mapping_layers=8, - mapping_fmaps=512, - mapping_use_wscale=True, - mapping_wscale_gain=1.0, - mapping_lr_mul=0.01, - # Settings for conditional generation. - label_dim=0, - embedding_dim=512, - embedding_bias=True, - embedding_use_wscale=True, - embedding_wscale_gian=1.0, - embedding_lr_mul=1.0, - normalize_embedding=True, - normalize_embedding_latent=False, - # Settings for synthesis network. - resolution=-1, - init_res=4, - image_channels=3, - final_tanh=False, - const_input=True, - architecture='skip', - demodulate=True, - use_wscale=True, - wscale_gain=1.0, - lr_mul=1.0, - noise_type='spatial', - fmaps_base=32 << 10, - fmaps_max=512, - filter_kernel=(1, 3, 3, 1), - conv_clamp=None, - eps=1e-8): - """Initializes with basic settings. - - Raises: - ValueError: If the `resolution` is not supported, or `architecture` - is not supported. - """ - super().__init__() - - if resolution not in _RESOLUTIONS_ALLOWED: - raise ValueError(f'Invalid resolution: `{resolution}`!\n' - f'Resolutions allowed: {_RESOLUTIONS_ALLOWED}.') - architecture = architecture.lower() - if architecture not in _ARCHITECTURES_ALLOWED: - raise ValueError(f'Invalid architecture: `{architecture}`!\n' - f'Architectures allowed: ' - f'{_ARCHITECTURES_ALLOWED}.') - - self.z_dim = z_dim - self.w_dim = w_dim - self.repeat_w = repeat_w - self.normalize_z = normalize_z - self.mapping_layers = mapping_layers - self.mapping_fmaps = mapping_fmaps - self.mapping_use_wscale = mapping_use_wscale - self.mapping_wscale_gain = mapping_wscale_gain - self.mapping_lr_mul = mapping_lr_mul - - self.label_dim = label_dim - self.embedding_dim = embedding_dim - self.embedding_bias = embedding_bias - self.embedding_use_wscale = embedding_use_wscale - self.embedding_wscale_gain = embedding_wscale_gian - self.embedding_lr_mul = embedding_lr_mul - self.normalize_embedding = normalize_embedding - self.normalize_embedding_latent = normalize_embedding_latent - - self.resolution = resolution - self.init_res = init_res - self.image_channels = image_channels - self.final_tanh = final_tanh - self.const_input = const_input - self.architecture = architecture - self.demodulate = demodulate - self.use_wscale = use_wscale - self.wscale_gain = wscale_gain - self.lr_mul = lr_mul - self.noise_type = noise_type.lower() - self.fmaps_base = fmaps_base - self.fmaps_max = fmaps_max - self.filter_kernel = filter_kernel - self.conv_clamp = conv_clamp - self.eps = eps - - # Dimension of latent space, which is convenient for sampling. - self.latent_dim = (z_dim,) - - # Number of synthesis (convolutional) layers. - self.num_layers = int(np.log2(resolution // init_res * 2)) * 2 - - self.mapping = MappingNetwork( - input_dim=z_dim, - output_dim=w_dim, - num_outputs=self.num_layers, - repeat_output=repeat_w, - normalize_input=normalize_z, - num_layers=mapping_layers, - hidden_dim=mapping_fmaps, - use_wscale=mapping_use_wscale, - wscale_gain=mapping_wscale_gain, - lr_mul=mapping_lr_mul, - label_dim=label_dim, - embedding_dim=embedding_dim, - embedding_bias=embedding_bias, - embedding_use_wscale=embedding_use_wscale, - embedding_wscale_gian=embedding_wscale_gian, - embedding_lr_mul=embedding_lr_mul, - normalize_embedding=normalize_embedding, - normalize_embedding_latent=normalize_embedding_latent, - eps=eps) - - # This is used for truncation trick. - if self.repeat_w: - self.register_buffer('w_avg', torch.zeros(w_dim)) - else: - self.register_buffer('w_avg', torch.zeros(self.num_layers * w_dim)) - - self.synthesis = SynthesisNetwork(resolution=resolution, - init_res=init_res, - w_dim=w_dim, - image_channels=image_channels, - final_tanh=final_tanh, - const_input=const_input, - architecture=architecture, - demodulate=demodulate, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - noise_type=noise_type, - fmaps_base=fmaps_base, - filter_kernel=filter_kernel, - fmaps_max=fmaps_max, - conv_clamp=conv_clamp, - eps=eps) - - self.pth_to_tf_var_mapping = {'w_avg': 'dlatent_avg'} - for key, val in self.mapping.pth_to_tf_var_mapping.items(): - self.pth_to_tf_var_mapping[f'mapping.{key}'] = val - for key, val in self.synthesis.pth_to_tf_var_mapping.items(): - self.pth_to_tf_var_mapping[f'synthesis.{key}'] = val - - def set_space_of_latent(self, space_of_latent): - """Sets the space to which the latent code belong. - - See `SynthesisNetwork` for more details. - """ - self.synthesis.set_space_of_latent(space_of_latent) - - def forward(self, - z, - label=None, - w_moving_decay=None, - sync_w_avg=False, - style_mixing_prob=None, - trunc_psi=None, - trunc_layers=None, - noise_mode='const', - fused_modulate=False, - fp16_res=None, - impl='cuda'): - """Connects mapping network and synthesis network. - - This forward function will also update the average `w_code`, perform - style mixing as a training regularizer, and do truncation trick, which - is specially designed for inference. - - Concretely, the truncation trick acts as follows: - - For layers in range [0, truncation_layers), the truncated w-code is - computed as - - w_new = w_avg + (w - w_avg) * truncation_psi - - To disable truncation, please set - - (1) truncation_psi = 1.0 (None) OR - (2) truncation_layers = 0 (None) - """ - - mapping_results = self.mapping(z, label, impl=impl) - - w = mapping_results['w'] - if self.training and w_moving_decay is not None: - if sync_w_avg: - batch_w_avg = all_gather(w.detach()).mean(dim=0) - else: - batch_w_avg = w.detach().mean(dim=0) - self.w_avg.copy_(batch_w_avg.lerp(self.w_avg, w_moving_decay)) - - wp = mapping_results.pop('wp') - if self.training and style_mixing_prob is not None: - if np.random.uniform() < style_mixing_prob: - new_z = torch.randn_like(z) - new_wp = self.mapping(new_z, label, impl=impl)['wp'] - mixing_cutoff = np.random.randint(1, self.num_layers) - wp[:, mixing_cutoff:] = new_wp[:, mixing_cutoff:] - - if not self.training: - trunc_psi = 1.0 if trunc_psi is None else trunc_psi - trunc_layers = 0 if trunc_layers is None else trunc_layers - if trunc_psi < 1.0 and trunc_layers > 0: - w_avg = self.w_avg.reshape(1, -1, self.w_dim)[:, :trunc_layers] - wp[:, :trunc_layers] = w_avg.lerp( - wp[:, :trunc_layers], trunc_psi) - - synthesis_results = self.synthesis(wp, - noise_mode=noise_mode, - fused_modulate=fused_modulate, - impl=impl, - fp16_res=fp16_res) - - return {**mapping_results, **synthesis_results} - - -class MappingNetwork(nn.Module): - """Implements the latent space mapping network. - - Basically, this network executes several dense layers in sequence, and the - label embedding if needed. - """ - - def __init__(self, - input_dim, - output_dim, - num_outputs, - repeat_output, - normalize_input, - num_layers, - hidden_dim, - use_wscale, - wscale_gain, - lr_mul, - label_dim, - embedding_dim, - embedding_bias, - embedding_use_wscale, - embedding_wscale_gian, - embedding_lr_mul, - normalize_embedding, - normalize_embedding_latent, - eps): - super().__init__() - - self.input_dim = input_dim - self.output_dim = output_dim - self.num_outputs = num_outputs - self.repeat_output = repeat_output - self.normalize_input = normalize_input - self.num_layers = num_layers - self.hidden_dim = hidden_dim - self.use_wscale = use_wscale - self.wscale_gain = wscale_gain - self.lr_mul = lr_mul - self.label_dim = label_dim - self.embedding_dim = embedding_dim - self.embedding_bias = embedding_bias - self.embedding_use_wscale = embedding_use_wscale - self.embedding_wscale_gian = embedding_wscale_gian - self.embedding_lr_mul = embedding_lr_mul - self.normalize_embedding = normalize_embedding - self.normalize_embedding_latent = normalize_embedding_latent - self.eps = eps - - self.pth_to_tf_var_mapping = {} - - self.norm = PixelNormLayer(dim=1, eps=eps) - - if self.label_dim > 0: - input_dim = input_dim + embedding_dim - self.embedding = DenseLayer(in_channels=label_dim, - out_channels=embedding_dim, - add_bias=embedding_bias, - init_bias=0.0, - use_wscale=embedding_use_wscale, - wscale_gain=embedding_wscale_gian, - lr_mul=embedding_lr_mul, - activation_type='linear') - self.pth_to_tf_var_mapping['embedding.weight'] = 'LabelEmbed/weight' - if self.embedding_bias: - self.pth_to_tf_var_mapping['embedding.bias'] = 'LabelEmbed/bias' - - if num_outputs is not None and not repeat_output: - output_dim = output_dim * num_outputs - for i in range(num_layers): - in_channels = (input_dim if i == 0 else hidden_dim) - out_channels = (output_dim if i == (num_layers - 1) else hidden_dim) - self.add_module(f'dense{i}', - DenseLayer(in_channels=in_channels, - out_channels=out_channels, - add_bias=True, - init_bias=0.0, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - activation_type='lrelu')) - self.pth_to_tf_var_mapping[f'dense{i}.weight'] = f'Dense{i}/weight' - self.pth_to_tf_var_mapping[f'dense{i}.bias'] = f'Dense{i}/bias' - - def forward(self, z, label=None, impl='cuda'): - if z.ndim != 2 or z.shape[1] != self.input_dim: - raise ValueError(f'Input latent code should be with shape ' - f'[batch_size, input_dim], where ' - f'`input_dim` equals to {self.input_dim}!\n' - f'But `{z.shape}` is received!') - if self.normalize_input: - z = self.norm(z) - - if self.label_dim > 0: - if label is None: - raise ValueError(f'Model requires an additional label ' - f'(with dimension {self.label_dim}) as input, ' - f'but no label is received!') - if label.ndim != 2 or label.shape != (z.shape[0], self.label_dim): - raise ValueError(f'Input label should be with shape ' - f'[batch_size, label_dim], where ' - f'`batch_size` equals to that of ' - f'latent codes ({z.shape[0]}) and ' - f'`label_dim` equals to {self.label_dim}!\n' - f'But `{label.shape}` is received!') - label = label.to(dtype=torch.float32) - embedding = self.embedding(label, impl=impl) - if self.normalize_embedding: - embedding = self.norm(embedding) - w = torch.cat((z, embedding), dim=1) - else: - w = z - - if self.label_dim > 0 and self.normalize_embedding_latent: - w = self.norm(w) - - for i in range(self.num_layers): - w = getattr(self, f'dense{i}')(w, impl=impl) - - wp = None - if self.num_outputs is not None: - if self.repeat_output: - wp = w.unsqueeze(1).repeat((1, self.num_outputs, 1)) - else: - wp = w.reshape(-1, self.num_outputs, self.output_dim) - - results = { - 'z': z, - 'label': label, - 'w': w, - 'wp': wp, - } - if self.label_dim > 0: - results['embedding'] = embedding - return results - - -class SynthesisNetwork(nn.Module): - """Implements the image synthesis network. - - Basically, this network executes several convolutional layers in sequence. - """ - - def __init__(self, - resolution, - init_res, - w_dim, - image_channels, - final_tanh, - const_input, - architecture, - demodulate, - use_wscale, - wscale_gain, - lr_mul, - noise_type, - fmaps_base, - fmaps_max, - filter_kernel, - conv_clamp, - eps): - super().__init__() - - self.init_res = init_res - self.init_res_log2 = int(np.log2(init_res)) - self.resolution = resolution - self.final_res_log2 = int(np.log2(resolution)) - self.w_dim = w_dim - self.image_channels = image_channels - self.final_tanh = final_tanh - self.const_input = const_input - self.architecture = architecture.lower() - self.demodulate = demodulate - self.use_wscale = use_wscale - self.wscale_gain = wscale_gain - self.lr_mul = lr_mul - self.noise_type = noise_type.lower() - self.fmaps_base = fmaps_base - self.fmaps_max = fmaps_max - self.filter_kernel = filter_kernel - self.conv_clamp = conv_clamp - self.eps = eps - - self.num_layers = (self.final_res_log2 - self.init_res_log2 + 1) * 2 - - self.pth_to_tf_var_mapping = {} - - for res_log2 in range(self.init_res_log2, self.final_res_log2 + 1): - res = 2 ** res_log2 - in_channels = self.get_nf(res // 2) - out_channels = self.get_nf(res) - block_idx = res_log2 - self.init_res_log2 - - # Early layer. - if res == init_res: - if self.const_input: - self.add_module('early_layer', - InputLayer(init_res=res, - channels=out_channels)) - self.pth_to_tf_var_mapping['early_layer.const'] = ( - f'{res}x{res}/Const/const') - else: - channels = out_channels * res * res - self.add_module('early_layer', - DenseLayer(in_channels=w_dim, - out_channels=channels, - add_bias=True, - init_bias=0.0, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - activation_type='lrelu')) - self.pth_to_tf_var_mapping['early_layer.weight'] = ( - f'{res}x{res}/Dense/weight') - self.pth_to_tf_var_mapping['early_layer.bias'] = ( - f'{res}x{res}/Dense/bias') - else: - # Residual branch (kernel 1x1) with upsampling, without bias, - # with linear activation. - if self.architecture == 'resnet': - layer_name = f'residual{block_idx}' - self.add_module(layer_name, - ConvLayer(in_channels=in_channels, - out_channels=out_channels, - kernel_size=1, - add_bias=False, - scale_factor=2, - filter_kernel=filter_kernel, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - activation_type='linear', - conv_clamp=None)) - self.pth_to_tf_var_mapping[f'{layer_name}.weight'] = ( - f'{res}x{res}/Skip/weight') - - # First layer (kernel 3x3) with upsampling. - layer_name = f'layer{2 * block_idx - 1}' - self.add_module(layer_name, - ModulateConvLayer(in_channels=in_channels, - out_channels=out_channels, - resolution=res, - w_dim=w_dim, - kernel_size=3, - add_bias=True, - scale_factor=2, - filter_kernel=filter_kernel, - demodulate=demodulate, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - noise_type=noise_type, - activation_type='lrelu', - conv_clamp=conv_clamp, - eps=eps)) - self.pth_to_tf_var_mapping[f'{layer_name}.weight'] = ( - f'{res}x{res}/Conv0_up/weight') - self.pth_to_tf_var_mapping[f'{layer_name}.bias'] = ( - f'{res}x{res}/Conv0_up/bias') - self.pth_to_tf_var_mapping[f'{layer_name}.style.weight'] = ( - f'{res}x{res}/Conv0_up/mod_weight') - self.pth_to_tf_var_mapping[f'{layer_name}.style.bias'] = ( - f'{res}x{res}/Conv0_up/mod_bias') - self.pth_to_tf_var_mapping[f'{layer_name}.noise_strength'] = ( - f'{res}x{res}/Conv0_up/noise_strength') - self.pth_to_tf_var_mapping[f'{layer_name}.noise'] = ( - f'noise{2 * block_idx - 1}') - - # Second layer (kernel 3x3) without upsampling. - layer_name = f'layer{2 * block_idx}' - self.add_module(layer_name, - ModulateConvLayer(in_channels=out_channels, - out_channels=out_channels, - resolution=res, - w_dim=w_dim, - kernel_size=3, - add_bias=True, - scale_factor=1, - filter_kernel=None, - demodulate=demodulate, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - noise_type=noise_type, - activation_type='lrelu', - conv_clamp=conv_clamp, - eps=eps)) - tf_layer_name = 'Conv' if res == self.init_res else 'Conv1' - self.pth_to_tf_var_mapping[f'{layer_name}.weight'] = ( - f'{res}x{res}/{tf_layer_name}/weight') - self.pth_to_tf_var_mapping[f'{layer_name}.bias'] = ( - f'{res}x{res}/{tf_layer_name}/bias') - self.pth_to_tf_var_mapping[f'{layer_name}.style.weight'] = ( - f'{res}x{res}/{tf_layer_name}/mod_weight') - self.pth_to_tf_var_mapping[f'{layer_name}.style.bias'] = ( - f'{res}x{res}/{tf_layer_name}/mod_bias') - self.pth_to_tf_var_mapping[f'{layer_name}.noise_strength'] = ( - f'{res}x{res}/{tf_layer_name}/noise_strength') - self.pth_to_tf_var_mapping[f'{layer_name}.noise'] = ( - f'noise{2 * block_idx}') - - # Output convolution layer for each resolution (if needed). - if res_log2 == self.final_res_log2 or self.architecture == 'skip': - layer_name = f'output{block_idx}' - self.add_module(layer_name, - ModulateConvLayer(in_channels=out_channels, - out_channels=image_channels, - resolution=res, - w_dim=w_dim, - kernel_size=1, - add_bias=True, - scale_factor=1, - filter_kernel=None, - demodulate=False, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - noise_type='none', - activation_type='linear', - conv_clamp=conv_clamp, - eps=eps)) - self.pth_to_tf_var_mapping[f'{layer_name}.weight'] = ( - f'{res}x{res}/ToRGB/weight') - self.pth_to_tf_var_mapping[f'{layer_name}.bias'] = ( - f'{res}x{res}/ToRGB/bias') - self.pth_to_tf_var_mapping[f'{layer_name}.style.weight'] = ( - f'{res}x{res}/ToRGB/mod_weight') - self.pth_to_tf_var_mapping[f'{layer_name}.style.bias'] = ( - f'{res}x{res}/ToRGB/mod_bias') - - # Used for upsampling output images for each resolution block for sum. - if self.architecture == 'skip': - self.register_buffer( - 'filter', upfirdn2d.setup_filter(filter_kernel)) - - def get_nf(self, res): - """Gets number of feature maps according to the given resolution.""" - return min(self.fmaps_base // res, self.fmaps_max) - - def set_space_of_latent(self, space_of_latent): - """Sets the space to which the latent code belong. - - This function is particularly used for choosing how to inject the latent - code into the convolutional layers. The original generator will take a - W-Space code and apply it for style modulation after an affine - transformation. But, sometimes, it may need to directly feed an already - affine-transformed code into the convolutional layer, e.g., when - training an encoder for GAN inversion. We term the transformed space as - Style Space (or Y-Space). This function is designed to tell the - convolutional layers how to use the input code. - - Args: - space_of_latent: The space to which the latent code belong. Case - insensitive. Support `W` and `Y`. - """ - space_of_latent = space_of_latent.upper() - for module in self.modules(): - if isinstance(module, ModulateConvLayer): - setattr(module, 'space_of_latent', space_of_latent) - - def forward(self, - wp, - noise_mode='const', - fused_modulate=False, - fp16_res=None, - impl='cuda'): - results = {'wp': wp} - - if self.const_input: - x = self.early_layer(wp[:, 0]) - else: - x = self.early_layer(wp[:, 0], impl=impl) - - # Cast to `torch.float16` if needed. - if fp16_res is not None and self.init_res >= fp16_res: - x = x.to(torch.float16) - - if self.architecture == 'origin': - for layer_idx in range(self.num_layers - 1): - layer = getattr(self, f'layer{layer_idx}') - x, style = layer(x, - wp[:, layer_idx], - noise_mode=noise_mode, - fused_modulate=fused_modulate, - impl=impl) - results[f'style{layer_idx}'] = style - - # Cast to `torch.float16` if needed. - if layer_idx % 2 == 0 and layer_idx != self.num_layers - 2: - res = self.init_res * (2 ** (layer_idx // 2)) - if fp16_res is not None and res * 2 >= fp16_res: - x = x.to(torch.float16) - else: - x = x.to(torch.float32) - output_layer = getattr(self, f'output{layer_idx // 2}') - image, style = output_layer(x, - wp[:, layer_idx + 1], - fused_modulate=fused_modulate, - impl=impl) - image = image.to(torch.float32) - results[f'output_style{layer_idx // 2}'] = style - - elif self.architecture == 'skip': - for layer_idx in range(self.num_layers - 1): - layer = getattr(self, f'layer{layer_idx}') - x, style = layer(x, - wp[:, layer_idx], - noise_mode=noise_mode, - fused_modulate=fused_modulate, - impl=impl) - results[f'style{layer_idx}'] = style - if layer_idx % 2 == 0: - output_layer = getattr(self, f'output{layer_idx // 2}') - y, style = output_layer(x, - wp[:, layer_idx + 1], - fused_modulate=fused_modulate, - impl=impl) - results[f'output_style{layer_idx // 2}'] = style - if layer_idx == 0: - image = y.to(torch.float32) - else: - image = y.to(torch.float32) + upfirdn2d.upsample2d( - image, self.filter, impl=impl) - - # Cast to `torch.float16` if needed. - if layer_idx != self.num_layers - 2: - res = self.init_res * (2 ** (layer_idx // 2)) - if fp16_res is not None and res * 2 >= fp16_res: - x = x.to(torch.float16) - else: - x = x.to(torch.float32) - - elif self.architecture == 'resnet': - x, style = self.layer0(x, - wp[:, 0], - noise_mode=noise_mode, - fused_modulate=fused_modulate, - impl=impl) - results['style0'] = style - for layer_idx in range(1, self.num_layers - 1, 2): - # Cast to `torch.float16` if needed. - if layer_idx % 2 == 1: - res = self.init_res * (2 ** (layer_idx // 2)) - if fp16_res is not None and res * 2 >= fp16_res: - x = x.to(torch.float16) - else: - x = x.to(torch.float32) - - skip_layer = getattr(self, f'residual{layer_idx // 2 + 1}') - residual = skip_layer(x, runtime_gain=np.sqrt(0.5), impl=impl) - layer = getattr(self, f'layer{layer_idx}') - x, style = layer(x, - wp[:, layer_idx], - noise_mode=noise_mode, - fused_modulate=fused_modulate, - impl=impl) - results[f'style{layer_idx}'] = style - layer = getattr(self, f'layer{layer_idx + 1}') - x, style = layer(x, - wp[:, layer_idx + 1], - runtime_gain=np.sqrt(0.5), - noise_mode=noise_mode, - fused_modulate=fused_modulate, - impl=impl) - results[f'style{layer_idx + 1}'] = style - x = x + residual - output_layer = getattr(self, f'output{layer_idx // 2 + 1}') - image, style = output_layer(x, - wp[:, layer_idx + 2], - fused_modulate=fused_modulate, - impl=impl) - image = image.to(torch.float32) - results[f'output_style{layer_idx // 2}'] = style - - if self.final_tanh: - image = torch.tanh(image) - results['image'] = image - return results - - -class PixelNormLayer(nn.Module): - """Implements pixel-wise feature vector normalization layer.""" - - def __init__(self, dim, eps): - super().__init__() - self.dim = dim - self.eps = eps - - def extra_repr(self): - return f'dim={self.dim}, epsilon={self.eps}' - - def forward(self, x): - scale = (x.square().mean(dim=self.dim, keepdim=True) + self.eps).rsqrt() - return x * scale - - -class InputLayer(nn.Module): - """Implements the input layer to start convolution with. - - Basically, this block starts from a const input, which is with shape - `(channels, init_res, init_res)`. - """ - - def __init__(self, init_res, channels): - super().__init__() - self.const = nn.Parameter(torch.randn(1, channels, init_res, init_res)) - - def forward(self, w): - x = self.const.repeat(w.shape[0], 1, 1, 1) - return x - - -class ConvLayer(nn.Module): - """Implements the convolutional layer. - - If upsampling is needed (i.e., `scale_factor = 2`), the feature map will - be filtered with `filter_kernel` after convolution. This layer will only be - used for skip connection in `resnet` architecture. - """ - - def __init__(self, - in_channels, - out_channels, - kernel_size, - add_bias, - scale_factor, - filter_kernel, - use_wscale, - wscale_gain, - lr_mul, - activation_type, - conv_clamp): - """Initializes with layer settings. - - Args: - in_channels: Number of channels of the input tensor. - out_channels: Number of channels of the output tensor. - kernel_size: Size of the convolutional kernels. - add_bias: Whether to add bias onto the convolutional result. - scale_factor: Scale factor for upsampling. - filter_kernel: Kernel used for filtering. - use_wscale: Whether to use weight scaling. - wscale_gain: Gain factor for weight scaling. - lr_mul: Learning multiplier for both weight and bias. - activation_type: Type of activation. - conv_clamp: A threshold to clamp the output of convolution layers to - avoid overflow under FP16 training. - """ - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.kernel_size = kernel_size - self.add_bias = add_bias - self.scale_factor = scale_factor - self.filter_kernel = filter_kernel - self.use_wscale = use_wscale - self.wscale_gain = wscale_gain - self.lr_mul = lr_mul - self.activation_type = activation_type - self.conv_clamp = conv_clamp - - weight_shape = (out_channels, in_channels, kernel_size, kernel_size) - fan_in = kernel_size * kernel_size * in_channels - wscale = wscale_gain / np.sqrt(fan_in) - if use_wscale: - self.weight = nn.Parameter(torch.randn(*weight_shape) / lr_mul) - self.wscale = wscale * lr_mul - else: - self.weight = nn.Parameter( - torch.randn(*weight_shape) * wscale / lr_mul) - self.wscale = lr_mul - - if add_bias: - self.bias = nn.Parameter(torch.zeros(out_channels)) - self.bscale = lr_mul - else: - self.bias = None - self.act_gain = bias_act.activation_funcs[activation_type].def_gain - - if scale_factor > 1: - assert filter_kernel is not None - self.register_buffer( - 'filter', upfirdn2d.setup_filter(filter_kernel)) - fh, fw = self.filter.shape - self.filter_padding = ( - kernel_size // 2 + (fw + scale_factor - 1) // 2, - kernel_size // 2 + (fw - scale_factor) // 2, - kernel_size // 2 + (fh + scale_factor - 1) // 2, - kernel_size // 2 + (fh - scale_factor) // 2) - - def extra_repr(self): - return (f'in_ch={self.in_channels}, ' - f'out_ch={self.out_channels}, ' - f'ksize={self.kernel_size}, ' - f'wscale_gain={self.wscale_gain:.3f}, ' - f'bias={self.add_bias}, ' - f'lr_mul={self.lr_mul:.3f}, ' - f'upsample={self.scale_factor}, ' - f'upsample_filter={self.filter_kernel}, ' - f'act={self.activation_type}, ' - f'clamp={self.conv_clamp}') - - def forward(self, x, runtime_gain=1.0, impl='cuda'): - dtype = x.dtype - - weight = self.weight - if self.wscale != 1.0: - weight = weight * self.wscale - bias = None - if self.bias is not None: - bias = self.bias.to(dtype) - if self.bscale != 1.0: - bias = bias * self.bscale - - if self.scale_factor == 1: # Native convolution without upsampling. - padding = self.kernel_size // 2 - x = conv2d_gradfix.conv2d( - x, weight.to(dtype), stride=1, padding=padding, impl=impl) - else: # Convolution with upsampling. - up = self.scale_factor - f = self.filter - # When kernel size = 1, use filtering function for upsampling. - if self.kernel_size == 1: - padding = self.filter_padding - x = conv2d_gradfix.conv2d( - x, weight.to(dtype), stride=1, padding=0, impl=impl) - x = upfirdn2d.upfirdn2d( - x, f, up=up, padding=padding, gain=up ** 2, impl=impl) - # When kernel size != 1, use transpose convolution for upsampling. - else: - # Following codes are borrowed from - # https://github.com/NVlabs/stylegan2-ada-pytorch - px0, px1, py0, py1 = self.filter_padding - kh, kw = weight.shape[2:] - px0 = px0 - (kw - 1) - px1 = px1 - (kw - up) - py0 = py0 - (kh - 1) - py1 = py1 - (kh - up) - pxt = max(min(-px0, -px1), 0) - pyt = max(min(-py0, -py1), 0) - weight = weight.transpose(0, 1) - padding = (pyt, pxt) - x = conv2d_gradfix.conv_transpose2d( - x, weight.to(dtype), stride=up, padding=padding, impl=impl) - padding = (px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt) - x = upfirdn2d.upfirdn2d( - x, f, up=1, padding=padding, gain=up ** 2, impl=impl) - - act_gain = self.act_gain * runtime_gain - act_clamp = None - if self.conv_clamp is not None: - act_clamp = self.conv_clamp * runtime_gain - x = bias_act.bias_act(x, bias, - act=self.activation_type, - gain=act_gain, - clamp=act_clamp, - impl=impl) - - assert x.dtype == dtype - return x - - -class ModulateConvLayer(nn.Module): - """Implements the convolutional layer with style modulation.""" - - def __init__(self, - in_channels, - out_channels, - resolution, - w_dim, - kernel_size, - add_bias, - scale_factor, - filter_kernel, - demodulate, - use_wscale, - wscale_gain, - lr_mul, - noise_type, - activation_type, - conv_clamp, - eps): - """Initializes with layer settings. - - Args: - in_channels: Number of channels of the input tensor. - out_channels: Number of channels of the output tensor. - resolution: Resolution of the output tensor. - w_dim: Dimension of W space for style modulation. - kernel_size: Size of the convolutional kernels. - add_bias: Whether to add bias onto the convolutional result. - scale_factor: Scale factor for upsampling. - filter_kernel: Kernel used for filtering. - demodulate: Whether to perform style demodulation. - use_wscale: Whether to use weight scaling. - wscale_gain: Gain factor for weight scaling. - lr_mul: Learning multiplier for both weight and bias. - noise_type: Type of noise added to the feature map after the - convolution (if needed). Support `none`, `spatial` and - `channel`. - activation_type: Type of activation. - conv_clamp: A threshold to clamp the output of convolution layers to - avoid overflow under FP16 training. - eps: A small value to avoid divide overflow. - """ - super().__init__() - - self.in_channels = in_channels - self.out_channels = out_channels - self.resolution = resolution - self.w_dim = w_dim - self.kernel_size = kernel_size - self.add_bias = add_bias - self.scale_factor = scale_factor - self.filter_kernel = filter_kernel - self.demodulate = demodulate - self.use_wscale = use_wscale - self.wscale_gain = wscale_gain - self.lr_mul = lr_mul - self.noise_type = noise_type.lower() - self.activation_type = activation_type - self.conv_clamp = conv_clamp - self.eps = eps - - self.space_of_latent = 'W' - - # Set up weight. - weight_shape = (out_channels, in_channels, kernel_size, kernel_size) - fan_in = kernel_size * kernel_size * in_channels - wscale = wscale_gain / np.sqrt(fan_in) - if use_wscale: - self.weight = nn.Parameter(torch.randn(*weight_shape) / lr_mul) - self.wscale = wscale * lr_mul - else: - self.weight = nn.Parameter( - torch.randn(*weight_shape) * wscale / lr_mul) - self.wscale = lr_mul - - # Set up bias. - if add_bias: - self.bias = nn.Parameter(torch.zeros(out_channels)) - self.bscale = lr_mul - else: - self.bias = None - self.act_gain = bias_act.activation_funcs[activation_type].def_gain - - # Set up style. - self.style = DenseLayer(in_channels=w_dim, - out_channels=in_channels, - add_bias=True, - init_bias=1.0, - use_wscale=use_wscale, - wscale_gain=wscale_gain, - lr_mul=lr_mul, - activation_type='linear') - - # Set up noise. - if self.noise_type != 'none': - self.noise_strength = nn.Parameter(torch.zeros(())) - if self.noise_type == 'spatial': - self.register_buffer( - 'noise', torch.randn(1, 1, resolution, resolution)) - elif self.noise_type == 'channel': - self.register_buffer( - 'noise', torch.randn(1, out_channels, 1, 1)) - else: - raise NotImplementedError(f'Not implemented noise type: ' - f'`{self.noise_type}`!') - - if scale_factor > 1: - assert filter_kernel is not None - self.register_buffer( - 'filter', upfirdn2d.setup_filter(filter_kernel)) - fh, fw = self.filter.shape - self.filter_padding = ( - kernel_size // 2 + (fw + scale_factor - 1) // 2, - kernel_size // 2 + (fw - scale_factor) // 2, - kernel_size // 2 + (fh + scale_factor - 1) // 2, - kernel_size // 2 + (fh - scale_factor) // 2) - - def extra_repr(self): - return (f'in_ch={self.in_channels}, ' - f'out_ch={self.out_channels}, ' - f'ksize={self.kernel_size}, ' - f'wscale_gain={self.wscale_gain:.3f}, ' - f'bias={self.add_bias}, ' - f'lr_mul={self.lr_mul:.3f}, ' - f'upsample={self.scale_factor}, ' - f'upsample_filter={self.filter_kernel}, ' - f'demodulate={self.demodulate}, ' - f'noise_type={self.noise_type}, ' - f'act={self.activation_type}, ' - f'clamp={self.conv_clamp}') - - def forward_style(self, w, impl='cuda'): - """Gets style code from the given input. - - More specifically, if the input is from W-Space, it will be projected by - an affine transformation. If it is from the Style Space (Y-Space), no - operation is required. - - NOTE: For codes from Y-Space, we use slicing to make sure the dimension - is correct, in case that the code is padded before fed into this layer. - """ - space_of_latent = self.space_of_latent.upper() - if space_of_latent == 'W': - if w.ndim != 2 or w.shape[1] != self.w_dim: - raise ValueError(f'The input tensor should be with shape ' - f'[batch_size, w_dim], where ' - f'`w_dim` equals to {self.w_dim}!\n' - f'But `{w.shape}` is received!') - style = self.style(w, impl=impl) - elif space_of_latent == 'Y': - if w.ndim != 2 or w.shape[1] < self.in_channels: - raise ValueError(f'The input tensor should be with shape ' - f'[batch_size, y_dim], where ' - f'`y_dim` equals to {self.in_channels}!\n' - f'But `{w.shape}` is received!') - style = w[:, :self.in_channels] - else: - raise NotImplementedError(f'Not implemented `space_of_latent`: ' - f'`{space_of_latent}`!') - return style - - def forward(self, - x, - w, - runtime_gain=1.0, - noise_mode='const', - fused_modulate=False, - impl='cuda'): - dtype = x.dtype - N, C, H, W = x.shape - - fused_modulate = (fused_modulate and - not self.training and - (dtype == torch.float32 or N == 1)) - - weight = self.weight - out_ch, in_ch, kh, kw = weight.shape - assert in_ch == C - - # Affine on `w`. - style = self.forward_style(w, impl=impl) - if not self.demodulate: - _style = style * self.wscale # Equivalent to scaling weight. - else: - _style = style - - # Prepare noise. - noise = None - noise_mode = noise_mode.lower() - if self.noise_type != 'none' and noise_mode != 'none': - if noise_mode == 'random': - noise = torch.randn((N, *self.noise.shape[1:]), device=x.device) - elif noise_mode == 'const': - noise = self.noise - else: - raise ValueError(f'Unknown noise mode `{noise_mode}`!') - noise = (noise * self.noise_strength).to(dtype) - - # Pre-normalize inputs to avoid FP16 overflow. - if dtype == torch.float16 and self.demodulate: - weight_max = weight.norm(float('inf'), dim=(1, 2, 3), keepdim=True) - weight = weight * (self.wscale / weight_max) - style_max = _style.norm(float('inf'), dim=1, keepdim=True) - _style = _style / style_max - - if self.demodulate or fused_modulate: - _weight = weight.unsqueeze(0) - _weight = _weight * _style.reshape(N, 1, in_ch, 1, 1) - if self.demodulate: - decoef = (_weight.square().sum(dim=(2, 3, 4)) + self.eps).rsqrt() - if self.demodulate and fused_modulate: - _weight = _weight * decoef.reshape(N, out_ch, 1, 1, 1) - - if not fused_modulate: - x = x * _style.to(dtype).reshape(N, in_ch, 1, 1) - w = weight.to(dtype) - groups = 1 - else: # Use group convolution to fuse style modulation and convolution. - x = x.reshape(1, N * in_ch, H, W) - w = _weight.reshape(N * out_ch, in_ch, kh, kw).to(dtype) - groups = N - - if self.scale_factor == 1: # Native convolution without upsampling. - up = 1 - padding = self.kernel_size // 2 - x = conv2d_gradfix.conv2d( - x, w, stride=1, padding=padding, groups=groups, impl=impl) - else: # Convolution with upsampling. - up = self.scale_factor - f = self.filter - # When kernel size = 1, use filtering function for upsampling. - if self.kernel_size == 1: - padding = self.filter_padding - x = conv2d_gradfix.conv2d( - x, w, stride=1, padding=0, groups=groups, impl=impl) - x = upfirdn2d.upfirdn2d( - x, f, up=up, padding=padding, gain=up ** 2, impl=impl) - # When kernel size != 1, use stride convolution for upsampling. - else: - # Following codes are borrowed from - # https://github.com/NVlabs/stylegan2-ada-pytorch - px0, px1, py0, py1 = self.filter_padding - px0 = px0 - (kw - 1) - px1 = px1 - (kw - up) - py0 = py0 - (kh - 1) - py1 = py1 - (kh - up) - pxt = max(min(-px0, -px1), 0) - pyt = max(min(-py0, -py1), 0) - if groups == 1: - w = w.transpose(0, 1) - else: - w = w.reshape(N, out_ch, in_ch, kh, kw) - w = w.transpose(1, 2) - w = w.reshape(N * in_ch, out_ch, kh, kw) - padding = (pyt, pxt) - x = conv2d_gradfix.conv_transpose2d( - x, w, stride=up, padding=padding, groups=groups, impl=impl) - padding = (px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt) - x = upfirdn2d.upfirdn2d( - x, f, up=1, padding=padding, gain=up ** 2, impl=impl) - - if not fused_modulate: - if self.demodulate: - decoef = decoef.to(dtype).reshape(N, out_ch, 1, 1) - if self.demodulate and noise is not None: - x = fma.fma(x, decoef, noise, impl=impl) - else: - if self.demodulate: - x = x * decoef - if noise is not None: - x = x + noise - else: - x = x.reshape(N, out_ch, H * up, W * up) - if noise is not None: - x = x + noise - - bias = None - if self.bias is not None: - bias = self.bias.to(dtype) - if self.bscale != 1.0: - bias = bias * self.bscale - - if self.activation_type == 'linear': # Shortcut for output layer. - x = bias_act.bias_act( - x, bias, act='linear', clamp=self.conv_clamp, impl=impl) - else: - act_gain = self.act_gain * runtime_gain - act_clamp = None - if self.conv_clamp is not None: - act_clamp = self.conv_clamp * runtime_gain - x = bias_act.bias_act(x, bias, - act=self.activation_type, - gain=act_gain, - clamp=act_clamp, - impl=impl) - - assert x.dtype == dtype - assert style.dtype == torch.float32 - return x, style - - -class DenseLayer(nn.Module): - """Implements the dense layer.""" - - def __init__(self, - in_channels, - out_channels, - add_bias, - init_bias, - use_wscale, - wscale_gain, - lr_mul, - activation_type): - """Initializes with layer settings. - - Args: - in_channels: Number of channels of the input tensor. - out_channels: Number of channels of the output tensor. - add_bias: Whether to add bias onto the fully-connected result. - init_bias: The initial bias value before training. - use_wscale: Whether to use weight scaling. - wscale_gain: Gain factor for weight scaling. - lr_mul: Learning multiplier for both weight and bias. - activation_type: Type of activation. - """ - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.add_bias = add_bias - self.init_bias = init_bias - self.use_wscale = use_wscale - self.wscale_gain = wscale_gain - self.lr_mul = lr_mul - self.activation_type = activation_type - - weight_shape = (out_channels, in_channels) - wscale = wscale_gain / np.sqrt(in_channels) - if use_wscale: - self.weight = nn.Parameter(torch.randn(*weight_shape) / lr_mul) - self.wscale = wscale * lr_mul - else: - self.weight = nn.Parameter( - torch.randn(*weight_shape) * wscale / lr_mul) - self.wscale = lr_mul - - if add_bias: - init_bias = np.float32(init_bias) / lr_mul - self.bias = nn.Parameter(torch.full([out_channels], init_bias)) - self.bscale = lr_mul - else: - self.bias = None - - def extra_repr(self): - return (f'in_ch={self.in_channels}, ' - f'out_ch={self.out_channels}, ' - f'wscale_gain={self.wscale_gain:.3f}, ' - f'bias={self.add_bias}, ' - f'init_bias={self.init_bias}, ' - f'lr_mul={self.lr_mul:.3f}, ' - f'act={self.activation_type}') - - def forward(self, x, impl='cuda'): - dtype = x.dtype - - if x.ndim != 2: - x = x.flatten(start_dim=1) - - weight = self.weight.to(dtype) * self.wscale - bias = None - if self.bias is not None: - bias = self.bias.to(dtype) - if self.bscale != 1.0: - bias = bias * self.bscale - - # Fast pass for linear activation. - if self.activation_type == 'linear' and bias is not None: - x = torch.addmm(bias.unsqueeze(0), x, weight.t()) - else: - x = x.matmul(weight.t()) - x = bias_act.bias_act(x, bias, act=self.activation_type, impl=impl) - - assert x.dtype == dtype - return x - -# pylint: enable=missing-function-docstring diff --git a/spaces/Iceclear/StableSR/StableSR/basicsr/data/realesrgan_dataset.py b/spaces/Iceclear/StableSR/StableSR/basicsr/data/realesrgan_dataset.py deleted file mode 100644 index 9b7c0603d8353f5457b0dd96f9a9a876a192d113..0000000000000000000000000000000000000000 --- a/spaces/Iceclear/StableSR/StableSR/basicsr/data/realesrgan_dataset.py +++ /dev/null @@ -1,242 +0,0 @@ -import cv2 -import math -import numpy as np -import os -import os.path as osp -import random -import time -import torch -from pathlib import Path -from torch.utils import data as data - -from basicsr.data.degradations import circular_lowpass_kernel, random_mixed_kernels -from basicsr.data.transforms import augment -from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor -from basicsr.utils.registry import DATASET_REGISTRY - -@DATASET_REGISTRY.register(suffix='basicsr') -class RealESRGANDataset(data.Dataset): - """Modified dataset based on the dataset used for Real-ESRGAN model: - Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. - - It loads gt (Ground-Truth) images, and augments them. - It also generates blur kernels and sinc kernels for generating low-quality images. - Note that the low-quality images are processed in tensors on GPUS for faster processing. - - Args: - opt (dict): Config for train datasets. It contains the following keys: - dataroot_gt (str): Data root path for gt. - meta_info (str): Path for meta information file. - io_backend (dict): IO backend type and other kwarg. - use_hflip (bool): Use horizontal flips. - use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). - Please see more options in the codes. - """ - - def __init__(self, opt): - super(RealESRGANDataset, self).__init__() - self.opt = opt - self.file_client = None - self.io_backend_opt = opt['io_backend'] - if 'crop_size' in opt: - self.crop_size = opt['crop_size'] - else: - self.crop_size = 512 - if 'image_type' not in opt: - opt['image_type'] = 'png' - - # support multiple type of data: file path and meta data, remove support of lmdb - self.paths = [] - if 'meta_info' in opt: - with open(self.opt['meta_info']) as fin: - paths = [line.strip().split(' ')[0] for line in fin] - self.paths = [v for v in paths] - if 'meta_num' in opt: - self.paths = sorted(self.paths)[:opt['meta_num']] - if 'gt_path' in opt: - if isinstance(opt['gt_path'], str): - self.paths.extend(sorted([str(x) for x in Path(opt['gt_path']).glob('*.'+opt['image_type'])])) - else: - self.paths.extend(sorted([str(x) for x in Path(opt['gt_path'][0]).glob('*.'+opt['image_type'])])) - if len(opt['gt_path']) > 1: - for i in range(len(opt['gt_path'])-1): - self.paths.extend(sorted([str(x) for x in Path(opt['gt_path'][i+1]).glob('*.'+opt['image_type'])])) - if 'imagenet_path' in opt: - class_list = os.listdir(opt['imagenet_path']) - for class_file in class_list: - self.paths.extend(sorted([str(x) for x in Path(os.path.join(opt['imagenet_path'], class_file)).glob('*.'+'JPEG')])) - if 'face_gt_path' in opt: - if isinstance(opt['face_gt_path'], str): - face_list = sorted([str(x) for x in Path(opt['face_gt_path']).glob('*.'+opt['image_type'])]) - self.paths.extend(face_list[:opt['num_face']]) - else: - face_list = sorted([str(x) for x in Path(opt['face_gt_path'][0]).glob('*.'+opt['image_type'])]) - self.paths.extend(face_list[:opt['num_face']]) - if len(opt['face_gt_path']) > 1: - for i in range(len(opt['face_gt_path'])-1): - self.paths.extend(sorted([str(x) for x in Path(opt['face_gt_path'][0]).glob('*.'+opt['image_type'])])[:opt['num_face']]) - - # limit number of pictures for test - if 'num_pic' in opt: - if 'val' or 'test' in opt: - random.shuffle(self.paths) - self.paths = self.paths[:opt['num_pic']] - else: - self.paths = self.paths[:opt['num_pic']] - - if 'mul_num' in opt: - self.paths = self.paths * opt['mul_num'] - # print('>>>>>>>>>>>>>>>>>>>>>') - # print(self.paths) - - # blur settings for the first degradation - self.blur_kernel_size = opt['blur_kernel_size'] - self.kernel_list = opt['kernel_list'] - self.kernel_prob = opt['kernel_prob'] # a list for each kernel probability - self.blur_sigma = opt['blur_sigma'] - self.betag_range = opt['betag_range'] # betag used in generalized Gaussian blur kernels - self.betap_range = opt['betap_range'] # betap used in plateau blur kernels - self.sinc_prob = opt['sinc_prob'] # the probability for sinc filters - - # blur settings for the second degradation - self.blur_kernel_size2 = opt['blur_kernel_size2'] - self.kernel_list2 = opt['kernel_list2'] - self.kernel_prob2 = opt['kernel_prob2'] - self.blur_sigma2 = opt['blur_sigma2'] - self.betag_range2 = opt['betag_range2'] - self.betap_range2 = opt['betap_range2'] - self.sinc_prob2 = opt['sinc_prob2'] - - # a final sinc filter - self.final_sinc_prob = opt['final_sinc_prob'] - - self.kernel_range = [2 * v + 1 for v in range(3, 11)] # kernel size ranges from 7 to 21 - # TODO: kernel range is now hard-coded, should be in the configure file - self.pulse_tensor = torch.zeros(21, 21).float() # convolving with pulse tensor brings no blurry effect - self.pulse_tensor[10, 10] = 1 - - def __getitem__(self, index): - if self.file_client is None: - self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt) - - # -------------------------------- Load gt images -------------------------------- # - # Shape: (h, w, c); channel order: BGR; image range: [0, 1], float32. - gt_path = self.paths[index] - # avoid errors caused by high latency in reading files - retry = 3 - while retry > 0: - try: - img_bytes = self.file_client.get(gt_path, 'gt') - except (IOError, OSError) as e: - # logger = get_root_logger() - # logger.warn(f'File client error: {e}, remaining retry times: {retry - 1}') - # change another file to read - index = random.randint(0, self.__len__()-1) - gt_path = self.paths[index] - time.sleep(1) # sleep 1s for occasional server congestion - else: - break - finally: - retry -= 1 - img_gt = imfrombytes(img_bytes, float32=True) - # filter the dataset and remove images with too low quality - img_size = os.path.getsize(gt_path) - img_size = img_size/1024 - - while img_gt.shape[0] * img_gt.shape[1] < 384*384 or img_size<100: - index = random.randint(0, self.__len__()-1) - gt_path = self.paths[index] - - time.sleep(0.1) # sleep 1s for occasional server congestion - img_bytes = self.file_client.get(gt_path, 'gt') - img_gt = imfrombytes(img_bytes, float32=True) - img_size = os.path.getsize(gt_path) - img_size = img_size/1024 - - # -------------------- Do augmentation for training: flip, rotation -------------------- # - img_gt = augment(img_gt, self.opt['use_hflip'], self.opt['use_rot']) - - # crop or pad to 400 - # TODO: 400 is hard-coded. You may change it accordingly - h, w = img_gt.shape[0:2] - crop_pad_size = self.crop_size - # pad - if h < crop_pad_size or w < crop_pad_size: - pad_h = max(0, crop_pad_size - h) - pad_w = max(0, crop_pad_size - w) - img_gt = cv2.copyMakeBorder(img_gt, 0, pad_h, 0, pad_w, cv2.BORDER_REFLECT_101) - # crop - if img_gt.shape[0] > crop_pad_size or img_gt.shape[1] > crop_pad_size: - h, w = img_gt.shape[0:2] - # randomly choose top and left coordinates - top = random.randint(0, h - crop_pad_size) - left = random.randint(0, w - crop_pad_size) - # top = (h - crop_pad_size) // 2 -1 - # left = (w - crop_pad_size) // 2 -1 - img_gt = img_gt[top:top + crop_pad_size, left:left + crop_pad_size, ...] - - # ------------------------ Generate kernels (used in the first degradation) ------------------------ # - kernel_size = random.choice(self.kernel_range) - if np.random.uniform() < self.opt['sinc_prob']: - # this sinc filter setting is for kernels ranging from [7, 21] - if kernel_size < 13: - omega_c = np.random.uniform(np.pi / 3, np.pi) - else: - omega_c = np.random.uniform(np.pi / 5, np.pi) - kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False) - else: - kernel = random_mixed_kernels( - self.kernel_list, - self.kernel_prob, - kernel_size, - self.blur_sigma, - self.blur_sigma, [-math.pi, math.pi], - self.betag_range, - self.betap_range, - noise_range=None) - # pad kernel - pad_size = (21 - kernel_size) // 2 - kernel = np.pad(kernel, ((pad_size, pad_size), (pad_size, pad_size))) - - # ------------------------ Generate kernels (used in the second degradation) ------------------------ # - kernel_size = random.choice(self.kernel_range) - if np.random.uniform() < self.opt['sinc_prob2']: - if kernel_size < 13: - omega_c = np.random.uniform(np.pi / 3, np.pi) - else: - omega_c = np.random.uniform(np.pi / 5, np.pi) - kernel2 = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False) - else: - kernel2 = random_mixed_kernels( - self.kernel_list2, - self.kernel_prob2, - kernel_size, - self.blur_sigma2, - self.blur_sigma2, [-math.pi, math.pi], - self.betag_range2, - self.betap_range2, - noise_range=None) - - # pad kernel - pad_size = (21 - kernel_size) // 2 - kernel2 = np.pad(kernel2, ((pad_size, pad_size), (pad_size, pad_size))) - - # ------------------------------------- the final sinc kernel ------------------------------------- # - if np.random.uniform() < self.opt['final_sinc_prob']: - kernel_size = random.choice(self.kernel_range) - omega_c = np.random.uniform(np.pi / 3, np.pi) - sinc_kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=21) - sinc_kernel = torch.FloatTensor(sinc_kernel) - else: - sinc_kernel = self.pulse_tensor - - # BGR to RGB, HWC to CHW, numpy to tensor - img_gt = img2tensor([img_gt], bgr2rgb=True, float32=True)[0] - kernel = torch.FloatTensor(kernel) - kernel2 = torch.FloatTensor(kernel2) - - return_d = {'gt': img_gt, 'kernel1': kernel, 'kernel2': kernel2, 'sinc_kernel': sinc_kernel, 'gt_path': gt_path} - return return_d - - def __len__(self): - return len(self.paths) diff --git a/spaces/Iceclear/StableSR/StableSR/basicsr/utils/lmdb_util.py b/spaces/Iceclear/StableSR/StableSR/basicsr/utils/lmdb_util.py deleted file mode 100644 index a2b45ce01d5e32ddbf8354d71fd1c8678bede822..0000000000000000000000000000000000000000 --- a/spaces/Iceclear/StableSR/StableSR/basicsr/utils/lmdb_util.py +++ /dev/null @@ -1,199 +0,0 @@ -import cv2 -import lmdb -import sys -from multiprocessing import Pool -from os import path as osp -from tqdm import tqdm - - -def make_lmdb_from_imgs(data_path, - lmdb_path, - img_path_list, - keys, - batch=5000, - compress_level=1, - multiprocessing_read=False, - n_thread=40, - map_size=None): - """Make lmdb from images. - - Contents of lmdb. The file structure is: - - :: - - example.lmdb - ├── data.mdb - ├── lock.mdb - ├── meta_info.txt - - The data.mdb and lock.mdb are standard lmdb files and you can refer to - https://lmdb.readthedocs.io/en/release/ for more details. - - The meta_info.txt is a specified txt file to record the meta information - of our datasets. It will be automatically created when preparing - datasets by our provided dataset tools. - Each line in the txt file records 1)image name (with extension), - 2)image shape, and 3)compression level, separated by a white space. - - For example, the meta information could be: - `000_00000000.png (720,1280,3) 1`, which means: - 1) image name (with extension): 000_00000000.png; - 2) image shape: (720,1280,3); - 3) compression level: 1 - - We use the image name without extension as the lmdb key. - - If `multiprocessing_read` is True, it will read all the images to memory - using multiprocessing. Thus, your server needs to have enough memory. - - Args: - data_path (str): Data path for reading images. - lmdb_path (str): Lmdb save path. - img_path_list (str): Image path list. - keys (str): Used for lmdb keys. - batch (int): After processing batch images, lmdb commits. - Default: 5000. - compress_level (int): Compress level when encoding images. Default: 1. - multiprocessing_read (bool): Whether use multiprocessing to read all - the images to memory. Default: False. - n_thread (int): For multiprocessing. - map_size (int | None): Map size for lmdb env. If None, use the - estimated size from images. Default: None - """ - - assert len(img_path_list) == len(keys), ('img_path_list and keys should have the same length, ' - f'but got {len(img_path_list)} and {len(keys)}') - print(f'Create lmdb for {data_path}, save to {lmdb_path}...') - print(f'Totoal images: {len(img_path_list)}') - if not lmdb_path.endswith('.lmdb'): - raise ValueError("lmdb_path must end with '.lmdb'.") - if osp.exists(lmdb_path): - print(f'Folder {lmdb_path} already exists. Exit.') - sys.exit(1) - - if multiprocessing_read: - # read all the images to memory (multiprocessing) - dataset = {} # use dict to keep the order for multiprocessing - shapes = {} - print(f'Read images with multiprocessing, #thread: {n_thread} ...') - pbar = tqdm(total=len(img_path_list), unit='image') - - def callback(arg): - """get the image data and update pbar.""" - key, dataset[key], shapes[key] = arg - pbar.update(1) - pbar.set_description(f'Read {key}') - - pool = Pool(n_thread) - for path, key in zip(img_path_list, keys): - pool.apply_async(read_img_worker, args=(osp.join(data_path, path), key, compress_level), callback=callback) - pool.close() - pool.join() - pbar.close() - print(f'Finish reading {len(img_path_list)} images.') - - # create lmdb environment - if map_size is None: - # obtain data size for one image - img = cv2.imread(osp.join(data_path, img_path_list[0]), cv2.IMREAD_UNCHANGED) - _, img_byte = cv2.imencode('.png', img, [cv2.IMWRITE_PNG_COMPRESSION, compress_level]) - data_size_per_img = img_byte.nbytes - print('Data size per image is: ', data_size_per_img) - data_size = data_size_per_img * len(img_path_list) - map_size = data_size * 10 - - env = lmdb.open(lmdb_path, map_size=map_size) - - # write data to lmdb - pbar = tqdm(total=len(img_path_list), unit='chunk') - txn = env.begin(write=True) - txt_file = open(osp.join(lmdb_path, 'meta_info.txt'), 'w') - for idx, (path, key) in enumerate(zip(img_path_list, keys)): - pbar.update(1) - pbar.set_description(f'Write {key}') - key_byte = key.encode('ascii') - if multiprocessing_read: - img_byte = dataset[key] - h, w, c = shapes[key] - else: - _, img_byte, img_shape = read_img_worker(osp.join(data_path, path), key, compress_level) - h, w, c = img_shape - - txn.put(key_byte, img_byte) - # write meta information - txt_file.write(f'{key}.png ({h},{w},{c}) {compress_level}\n') - if idx % batch == 0: - txn.commit() - txn = env.begin(write=True) - pbar.close() - txn.commit() - env.close() - txt_file.close() - print('\nFinish writing lmdb.') - - -def read_img_worker(path, key, compress_level): - """Read image worker. - - Args: - path (str): Image path. - key (str): Image key. - compress_level (int): Compress level when encoding images. - - Returns: - str: Image key. - byte: Image byte. - tuple[int]: Image shape. - """ - - img = cv2.imread(path, cv2.IMREAD_UNCHANGED) - if img.ndim == 2: - h, w = img.shape - c = 1 - else: - h, w, c = img.shape - _, img_byte = cv2.imencode('.png', img, [cv2.IMWRITE_PNG_COMPRESSION, compress_level]) - return (key, img_byte, (h, w, c)) - - -class LmdbMaker(): - """LMDB Maker. - - Args: - lmdb_path (str): Lmdb save path. - map_size (int): Map size for lmdb env. Default: 1024 ** 4, 1TB. - batch (int): After processing batch images, lmdb commits. - Default: 5000. - compress_level (int): Compress level when encoding images. Default: 1. - """ - - def __init__(self, lmdb_path, map_size=1024**4, batch=5000, compress_level=1): - if not lmdb_path.endswith('.lmdb'): - raise ValueError("lmdb_path must end with '.lmdb'.") - if osp.exists(lmdb_path): - print(f'Folder {lmdb_path} already exists. Exit.') - sys.exit(1) - - self.lmdb_path = lmdb_path - self.batch = batch - self.compress_level = compress_level - self.env = lmdb.open(lmdb_path, map_size=map_size) - self.txn = self.env.begin(write=True) - self.txt_file = open(osp.join(lmdb_path, 'meta_info.txt'), 'w') - self.counter = 0 - - def put(self, img_byte, key, img_shape): - self.counter += 1 - key_byte = key.encode('ascii') - self.txn.put(key_byte, img_byte) - # write meta information - h, w, c = img_shape - self.txt_file.write(f'{key}.png ({h},{w},{c}) {self.compress_level}\n') - if self.counter % self.batch == 0: - self.txn.commit() - self.txn = self.env.begin(write=True) - - def close(self): - self.txn.commit() - self.env.close() - self.txt_file.close() diff --git a/spaces/JammyMachina/streamlit-jam-machine/utils.py b/spaces/JammyMachina/streamlit-jam-machine/utils.py deleted file mode 100644 index 37d5527f40916eeb539d0dd87f822a5ecc44511e..0000000000000000000000000000000000000000 --- a/spaces/JammyMachina/streamlit-jam-machine/utils.py +++ /dev/null @@ -1,246 +0,0 @@ -from datetime import datetime -from miditok import Event, MIDILike -import os -import json -from time import perf_counter -from joblib import Parallel, delayed -from zipfile import ZipFile, ZIP_DEFLATED -from scipy.io.wavfile import write -import numpy as np -from pydub import AudioSegment -import shutil - - -def writeToFile(path, content): - if type(content) is dict: - with open(f"{path}", "w") as json_file: - json.dump(content, json_file) - else: - if type(content) is not str: - content = str(content) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w") as f: - f.write(content) - - -# Function to read from text from txt file: -def readFromFile(path, isJSON=False): - with open(path, "r") as f: - if isJSON: - return json.load(f) - else: - return f.read() - - -def chain(input, funcs, *params): - res = input - for func in funcs: - try: - res = func(res, *params) - except TypeError: - res = func(res) - return res - - -def to_beat_str(value, beat_res=8): - values = [ - int(int(value * beat_res) / beat_res), - int(int(value * beat_res) % beat_res), - beat_res, - ] - return ".".join(map(str, values)) - - -def to_base10(beat_str): - integer, decimal, base = split_dots(beat_str) - return integer + decimal / base - - -def split_dots(value): - return list(map(int, value.split("."))) - - -def compute_list_average(l): - return sum(l) / len(l) - - -def get_datetime(): - return datetime.now().strftime("%Y%m%d_%H%M%S") - - -def get_text(event): - match event.type: - case "Piece-Start": - return "PIECE_START " - case "Track-Start": - return "TRACK_START " - case "Track-End": - return "TRACK_END " - case "Instrument": - return f"INST={event.value} " - case "Bar-Start": - return "BAR_START " - case "Bar-End": - return "BAR_END " - case "Time-Shift": - return f"TIME_SHIFT={event.value} " - case "Note-On": - return f"NOTE_ON={event.value} " - case "Note-Off": - return f"NOTE_OFF={event.value} " - case _: - return "" - - -def get_event(text, value=None): - match text: - case "PIECE_START": - return Event("Piece-Start", value) - case "TRACK_START": - return None - case "TRACK_END": - return None - case "INST": - return Event("Instrument", value) - case "BAR_START": - return Event("Bar-Start", value) - case "BAR_END": - return Event("Bar-End", value) - case "TIME_SHIFT": - return Event("Time-Shift", value) - case "TIME_DELTA": - return Event("Time-Shift", to_beat_str(int(value) / 4)) - case "NOTE_ON": - return Event("Note-On", value) - case "NOTE_OFF": - return Event("Note-Off", value) - case _: - return None - - -# TODO: Make this singleton -def get_miditok(): - pitch_range = range(0, 140) # was (21, 109) - beat_res = {(0, 400): 8} - return MIDILike(pitch_range, beat_res) - - -class WriteTextMidiToFile: # utils saving to file - def __init__(self, generate_midi, output_path): - self.generated_midi = generate_midi.generated_piece - self.output_path = output_path - self.hyperparameter_and_bars = generate_midi.piece_by_track - - def hashing_seq(self): - self.current_time = get_datetime() - self.output_path_filename = f"{self.output_path}/{self.current_time}.json" - - def wrapping_seq_hyperparameters_in_dict(self): - # assert type(self.generated_midi) is str, "error: generate_midi must be a string" - # assert ( - # type(self.hyperparameter_dict) is dict - # ), "error: feature_dict must be a dictionnary" - return { - "generate_midi": self.generated_midi, - "hyperparameters_and_bars": self.hyperparameter_and_bars, - } - - def text_midi_to_file(self): - self.hashing_seq() - output_dict = self.wrapping_seq_hyperparameters_in_dict() - print(f"Token generate_midi written: {self.output_path_filename}") - writeToFile(self.output_path_filename, output_dict) - return self.output_path_filename - - -def get_files(directory, extension, recursive=False): - """ - Given a directory, get a list of the file paths of all files matching the - specified file extension. - directory: the directory to search as a Path object - extension: the file extension to match as a string - recursive: whether to search recursively in the directory or not - """ - if recursive: - return list(directory.rglob(f"*.{extension}")) - else: - return list(directory.glob(f"*.{extension}")) - - -def timeit(func): - def wrapper(*args, **kwargs): - start = perf_counter() - result = func(*args, **kwargs) - end = perf_counter() - print(f"{func.__name__} took {end - start:.2f} seconds to run.") - return result - - return wrapper - - -class FileCompressor: - def __init__(self, input_directory, output_directory, n_jobs=-1): - self.input_directory = input_directory - self.output_directory = output_directory - self.n_jobs = n_jobs - - # File compression and decompression - def unzip_file(self, file): - """uncompress single zip file""" - with ZipFile(file, "r") as zip_ref: - zip_ref.extractall(self.output_directory) - - def zip_file(self, file): - """compress a single text file to a new zip file and delete the original""" - output_file = self.output_directory / (file.stem + ".zip") - with ZipFile(output_file, "w") as zip_ref: - zip_ref.write(file, arcname=file.name, compress_type=ZIP_DEFLATED) - file.unlink() - - @timeit - def unzip(self): - """uncompress all zip files in folder""" - files = get_files(self.input_directory, extension="zip") - Parallel(n_jobs=self.n_jobs)(delayed(self.unzip_file)(file) for file in files) - - @timeit - def zip(self): - """compress all text files in folder to new zip files and remove the text files""" - files = get_files(self.output_directory, extension="txt") - Parallel(n_jobs=self.n_jobs)(delayed(self.zip_file)(file) for file in files) - - -def load_jsonl(filepath): - """Load a jsonl file""" - with open(filepath, "r") as f: - data = [json.loads(line) for line in f] - return data - - -def write_mp3(waveform, output_path, bitrate="92k"): - """ - Write a waveform to an mp3 file. - output_path: Path object for the output mp3 file - waveform: numpy array of the waveform - bitrate: bitrate of the mp3 file (64k, 92k, 128k, 256k, 312k) - """ - # write the wav file - wav_path = output_path.with_suffix(".wav") - write(wav_path, 44100, waveform.astype(np.float32)) - # compress the wav file as mp3 - AudioSegment.from_wav(wav_path).export(output_path, format="mp3", bitrate=bitrate) - # remove the wav file - wav_path.unlink() - - -def copy_file(input_file, output_dir): - """Copy an input file to the output_dir""" - output_file = output_dir / input_file.name - shutil.copy(input_file, output_file) - - -def index_has_substring(list, substring): - for i, s in enumerate(list): - if substring in s: - return i - return -1 diff --git a/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/archs/rrdbnet_arch.py b/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/archs/rrdbnet_arch.py deleted file mode 100644 index 49a2d6c204557cba53ada7550deb587541855cfb..0000000000000000000000000000000000000000 --- a/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/archs/rrdbnet_arch.py +++ /dev/null @@ -1,119 +0,0 @@ -import torch -from torch import nn as nn -from torch.nn import functional as F - -from basicsr.utils.registry import ARCH_REGISTRY -from .arch_util import default_init_weights, make_layer, pixel_unshuffle - - -class ResidualDenseBlock(nn.Module): - """Residual Dense Block. - - Used in RRDB block in ESRGAN. - - Args: - num_feat (int): Channel number of intermediate features. - num_grow_ch (int): Channels for each growth. - """ - - def __init__(self, num_feat=64, num_grow_ch=32): - super(ResidualDenseBlock, self).__init__() - self.conv1 = nn.Conv2d(num_feat, num_grow_ch, 3, 1, 1) - self.conv2 = nn.Conv2d(num_feat + num_grow_ch, num_grow_ch, 3, 1, 1) - self.conv3 = nn.Conv2d(num_feat + 2 * num_grow_ch, num_grow_ch, 3, 1, 1) - self.conv4 = nn.Conv2d(num_feat + 3 * num_grow_ch, num_grow_ch, 3, 1, 1) - self.conv5 = nn.Conv2d(num_feat + 4 * num_grow_ch, num_feat, 3, 1, 1) - - self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) - - # initialization - default_init_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1) - - def forward(self, x): - x1 = self.lrelu(self.conv1(x)) - x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1))) - x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1))) - x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1))) - x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1)) - # Emperically, we use 0.2 to scale the residual for better performance - return x5 * 0.2 + x - - -class RRDB(nn.Module): - """Residual in Residual Dense Block. - - Used in RRDB-Net in ESRGAN. - - Args: - num_feat (int): Channel number of intermediate features. - num_grow_ch (int): Channels for each growth. - """ - - def __init__(self, num_feat, num_grow_ch=32): - super(RRDB, self).__init__() - self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch) - self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch) - self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch) - - def forward(self, x): - out = self.rdb1(x) - out = self.rdb2(out) - out = self.rdb3(out) - # Emperically, we use 0.2 to scale the residual for better performance - return out * 0.2 + x - - -@ARCH_REGISTRY.register() -class RRDBNet(nn.Module): - """Networks consisting of Residual in Residual Dense Block, which is used - in ESRGAN. - - ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks. - - We extend ESRGAN for scale x2 and scale x1. - Note: This is one option for scale 1, scale 2 in RRDBNet. - We first employ the pixel-unshuffle (an inverse operation of pixelshuffle to reduce the spatial size - and enlarge the channel size before feeding inputs into the main ESRGAN architecture. - - Args: - num_in_ch (int): Channel number of inputs. - num_out_ch (int): Channel number of outputs. - num_feat (int): Channel number of intermediate features. - Default: 64 - num_block (int): Block number in the trunk network. Defaults: 23 - num_grow_ch (int): Channels for each growth. Default: 32. - """ - - def __init__(self, num_in_ch, num_out_ch, scale=4, num_feat=64, num_block=23, num_grow_ch=32): - super(RRDBNet, self).__init__() - self.scale = scale - if scale == 2: - num_in_ch = num_in_ch * 4 - elif scale == 1: - num_in_ch = num_in_ch * 16 - self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1) - self.body = make_layer(RRDB, num_block, num_feat=num_feat, num_grow_ch=num_grow_ch) - self.conv_body = nn.Conv2d(num_feat, num_feat, 3, 1, 1) - # upsample - self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) - self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) - self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1) - self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) - - self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) - - def forward(self, x): - if self.scale == 2: - feat = pixel_unshuffle(x, scale=2) - elif self.scale == 1: - feat = pixel_unshuffle(x, scale=4) - else: - feat = x - feat = self.conv_first(feat) - body_feat = self.conv_body(self.body(feat)) - feat = feat + body_feat - # upsample - feat = self.lrelu(self.conv_up1(F.interpolate(feat, scale_factor=2, mode='nearest'))) - feat = self.lrelu(self.conv_up2(F.interpolate(feat, scale_factor=2, mode='nearest'))) - out = self.conv_last(self.lrelu(self.conv_hr(feat))) - return out \ No newline at end of file diff --git a/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/ops/dcn/src/deform_conv_cuda.cpp b/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/ops/dcn/src/deform_conv_cuda.cpp deleted file mode 100644 index 5d9424908ed2dbd4ac3cdb98d13e09287a4d2f2d..0000000000000000000000000000000000000000 --- a/spaces/Jasonyoyo/CodeFormer/CodeFormer/basicsr/ops/dcn/src/deform_conv_cuda.cpp +++ /dev/null @@ -1,685 +0,0 @@ -// modify from -// https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/blob/mmdetection/mmdet/ops/dcn/src/deform_conv_cuda.c - -#include -#include - -#include -#include - -void deformable_im2col(const at::Tensor data_im, const at::Tensor data_offset, - const int channels, const int height, const int width, - const int ksize_h, const int ksize_w, const int pad_h, - const int pad_w, const int stride_h, const int stride_w, - const int dilation_h, const int dilation_w, - const int parallel_imgs, const int deformable_group, - at::Tensor data_col); - -void deformable_col2im(const at::Tensor data_col, const at::Tensor data_offset, - const int channels, const int height, const int width, - const int ksize_h, const int ksize_w, const int pad_h, - const int pad_w, const int stride_h, const int stride_w, - const int dilation_h, const int dilation_w, - const int parallel_imgs, const int deformable_group, - at::Tensor grad_im); - -void deformable_col2im_coord( - const at::Tensor data_col, const at::Tensor data_im, - const at::Tensor data_offset, const int channels, const int height, - const int width, const int ksize_h, const int ksize_w, const int pad_h, - const int pad_w, const int stride_h, const int stride_w, - const int dilation_h, const int dilation_w, const int parallel_imgs, - const int deformable_group, at::Tensor grad_offset); - -void modulated_deformable_im2col_cuda( - const at::Tensor data_im, const at::Tensor data_offset, - const at::Tensor data_mask, const int batch_size, const int channels, - const int height_im, const int width_im, const int height_col, - const int width_col, const int kernel_h, const int kenerl_w, - const int pad_h, const int pad_w, const int stride_h, const int stride_w, - const int dilation_h, const int dilation_w, const int deformable_group, - at::Tensor data_col); - -void modulated_deformable_col2im_cuda( - const at::Tensor data_col, const at::Tensor data_offset, - const at::Tensor data_mask, const int batch_size, const int channels, - const int height_im, const int width_im, const int height_col, - const int width_col, const int kernel_h, const int kenerl_w, - const int pad_h, const int pad_w, const int stride_h, const int stride_w, - const int dilation_h, const int dilation_w, const int deformable_group, - at::Tensor grad_im); - -void modulated_deformable_col2im_coord_cuda( - const at::Tensor data_col, const at::Tensor data_im, - const at::Tensor data_offset, const at::Tensor data_mask, - const int batch_size, const int channels, const int height_im, - const int width_im, const int height_col, const int width_col, - const int kernel_h, const int kenerl_w, const int pad_h, const int pad_w, - const int stride_h, const int stride_w, const int dilation_h, - const int dilation_w, const int deformable_group, at::Tensor grad_offset, - at::Tensor grad_mask); - -void shape_check(at::Tensor input, at::Tensor offset, at::Tensor *gradOutput, - at::Tensor weight, int kH, int kW, int dH, int dW, int padH, - int padW, int dilationH, int dilationW, int group, - int deformable_group) { - TORCH_CHECK(weight.ndimension() == 4, - "4D weight tensor (nOutputPlane,nInputPlane,kH,kW) expected, " - "but got: %s", - weight.ndimension()); - - TORCH_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); - - TORCH_CHECK(kW > 0 && kH > 0, - "kernel size should be greater than zero, but got kH: %d kW: %d", kH, - kW); - - TORCH_CHECK((weight.size(2) == kH && weight.size(3) == kW), - "kernel size should be consistent with weight, ", - "but got kH: %d kW: %d weight.size(2): %d, weight.size(3): %d", kH, - kW, weight.size(2), weight.size(3)); - - TORCH_CHECK(dW > 0 && dH > 0, - "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); - - TORCH_CHECK( - dilationW > 0 && dilationH > 0, - "dilation should be greater than 0, but got dilationH: %d dilationW: %d", - dilationH, dilationW); - - int ndim = input.ndimension(); - int dimf = 0; - int dimh = 1; - int dimw = 2; - - if (ndim == 4) { - dimf++; - dimh++; - dimw++; - } - - TORCH_CHECK(ndim == 3 || ndim == 4, "3D or 4D input tensor expected but got: %s", - ndim); - - long nInputPlane = weight.size(1) * group; - long inputHeight = input.size(dimh); - long inputWidth = input.size(dimw); - long nOutputPlane = weight.size(0); - long outputHeight = - (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; - long outputWidth = - (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; - - TORCH_CHECK(nInputPlane % deformable_group == 0, - "input channels must divide deformable group size"); - - if (outputWidth < 1 || outputHeight < 1) - AT_ERROR( - "Given input size: (%ld x %ld x %ld). " - "Calculated output size: (%ld x %ld x %ld). Output size is too small", - nInputPlane, inputHeight, inputWidth, nOutputPlane, outputHeight, - outputWidth); - - TORCH_CHECK(input.size(1) == nInputPlane, - "invalid number of input planes, expected: %d, but got: %d", - nInputPlane, input.size(1)); - - TORCH_CHECK((inputHeight >= kH && inputWidth >= kW), - "input image is smaller than kernel"); - - TORCH_CHECK((offset.size(2) == outputHeight && offset.size(3) == outputWidth), - "invalid spatial size of offset, expected height: %d width: %d, but " - "got height: %d width: %d", - outputHeight, outputWidth, offset.size(2), offset.size(3)); - - TORCH_CHECK((offset.size(1) == deformable_group * 2 * kH * kW), - "invalid number of channels of offset"); - - if (gradOutput != NULL) { - TORCH_CHECK(gradOutput->size(dimf) == nOutputPlane, - "invalid number of gradOutput planes, expected: %d, but got: %d", - nOutputPlane, gradOutput->size(dimf)); - - TORCH_CHECK((gradOutput->size(dimh) == outputHeight && - gradOutput->size(dimw) == outputWidth), - "invalid size of gradOutput, expected height: %d width: %d , but " - "got height: %d width: %d", - outputHeight, outputWidth, gradOutput->size(dimh), - gradOutput->size(dimw)); - } -} - -int deform_conv_forward_cuda(at::Tensor input, at::Tensor weight, - at::Tensor offset, at::Tensor output, - at::Tensor columns, at::Tensor ones, int kW, - int kH, int dW, int dH, int padW, int padH, - int dilationW, int dilationH, int group, - int deformable_group, int im2col_step) { - // todo: resize columns to include im2col: done - // todo: add im2col_step as input - // todo: add new output buffer and transpose it to output (or directly - // transpose output) todo: possibly change data indexing because of - // parallel_imgs - - shape_check(input, offset, NULL, weight, kH, kW, dH, dW, padH, padW, - dilationH, dilationW, group, deformable_group); - at::DeviceGuard guard(input.device()); - - input = input.contiguous(); - offset = offset.contiguous(); - weight = weight.contiguous(); - - int batch = 1; - if (input.ndimension() == 3) { - // Force batch - batch = 0; - input.unsqueeze_(0); - offset.unsqueeze_(0); - } - - // todo: assert batchsize dividable by im2col_step - - long batchSize = input.size(0); - long nInputPlane = input.size(1); - long inputHeight = input.size(2); - long inputWidth = input.size(3); - - long nOutputPlane = weight.size(0); - - long outputWidth = - (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; - long outputHeight = - (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; - - TORCH_CHECK((offset.size(0) == batchSize), "invalid batch size of offset"); - - output = output.view({batchSize / im2col_step, im2col_step, nOutputPlane, - outputHeight, outputWidth}); - columns = at::zeros( - {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth}, - input.options()); - - if (ones.ndimension() != 2 || - ones.size(0) * ones.size(1) < outputHeight * outputWidth) { - ones = at::ones({outputHeight, outputWidth}, input.options()); - } - - input = input.view({batchSize / im2col_step, im2col_step, nInputPlane, - inputHeight, inputWidth}); - offset = - offset.view({batchSize / im2col_step, im2col_step, - deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - - at::Tensor output_buffer = - at::zeros({batchSize / im2col_step, nOutputPlane, - im2col_step * outputHeight, outputWidth}, - output.options()); - - output_buffer = output_buffer.view( - {output_buffer.size(0), group, output_buffer.size(1) / group, - output_buffer.size(2), output_buffer.size(3)}); - - for (int elt = 0; elt < batchSize / im2col_step; elt++) { - deformable_im2col(input[elt], offset[elt], nInputPlane, inputHeight, - inputWidth, kH, kW, padH, padW, dH, dW, dilationH, - dilationW, im2col_step, deformable_group, columns); - - columns = columns.view({group, columns.size(0) / group, columns.size(1)}); - weight = weight.view({group, weight.size(0) / group, weight.size(1), - weight.size(2), weight.size(3)}); - - for (int g = 0; g < group; g++) { - output_buffer[elt][g] = output_buffer[elt][g] - .flatten(1) - .addmm_(weight[g].flatten(1), columns[g]) - .view_as(output_buffer[elt][g]); - } - } - - output_buffer = output_buffer.view( - {output_buffer.size(0), output_buffer.size(1) * output_buffer.size(2), - output_buffer.size(3), output_buffer.size(4)}); - - output_buffer = output_buffer.view({batchSize / im2col_step, nOutputPlane, - im2col_step, outputHeight, outputWidth}); - output_buffer.transpose_(1, 2); - output.copy_(output_buffer); - output = output.view({batchSize, nOutputPlane, outputHeight, outputWidth}); - - input = input.view({batchSize, nInputPlane, inputHeight, inputWidth}); - offset = offset.view( - {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - - if (batch == 0) { - output = output.view({nOutputPlane, outputHeight, outputWidth}); - input = input.view({nInputPlane, inputHeight, inputWidth}); - offset = offset.view({offset.size(1), offset.size(2), offset.size(3)}); - } - - return 1; -} - -int deform_conv_backward_input_cuda(at::Tensor input, at::Tensor offset, - at::Tensor gradOutput, at::Tensor gradInput, - at::Tensor gradOffset, at::Tensor weight, - at::Tensor columns, int kW, int kH, int dW, - int dH, int padW, int padH, int dilationW, - int dilationH, int group, - int deformable_group, int im2col_step) { - shape_check(input, offset, &gradOutput, weight, kH, kW, dH, dW, padH, padW, - dilationH, dilationW, group, deformable_group); - at::DeviceGuard guard(input.device()); - - input = input.contiguous(); - offset = offset.contiguous(); - gradOutput = gradOutput.contiguous(); - weight = weight.contiguous(); - - int batch = 1; - - if (input.ndimension() == 3) { - // Force batch - batch = 0; - input = input.view({1, input.size(0), input.size(1), input.size(2)}); - offset = offset.view({1, offset.size(0), offset.size(1), offset.size(2)}); - gradOutput = gradOutput.view( - {1, gradOutput.size(0), gradOutput.size(1), gradOutput.size(2)}); - } - - long batchSize = input.size(0); - long nInputPlane = input.size(1); - long inputHeight = input.size(2); - long inputWidth = input.size(3); - - long nOutputPlane = weight.size(0); - - long outputWidth = - (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; - long outputHeight = - (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; - - TORCH_CHECK((offset.size(0) == batchSize), 3, "invalid batch size of offset"); - gradInput = gradInput.view({batchSize, nInputPlane, inputHeight, inputWidth}); - columns = at::zeros( - {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth}, - input.options()); - - // change order of grad output - gradOutput = gradOutput.view({batchSize / im2col_step, im2col_step, - nOutputPlane, outputHeight, outputWidth}); - gradOutput.transpose_(1, 2); - - gradInput = gradInput.view({batchSize / im2col_step, im2col_step, nInputPlane, - inputHeight, inputWidth}); - input = input.view({batchSize / im2col_step, im2col_step, nInputPlane, - inputHeight, inputWidth}); - gradOffset = gradOffset.view({batchSize / im2col_step, im2col_step, - deformable_group * 2 * kH * kW, outputHeight, - outputWidth}); - offset = - offset.view({batchSize / im2col_step, im2col_step, - deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - - for (int elt = 0; elt < batchSize / im2col_step; elt++) { - // divide into groups - columns = columns.view({group, columns.size(0) / group, columns.size(1)}); - weight = weight.view({group, weight.size(0) / group, weight.size(1), - weight.size(2), weight.size(3)}); - gradOutput = gradOutput.view( - {gradOutput.size(0), group, gradOutput.size(1) / group, - gradOutput.size(2), gradOutput.size(3), gradOutput.size(4)}); - - for (int g = 0; g < group; g++) { - columns[g] = columns[g].addmm_(weight[g].flatten(1).transpose(0, 1), - gradOutput[elt][g].flatten(1), 0.0f, 1.0f); - } - - columns = - columns.view({columns.size(0) * columns.size(1), columns.size(2)}); - gradOutput = gradOutput.view( - {gradOutput.size(0), gradOutput.size(1) * gradOutput.size(2), - gradOutput.size(3), gradOutput.size(4), gradOutput.size(5)}); - - deformable_col2im_coord(columns, input[elt], offset[elt], nInputPlane, - inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, - dilationH, dilationW, im2col_step, deformable_group, - gradOffset[elt]); - - deformable_col2im(columns, offset[elt], nInputPlane, inputHeight, - inputWidth, kH, kW, padH, padW, dH, dW, dilationH, - dilationW, im2col_step, deformable_group, gradInput[elt]); - } - - gradOutput.transpose_(1, 2); - gradOutput = - gradOutput.view({batchSize, nOutputPlane, outputHeight, outputWidth}); - - gradInput = gradInput.view({batchSize, nInputPlane, inputHeight, inputWidth}); - input = input.view({batchSize, nInputPlane, inputHeight, inputWidth}); - gradOffset = gradOffset.view( - {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - offset = offset.view( - {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - - if (batch == 0) { - gradOutput = gradOutput.view({nOutputPlane, outputHeight, outputWidth}); - input = input.view({nInputPlane, inputHeight, inputWidth}); - gradInput = gradInput.view({nInputPlane, inputHeight, inputWidth}); - offset = offset.view({offset.size(1), offset.size(2), offset.size(3)}); - gradOffset = - gradOffset.view({offset.size(1), offset.size(2), offset.size(3)}); - } - - return 1; -} - -int deform_conv_backward_parameters_cuda( - at::Tensor input, at::Tensor offset, at::Tensor gradOutput, - at::Tensor gradWeight, // at::Tensor gradBias, - at::Tensor columns, at::Tensor ones, int kW, int kH, int dW, int dH, - int padW, int padH, int dilationW, int dilationH, int group, - int deformable_group, float scale, int im2col_step) { - // todo: transpose and reshape outGrad - // todo: reshape columns - // todo: add im2col_step as input - - shape_check(input, offset, &gradOutput, gradWeight, kH, kW, dH, dW, padH, - padW, dilationH, dilationW, group, deformable_group); - at::DeviceGuard guard(input.device()); - - input = input.contiguous(); - offset = offset.contiguous(); - gradOutput = gradOutput.contiguous(); - - int batch = 1; - - if (input.ndimension() == 3) { - // Force batch - batch = 0; - input = input.view( - at::IntList({1, input.size(0), input.size(1), input.size(2)})); - gradOutput = gradOutput.view( - {1, gradOutput.size(0), gradOutput.size(1), gradOutput.size(2)}); - } - - long batchSize = input.size(0); - long nInputPlane = input.size(1); - long inputHeight = input.size(2); - long inputWidth = input.size(3); - - long nOutputPlane = gradWeight.size(0); - - long outputWidth = - (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1; - long outputHeight = - (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1; - - TORCH_CHECK((offset.size(0) == batchSize), "invalid batch size of offset"); - - columns = at::zeros( - {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth}, - input.options()); - - gradOutput = gradOutput.view({batchSize / im2col_step, im2col_step, - nOutputPlane, outputHeight, outputWidth}); - gradOutput.transpose_(1, 2); - - at::Tensor gradOutputBuffer = at::zeros_like(gradOutput); - gradOutputBuffer = - gradOutputBuffer.view({batchSize / im2col_step, nOutputPlane, im2col_step, - outputHeight, outputWidth}); - gradOutputBuffer.copy_(gradOutput); - gradOutputBuffer = - gradOutputBuffer.view({batchSize / im2col_step, nOutputPlane, - im2col_step * outputHeight, outputWidth}); - - gradOutput.transpose_(1, 2); - gradOutput = - gradOutput.view({batchSize, nOutputPlane, outputHeight, outputWidth}); - - input = input.view({batchSize / im2col_step, im2col_step, nInputPlane, - inputHeight, inputWidth}); - offset = - offset.view({batchSize / im2col_step, im2col_step, - deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - - for (int elt = 0; elt < batchSize / im2col_step; elt++) { - deformable_im2col(input[elt], offset[elt], nInputPlane, inputHeight, - inputWidth, kH, kW, padH, padW, dH, dW, dilationH, - dilationW, im2col_step, deformable_group, columns); - - // divide into group - gradOutputBuffer = gradOutputBuffer.view( - {gradOutputBuffer.size(0), group, gradOutputBuffer.size(1) / group, - gradOutputBuffer.size(2), gradOutputBuffer.size(3)}); - columns = columns.view({group, columns.size(0) / group, columns.size(1)}); - gradWeight = - gradWeight.view({group, gradWeight.size(0) / group, gradWeight.size(1), - gradWeight.size(2), gradWeight.size(3)}); - - for (int g = 0; g < group; g++) { - gradWeight[g] = gradWeight[g] - .flatten(1) - .addmm_(gradOutputBuffer[elt][g].flatten(1), - columns[g].transpose(1, 0), 1.0, scale) - .view_as(gradWeight[g]); - } - gradOutputBuffer = gradOutputBuffer.view( - {gradOutputBuffer.size(0), - gradOutputBuffer.size(1) * gradOutputBuffer.size(2), - gradOutputBuffer.size(3), gradOutputBuffer.size(4)}); - columns = - columns.view({columns.size(0) * columns.size(1), columns.size(2)}); - gradWeight = gradWeight.view({gradWeight.size(0) * gradWeight.size(1), - gradWeight.size(2), gradWeight.size(3), - gradWeight.size(4)}); - } - - input = input.view({batchSize, nInputPlane, inputHeight, inputWidth}); - offset = offset.view( - {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth}); - - if (batch == 0) { - gradOutput = gradOutput.view({nOutputPlane, outputHeight, outputWidth}); - input = input.view({nInputPlane, inputHeight, inputWidth}); - } - - return 1; -} - -void modulated_deform_conv_cuda_forward( - at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor ones, - at::Tensor offset, at::Tensor mask, at::Tensor output, at::Tensor columns, - int kernel_h, int kernel_w, const int stride_h, const int stride_w, - const int pad_h, const int pad_w, const int dilation_h, - const int dilation_w, const int group, const int deformable_group, - const bool with_bias) { - TORCH_CHECK(input.is_contiguous(), "input tensor has to be contiguous"); - TORCH_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); - at::DeviceGuard guard(input.device()); - - const int batch = input.size(0); - const int channels = input.size(1); - const int height = input.size(2); - const int width = input.size(3); - - const int channels_out = weight.size(0); - const int channels_kernel = weight.size(1); - const int kernel_h_ = weight.size(2); - const int kernel_w_ = weight.size(3); - - if (kernel_h_ != kernel_h || kernel_w_ != kernel_w) - AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).", - kernel_h_, kernel_w, kernel_h_, kernel_w_); - if (channels != channels_kernel * group) - AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).", - channels, channels_kernel * group); - - const int height_out = - (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; - const int width_out = - (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; - - if (ones.ndimension() != 2 || - ones.size(0) * ones.size(1) < height_out * width_out) { - // Resize plane and fill with ones... - ones = at::ones({height_out, width_out}, input.options()); - } - - // resize output - output = output.view({batch, channels_out, height_out, width_out}).zero_(); - // resize temporary columns - columns = - at::zeros({channels * kernel_h * kernel_w, 1 * height_out * width_out}, - input.options()); - - output = output.view({output.size(0), group, output.size(1) / group, - output.size(2), output.size(3)}); - - for (int b = 0; b < batch; b++) { - modulated_deformable_im2col_cuda( - input[b], offset[b], mask[b], 1, channels, height, width, height_out, - width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, - dilation_h, dilation_w, deformable_group, columns); - - // divide into group - weight = weight.view({group, weight.size(0) / group, weight.size(1), - weight.size(2), weight.size(3)}); - columns = columns.view({group, columns.size(0) / group, columns.size(1)}); - - for (int g = 0; g < group; g++) { - output[b][g] = output[b][g] - .flatten(1) - .addmm_(weight[g].flatten(1), columns[g]) - .view_as(output[b][g]); - } - - weight = weight.view({weight.size(0) * weight.size(1), weight.size(2), - weight.size(3), weight.size(4)}); - columns = - columns.view({columns.size(0) * columns.size(1), columns.size(2)}); - } - - output = output.view({output.size(0), output.size(1) * output.size(2), - output.size(3), output.size(4)}); - - if (with_bias) { - output += bias.view({1, bias.size(0), 1, 1}); - } -} - -void modulated_deform_conv_cuda_backward( - at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor ones, - at::Tensor offset, at::Tensor mask, at::Tensor columns, - at::Tensor grad_input, at::Tensor grad_weight, at::Tensor grad_bias, - at::Tensor grad_offset, at::Tensor grad_mask, at::Tensor grad_output, - int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, - int pad_w, int dilation_h, int dilation_w, int group, int deformable_group, - const bool with_bias) { - TORCH_CHECK(input.is_contiguous(), "input tensor has to be contiguous"); - TORCH_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); - at::DeviceGuard guard(input.device()); - - const int batch = input.size(0); - const int channels = input.size(1); - const int height = input.size(2); - const int width = input.size(3); - - const int channels_kernel = weight.size(1); - const int kernel_h_ = weight.size(2); - const int kernel_w_ = weight.size(3); - if (kernel_h_ != kernel_h || kernel_w_ != kernel_w) - AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).", - kernel_h_, kernel_w, kernel_h_, kernel_w_); - if (channels != channels_kernel * group) - AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).", - channels, channels_kernel * group); - - const int height_out = - (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; - const int width_out = - (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; - - if (ones.ndimension() != 2 || - ones.size(0) * ones.size(1) < height_out * width_out) { - // Resize plane and fill with ones... - ones = at::ones({height_out, width_out}, input.options()); - } - - grad_input = grad_input.view({batch, channels, height, width}); - columns = at::zeros({channels * kernel_h * kernel_w, height_out * width_out}, - input.options()); - - grad_output = - grad_output.view({grad_output.size(0), group, grad_output.size(1) / group, - grad_output.size(2), grad_output.size(3)}); - - for (int b = 0; b < batch; b++) { - // divide int group - columns = columns.view({group, columns.size(0) / group, columns.size(1)}); - weight = weight.view({group, weight.size(0) / group, weight.size(1), - weight.size(2), weight.size(3)}); - - for (int g = 0; g < group; g++) { - columns[g].addmm_(weight[g].flatten(1).transpose(0, 1), - grad_output[b][g].flatten(1), 0.0f, 1.0f); - } - - columns = - columns.view({columns.size(0) * columns.size(1), columns.size(2)}); - weight = weight.view({weight.size(0) * weight.size(1), weight.size(2), - weight.size(3), weight.size(4)}); - - // gradient w.r.t. input coordinate data - modulated_deformable_col2im_coord_cuda( - columns, input[b], offset[b], mask[b], 1, channels, height, width, - height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, - stride_w, dilation_h, dilation_w, deformable_group, grad_offset[b], - grad_mask[b]); - // gradient w.r.t. input data - modulated_deformable_col2im_cuda( - columns, offset[b], mask[b], 1, channels, height, width, height_out, - width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, - dilation_h, dilation_w, deformable_group, grad_input[b]); - - // gradient w.r.t. weight, dWeight should accumulate across the batch and - // group - modulated_deformable_im2col_cuda( - input[b], offset[b], mask[b], 1, channels, height, width, height_out, - width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, - dilation_h, dilation_w, deformable_group, columns); - - columns = columns.view({group, columns.size(0) / group, columns.size(1)}); - grad_weight = grad_weight.view({group, grad_weight.size(0) / group, - grad_weight.size(1), grad_weight.size(2), - grad_weight.size(3)}); - if (with_bias) - grad_bias = grad_bias.view({group, grad_bias.size(0) / group}); - - for (int g = 0; g < group; g++) { - grad_weight[g] = - grad_weight[g] - .flatten(1) - .addmm_(grad_output[b][g].flatten(1), columns[g].transpose(0, 1)) - .view_as(grad_weight[g]); - if (with_bias) { - grad_bias[g] = - grad_bias[g] - .view({-1, 1}) - .addmm_(grad_output[b][g].flatten(1), ones.view({-1, 1})) - .view(-1); - } - } - - columns = - columns.view({columns.size(0) * columns.size(1), columns.size(2)}); - grad_weight = grad_weight.view({grad_weight.size(0) * grad_weight.size(1), - grad_weight.size(2), grad_weight.size(3), - grad_weight.size(4)}); - if (with_bias) - grad_bias = grad_bias.view({grad_bias.size(0) * grad_bias.size(1)}); - } - grad_output = grad_output.view({grad_output.size(0) * grad_output.size(1), - grad_output.size(2), grad_output.size(3), - grad_output.size(4)}); -} diff --git a/spaces/JayceeAngel/openai-reverse-proxy/server.js b/spaces/JayceeAngel/openai-reverse-proxy/server.js deleted file mode 100644 index 93795e28b48bb70533f62a0b21e46129994e1c4b..0000000000000000000000000000000000000000 --- a/spaces/JayceeAngel/openai-reverse-proxy/server.js +++ /dev/null @@ -1,29 +0,0 @@ -const express = require('express'); -const proxy = require('express-http-proxy'); -const app = express(); -const targetUrl = 'https://api.openai.com'; -const openaiKey = process.env.OPENAI_KEY -const port = 7860; - -app.use('/', proxy(targetUrl, { - proxyReqOptDecorator: (proxyReqOpts, srcReq) => { - // Modify the request headers if necessary - proxyReqOpts.headers['Authorization'] = 'Bearer '+openaiKey; - return proxyReqOpts; - }, -})); - -const baseUrl = getExternalUrl(process.env.SPACE_ID); - -function getExternalUrl(spaceId) { - try { - const [username, spacename] = spaceId.split("/"); - return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/v1`; - } catch (e) { - return ""; - } -} - -app.listen(port, () => { - console.log(`Reverse proxy server running on ${baseUrl}`); -}); \ No newline at end of file diff --git a/spaces/Jeff2323/ai-comic-factory/src/components/ui/badge.tsx b/spaces/Jeff2323/ai-comic-factory/src/components/ui/badge.tsx deleted file mode 100644 index 8a05c5e844f6551efb3b35a0a23c748a9a6639b4..0000000000000000000000000000000000000000 --- a/spaces/Jeff2323/ai-comic-factory/src/components/ui/badge.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" - -import { cn } from "@/lib/utils" - -const badgeVariants = cva( - "inline-flex items-center rounded-full border border-stone-200 px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-stone-400 focus:ring-offset-2 dark:border-stone-800 dark:focus:ring-stone-800", - { - variants: { - variant: { - default: - "border-transparent bg-stone-900 text-stone-50 hover:bg-stone-900/80 dark:bg-stone-50 dark:text-stone-900 dark:hover:bg-stone-50/80", - secondary: - "border-transparent bg-stone-100 text-stone-900 hover:bg-stone-100/80 dark:bg-stone-800 dark:text-stone-50 dark:hover:bg-stone-800/80", - destructive: - "border-transparent bg-red-500 text-stone-50 hover:bg-red-500/80 dark:bg-red-900 dark:text-red-50 dark:hover:bg-red-900/80", - outline: "text-stone-950 dark:text-stone-50", - }, - }, - defaultVariants: { - variant: "default", - }, - } -) - -export interface BadgeProps - extends React.HTMLAttributes, - VariantProps {} - -function Badge({ className, variant, ...props }: BadgeProps) { - return ( -
- ) -} - -export { Badge, badgeVariants } diff --git a/spaces/JeffJing/ZookChatBot/steamship/data/operations/__init__.py b/spaces/JeffJing/ZookChatBot/steamship/data/operations/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/JoeyFoursheds/ClonerHug/infer_pack/attentions.py b/spaces/JoeyFoursheds/ClonerHug/infer_pack/attentions.py deleted file mode 100644 index 77cb63ffccf3e33badf22d50862a64ba517b487f..0000000000000000000000000000000000000000 --- a/spaces/JoeyFoursheds/ClonerHug/infer_pack/attentions.py +++ /dev/null @@ -1,417 +0,0 @@ -import copy -import math -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - -from infer_pack import commons -from infer_pack import modules -from infer_pack.modules import LayerNorm - - -class Encoder(nn.Module): - def __init__( - self, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size=1, - p_dropout=0.0, - window_size=10, - **kwargs - ): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append( - MultiHeadAttention( - hidden_channels, - hidden_channels, - n_heads, - p_dropout=p_dropout, - window_size=window_size, - ) - ) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append( - FFN( - hidden_channels, - hidden_channels, - filter_channels, - kernel_size, - p_dropout=p_dropout, - ) - ) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__( - self, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size=1, - p_dropout=0.0, - proximal_bias=False, - proximal_init=True, - **kwargs - ): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append( - MultiHeadAttention( - hidden_channels, - hidden_channels, - n_heads, - p_dropout=p_dropout, - proximal_bias=proximal_bias, - proximal_init=proximal_init, - ) - ) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append( - MultiHeadAttention( - hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout - ) - ) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append( - FFN( - hidden_channels, - hidden_channels, - filter_channels, - kernel_size, - p_dropout=p_dropout, - causal=True, - ) - ) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( - device=x.device, dtype=x.dtype - ) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__( - self, - channels, - out_channels, - n_heads, - p_dropout=0.0, - window_size=None, - heads_share=True, - block_length=None, - proximal_bias=False, - proximal_init=False, - ): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels**-0.5 - self.emb_rel_k = nn.Parameter( - torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) - * rel_stddev - ) - self.emb_rel_v = nn.Parameter( - torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) - * rel_stddev - ) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1)) - if self.window_size is not None: - assert ( - t_s == t_t - ), "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys( - query / math.sqrt(self.k_channels), key_relative_embeddings - ) - scores_local = self._relative_position_to_absolute_position(rel_logits) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to( - device=scores.device, dtype=scores.dtype - ) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - assert ( - t_s == t_t - ), "Local attention is only available for self-attention." - block_mask = ( - torch.ones_like(scores) - .triu(-self.block_length) - .tril(self.block_length) - ) - scores = scores.masked_fill(block_mask == 0, -1e4) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings( - self.emb_rel_v, t_s - ) - output = output + self._matmul_with_relative_values( - relative_weights, value_relative_embeddings - ) - output = ( - output.transpose(2, 3).contiguous().view(b, d, t_t) - ) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]), - ) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[ - :, slice_start_position:slice_end_position - ] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad( - x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]) - ) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[ - :, :, :length, length - 1 : - ] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad( - x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]) - ) - x_flat = x.view([batch, heads, length**2 + length * (length - 1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__( - self, - in_channels, - out_channels, - filter_channels, - kernel_size, - p_dropout=0.0, - activation=None, - causal=False, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - self.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(x * x_mask)) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/Jorgerv97/Herramienta_interactiva_ensenyanza_tecnicas_aprendizaje_supervisado_salud/app.py b/spaces/Jorgerv97/Herramienta_interactiva_ensenyanza_tecnicas_aprendizaje_supervisado_salud/app.py deleted file mode 100644 index 04db39c25b441636ced84a63857a29f53a90ee6b..0000000000000000000000000000000000000000 --- a/spaces/Jorgerv97/Herramienta_interactiva_ensenyanza_tecnicas_aprendizaje_supervisado_salud/app.py +++ /dev/null @@ -1,112 +0,0 @@ -from shiny import App, Inputs, Outputs, Session, reactive, render, ui -import shinyswatch - -from pathlib import Path - -# Importar la interfaz y los servidores de los componentes -from learningTool import learningTool_ui, learningTool_server -from customTool import customTool_ui, customTool_server -from ExtraInfo.extraInfo import extra_info_Python_programming_ui, extra_info_project_info_ui - - -############################## COMPROBACIONES DE PATH Y CARPETAS ############################# - -# Creación / comprobación de las carpetas para guardar las imágenes de plots de árboles: -Path(Path(__file__).parent / 'DecTrees').mkdir(exist_ok=True) -Path(Path(__file__).parent / 'RanForests').mkdir(exist_ok=True) - - - -############################################################################################## -########################################## UI ################################################ -############################################################################################## - -app_ui = ui.page_fluid( - # Available themes: - # cerulean, cosmo, cyborg, darkly, flatly, journal, litera, lumen, lux, - # materia, minty, morph, pulse, quartz, sandstone, simplex, sketchy, slate, - # solar, spacelab, superhero, united, vapor, yeti, zephyr - # Good ones: cerulean, litera, materia, pulse, slate, spacelab, superhero, zephyr - # Funny: sketchy, vapor - shinyswatch.theme.cerulean(), - - # Estilo especial sobreescito al estilo del tema utilizado para hacer los botones más intuitivos - # y mejorar el feedback recibido por la interacción con ellos - ui.tags.style( - """ - button { - border: 1px solid DimGray !important; - box-shadow: 0 4px DarkGray !important; - transition: 0.1s !important; - } - button:hover { - border: 1px solid DimGray !important; - transform: translateY(-2px) !important; - box-shadow: 0px 6px Silver !important; - } - button:active { - border: 1px solid DimGray !important; - box-shadow: 0 2px DimGray !important; - transform: translateY(2px) !important; - } - """ - ), - - ui.page_navbar( - ui.nav_spacer(), -#################################### HERRAMIENTA INTERACTIVA ################################# - ui.nav( - "Herramienta Interactiva", - learningTool_ui("learning_tool"), - ), -#################################### USA DATOS PROPIOS ####################################### - ui.nav( - "¡Usa tus datos!", - customTool_ui("custom_tool"), - ), -#################################### EXTRA ################################################### - ui.nav( - "Extra", - ui.panel_main( - extra_info_Python_programming_ui("extra_info"), - ui.tags.hr(), - width=12 - ), - ui.panel_main( - extra_info_project_info_ui("extra_info"), - width=12 - ), - ), - - title="Herramienta Interactiva", #para la enseñanza de técnicas de aprendizaje supervisado en salud", - window_title="Herramienta Interactiva para enseñanza de ML by Jorge Ruiz", - lang="es", - bg="#006ee6", - #collapsible=True, - position="static-top", - ) -) - - - - -############################################################################################## -######################################## SERVER ############################################## -############################################################################################## - -def server(input: Inputs, output: Outputs, session: Session): - -############### SERVIDORES INDIVIDUALES DE LOS COMPONENTES INTEGRADOS ######################## - - learningTool_server("learning_tool") - customTool_server("custom_tool"), - - - - - -############################################################################################## -##################################### SHINY APP ############################################## -############################################################################################## - -app = App(app_ui, server) \ No newline at end of file diff --git a/spaces/JosephusCheung/LL7M-JS-Tokenizer/index.html b/spaces/JosephusCheung/LL7M-JS-Tokenizer/index.html deleted file mode 100644 index c4c32b4a9daeafd9dcbc3fba0a9b3596eafab913..0000000000000000000000000000000000000000 --- a/spaces/JosephusCheung/LL7M-JS-Tokenizer/index.html +++ /dev/null @@ -1 +0,0 @@ -ll7m-tokenizer-js playground
\ No newline at end of file diff --git a/spaces/KaguraNana/XiaokunChatGPT/README.md b/spaces/KaguraNana/XiaokunChatGPT/README.md deleted file mode 100644 index d1ae83f73ac14888dedce02615afaaaea7f3d7d5..0000000000000000000000000000000000000000 --- a/spaces/KaguraNana/XiaokunChatGPT/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: ChuanhuChatGPT -emoji: 🐠 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.19.1 -app_file: app.py -pinned: false -license: mit -duplicated_from: JohnSmith9982/ChuanhuChatGPT ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Kangarroar/ApplioRVC-Inference/lib/uvr5_pack/lib_v5/nets_537227KB.py b/spaces/Kangarroar/ApplioRVC-Inference/lib/uvr5_pack/lib_v5/nets_537227KB.py deleted file mode 100644 index a1bb530e006482704f234c2e739a695174142941..0000000000000000000000000000000000000000 --- a/spaces/Kangarroar/ApplioRVC-Inference/lib/uvr5_pack/lib_v5/nets_537227KB.py +++ /dev/null @@ -1,123 +0,0 @@ -import torch -import numpy as np -from torch import nn -import torch.nn.functional as F - -from . import layers_537238KB as layers - - -class BaseASPPNet(nn.Module): - def __init__(self, nin, ch, dilations=(4, 8, 16)): - super(BaseASPPNet, self).__init__() - self.enc1 = layers.Encoder(nin, ch, 3, 2, 1) - self.enc2 = layers.Encoder(ch, ch * 2, 3, 2, 1) - self.enc3 = layers.Encoder(ch * 2, ch * 4, 3, 2, 1) - self.enc4 = layers.Encoder(ch * 4, ch * 8, 3, 2, 1) - - self.aspp = layers.ASPPModule(ch * 8, ch * 16, dilations) - - self.dec4 = layers.Decoder(ch * (8 + 16), ch * 8, 3, 1, 1) - self.dec3 = layers.Decoder(ch * (4 + 8), ch * 4, 3, 1, 1) - self.dec2 = layers.Decoder(ch * (2 + 4), ch * 2, 3, 1, 1) - self.dec1 = layers.Decoder(ch * (1 + 2), ch, 3, 1, 1) - - def __call__(self, x): - h, e1 = self.enc1(x) - h, e2 = self.enc2(h) - h, e3 = self.enc3(h) - h, e4 = self.enc4(h) - - h = self.aspp(h) - - h = self.dec4(h, e4) - h = self.dec3(h, e3) - h = self.dec2(h, e2) - h = self.dec1(h, e1) - - return h - - -class CascadedASPPNet(nn.Module): - def __init__(self, n_fft): - super(CascadedASPPNet, self).__init__() - self.stg1_low_band_net = BaseASPPNet(2, 64) - self.stg1_high_band_net = BaseASPPNet(2, 64) - - self.stg2_bridge = layers.Conv2DBNActiv(66, 32, 1, 1, 0) - self.stg2_full_band_net = BaseASPPNet(32, 64) - - self.stg3_bridge = layers.Conv2DBNActiv(130, 64, 1, 1, 0) - self.stg3_full_band_net = BaseASPPNet(64, 128) - - self.out = nn.Conv2d(128, 2, 1, bias=False) - self.aux1_out = nn.Conv2d(64, 2, 1, bias=False) - self.aux2_out = nn.Conv2d(64, 2, 1, bias=False) - - self.max_bin = n_fft // 2 - self.output_bin = n_fft // 2 + 1 - - self.offset = 128 - - def forward(self, x, aggressiveness=None): - mix = x.detach() - x = x.clone() - - x = x[:, :, : self.max_bin] - - bandw = x.size()[2] // 2 - aux1 = torch.cat( - [ - self.stg1_low_band_net(x[:, :, :bandw]), - self.stg1_high_band_net(x[:, :, bandw:]), - ], - dim=2, - ) - - h = torch.cat([x, aux1], dim=1) - aux2 = self.stg2_full_band_net(self.stg2_bridge(h)) - - h = torch.cat([x, aux1, aux2], dim=1) - h = self.stg3_full_band_net(self.stg3_bridge(h)) - - mask = torch.sigmoid(self.out(h)) - mask = F.pad( - input=mask, - pad=(0, 0, 0, self.output_bin - mask.size()[2]), - mode="replicate", - ) - - if self.training: - aux1 = torch.sigmoid(self.aux1_out(aux1)) - aux1 = F.pad( - input=aux1, - pad=(0, 0, 0, self.output_bin - aux1.size()[2]), - mode="replicate", - ) - aux2 = torch.sigmoid(self.aux2_out(aux2)) - aux2 = F.pad( - input=aux2, - pad=(0, 0, 0, self.output_bin - aux2.size()[2]), - mode="replicate", - ) - return mask * mix, aux1 * mix, aux2 * mix - else: - if aggressiveness: - mask[:, :, : aggressiveness["split_bin"]] = torch.pow( - mask[:, :, : aggressiveness["split_bin"]], - 1 + aggressiveness["value"] / 3, - ) - mask[:, :, aggressiveness["split_bin"] :] = torch.pow( - mask[:, :, aggressiveness["split_bin"] :], - 1 + aggressiveness["value"], - ) - - return mask * mix - - def predict(self, x_mag, aggressiveness=None): - h = self.forward(x_mag, aggressiveness) - - if self.offset > 0: - h = h[:, :, :, self.offset : -self.offset] - assert h.size()[3] > 0 - - return h diff --git a/spaces/KenjieDec/RemBG/rembg/sessions/sam.py b/spaces/KenjieDec/RemBG/rembg/sessions/sam.py deleted file mode 100644 index 9d1ed7de95264ba7e15ba8a606fa6960e66541db..0000000000000000000000000000000000000000 --- a/spaces/KenjieDec/RemBG/rembg/sessions/sam.py +++ /dev/null @@ -1,169 +0,0 @@ -import os -from typing import List - -import numpy as np -import onnxruntime as ort -import pooch -from PIL import Image -from PIL.Image import Image as PILImage - -from .base import BaseSession - - -def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int): - scale = long_side_length * 1.0 / max(oldh, oldw) - newh, neww = oldh * scale, oldw * scale - neww = int(neww + 0.5) - newh = int(newh + 0.5) - return (newh, neww) - - -def apply_coords(coords: np.ndarray, original_size, target_length) -> np.ndarray: - old_h, old_w = original_size - new_h, new_w = get_preprocess_shape( - original_size[0], original_size[1], target_length - ) - coords = coords.copy().astype(float) - coords[..., 0] = coords[..., 0] * (new_w / old_w) - coords[..., 1] = coords[..., 1] * (new_h / old_h) - return coords - - -def resize_longes_side(img: PILImage, size=1024): - w, h = img.size - if h > w: - new_h, new_w = size, int(w * size / h) - else: - new_h, new_w = int(h * size / w), size - - return img.resize((new_w, new_h)) - - -def pad_to_square(img: np.ndarray, size=1024): - h, w = img.shape[:2] - padh = size - h - padw = size - w - img = np.pad(img, ((0, padh), (0, padw), (0, 0)), mode="constant") - img = img.astype(np.float32) - return img - - -class SamSession(BaseSession): - def __init__(self, model_name: str, sess_opts: ort.SessionOptions, *args, **kwargs): - self.model_name = model_name - paths = self.__class__.download_models() - self.encoder = ort.InferenceSession( - str(paths[0]), - providers=ort.get_available_providers(), - sess_options=sess_opts, - ) - self.decoder = ort.InferenceSession( - str(paths[1]), - providers=ort.get_available_providers(), - sess_options=sess_opts, - ) - - def normalize( - self, - img: np.ndarray, - mean=(123.675, 116.28, 103.53), - std=(58.395, 57.12, 57.375), - size=(1024, 1024), - *args, - **kwargs, - ): - pixel_mean = np.array([*mean]).reshape(1, 1, -1) - pixel_std = np.array([*std]).reshape(1, 1, -1) - x = (img - pixel_mean) / pixel_std - return x - - def predict( - self, - img: PILImage, - *args, - **kwargs, - ) -> List[PILImage]: - # Preprocess image - image = resize_longes_side(img) - image = np.array(image) - image = self.normalize(image) - image = pad_to_square(image) - - input_labels = kwargs.get("input_labels") - input_points = kwargs.get("input_points") - - if input_labels is None: - raise ValueError("input_labels is required") - if input_points is None: - raise ValueError("input_points is required") - - # Transpose - image = image.transpose(2, 0, 1)[None, :, :, :] - # Run encoder (Image embedding) - encoded = self.encoder.run(None, {"x": image}) - image_embedding = encoded[0] - - # Add a batch index, concatenate a padding point, and transform. - onnx_coord = np.concatenate([input_points, np.array([[0.0, 0.0]])], axis=0)[ - None, :, : - ] - onnx_label = np.concatenate([input_labels, np.array([-1])], axis=0)[ - None, : - ].astype(np.float32) - onnx_coord = apply_coords(onnx_coord, img.size[::1], 1024).astype(np.float32) - - # Create an empty mask input and an indicator for no mask. - onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32) - onnx_has_mask_input = np.zeros(1, dtype=np.float32) - - decoder_inputs = { - "image_embeddings": image_embedding, - "point_coords": onnx_coord, - "point_labels": onnx_label, - "mask_input": onnx_mask_input, - "has_mask_input": onnx_has_mask_input, - "orig_im_size": np.array(img.size[::-1], dtype=np.float32), - } - - masks, _, low_res_logits = self.decoder.run(None, decoder_inputs) - masks = masks > 0.0 - masks = [ - Image.fromarray((masks[i, 0] * 255).astype(np.uint8)) - for i in range(masks.shape[0]) - ] - - return masks - - @classmethod - def download_models(cls, *args, **kwargs): - fname_encoder = f"{cls.name()}_encoder.onnx" - fname_decoder = f"{cls.name()}_decoder.onnx" - - pooch.retrieve( - "https://github.com/danielgatis/rembg/releases/download/v0.0.0/vit_b-encoder-quant.onnx", - None - if cls.checksum_disabled(*args, **kwargs) - else "md5:13d97c5c79ab13ef86d67cbde5f1b250", - fname=fname_encoder, - path=cls.u2net_home(*args, **kwargs), - progressbar=True, - ) - - pooch.retrieve( - "https://github.com/danielgatis/rembg/releases/download/v0.0.0/vit_b-decoder-quant.onnx", - None - if cls.checksum_disabled(*args, **kwargs) - else "md5:fa3d1c36a3187d3de1c8deebf33dd127", - fname=fname_decoder, - path=cls.u2net_home(*args, **kwargs), - progressbar=True, - ) - - return ( - os.path.join(cls.u2net_home(), fname_encoder), - os.path.join(cls.u2net_home(), fname_decoder), - ) - - @classmethod - def name(cls, *args, **kwargs): - return "sam" diff --git a/spaces/KyanChen/RSPrompter/mmdet/models/task_modules/samplers/mask_sampling_result.py b/spaces/KyanChen/RSPrompter/mmdet/models/task_modules/samplers/mask_sampling_result.py deleted file mode 100644 index adaa62e8a0af28bb004a34b961f672ec03988d2c..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/models/task_modules/samplers/mask_sampling_result.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -"""copy from -https://github.com/ZwwWayne/K-Net/blob/main/knet/det/mask_pseudo_sampler.py.""" - -import torch -from torch import Tensor - -from ..assigners import AssignResult -from .sampling_result import SamplingResult - - -class MaskSamplingResult(SamplingResult): - """Mask sampling result.""" - - def __init__(self, - pos_inds: Tensor, - neg_inds: Tensor, - masks: Tensor, - gt_masks: Tensor, - assign_result: AssignResult, - gt_flags: Tensor, - avg_factor_with_neg: bool = True) -> None: - self.pos_inds = pos_inds - self.neg_inds = neg_inds - self.num_pos = max(pos_inds.numel(), 1) - self.num_neg = max(neg_inds.numel(), 1) - self.avg_factor = self.num_pos + self.num_neg \ - if avg_factor_with_neg else self.num_pos - - self.pos_masks = masks[pos_inds] - self.neg_masks = masks[neg_inds] - self.pos_is_gt = gt_flags[pos_inds] - - self.num_gts = gt_masks.shape[0] - self.pos_assigned_gt_inds = assign_result.gt_inds[pos_inds] - 1 - - if gt_masks.numel() == 0: - # hack for index error case - assert self.pos_assigned_gt_inds.numel() == 0 - self.pos_gt_masks = torch.empty_like(gt_masks) - else: - self.pos_gt_masks = gt_masks[self.pos_assigned_gt_inds, :] - - @property - def masks(self) -> Tensor: - """torch.Tensor: concatenated positive and negative masks.""" - return torch.cat([self.pos_masks, self.neg_masks]) - - def __nice__(self) -> str: - data = self.info.copy() - data['pos_masks'] = data.pop('pos_masks').shape - data['neg_masks'] = data.pop('neg_masks').shape - parts = [f"'{k}': {v!r}" for k, v in sorted(data.items())] - body = ' ' + ',\n '.join(parts) - return '{\n' + body + '\n}' - - @property - def info(self) -> dict: - """Returns a dictionary of info about the object.""" - return { - 'pos_inds': self.pos_inds, - 'neg_inds': self.neg_inds, - 'pos_masks': self.pos_masks, - 'neg_masks': self.neg_masks, - 'pos_is_gt': self.pos_is_gt, - 'num_gts': self.num_gts, - 'pos_assigned_gt_inds': self.pos_assigned_gt_inds, - } diff --git a/spaces/LabAlproITS/CyberDAS-FE/templates/index.html b/spaces/LabAlproITS/CyberDAS-FE/templates/index.html deleted file mode 100644 index 5aa46f37ec4ff9ea98727e69b751acf9988997ea..0000000000000000000000000000000000000000 --- a/spaces/LabAlproITS/CyberDAS-FE/templates/index.html +++ /dev/null @@ -1,157 +0,0 @@ - - - - - - - - - Insurance Cost Prediction Application - - - -
- - - -
- -
-
-
-

Predict Your Insurance Cost:

- -
- - - - - - - - - - - - - - - - - - - -
-
-
-
-

Your estimate insurance cost:

-

$0.00 USD

-
-

-

-

-

-

-

-
-
-
- logo-dts -
-
-
-
- -
- -
- -
- -
- - - - - - - - diff --git a/spaces/LanguageBind/LanguageBind/open_clip/generation_utils.py b/spaces/LanguageBind/LanguageBind/open_clip/generation_utils.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/train/losses.py b/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/train/losses.py deleted file mode 100644 index b1b263e4c205e78ffe970f622ab6ff68f36d3b17..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/train/losses.py +++ /dev/null @@ -1,58 +0,0 @@ -import torch - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - rl = rl.float().detach() - gl = gl.float() - loss += torch.mean(torch.abs(rl - gl)) - - return loss * 2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - loss = 0 - r_losses = [] - g_losses = [] - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - dr = dr.float() - dg = dg.float() - r_loss = torch.mean((1 - dr) ** 2) - g_loss = torch.mean(dg**2) - loss += r_loss + g_loss - r_losses.append(r_loss.item()) - g_losses.append(g_loss.item()) - - return loss, r_losses, g_losses - - -def generator_loss(disc_outputs): - loss = 0 - gen_losses = [] - for dg in disc_outputs: - dg = dg.float() - l = torch.mean((1 - dg) ** 2) - gen_losses.append(l) - loss += l - - return loss, gen_losses - - -def kl_loss(z_p, logs_q, m_p, logs_p, z_mask): - """ - z_p, logs_q: [b, h, t_t] - m_p, logs_p: [b, h, t_t] - """ - z_p = z_p.float() - logs_q = logs_q.float() - m_p = m_p.float() - logs_p = logs_p.float() - z_mask = z_mask.float() - - kl = logs_p - logs_q - 0.5 - kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p) - kl = torch.sum(kl * z_mask) - l = kl / torch.sum(z_mask) - return l diff --git a/spaces/LightSY/W2L-TD/README.md b/spaces/LightSY/W2L-TD/README.md deleted file mode 100644 index f710dbad9bee00464025fc46cc9f512e39c0ac29..0000000000000000000000000000000000000000 --- a/spaces/LightSY/W2L-TD/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: W2L TD -emoji: 📊 -colorFrom: blue -colorTo: pink -sdk: gradio -sdk_version: 3.24.1 -app_file: app_hug.py -pinned: false -license: other ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/LightSY/W2L-TD/facelib/utils/misc.py b/spaces/LightSY/W2L-TD/facelib/utils/misc.py deleted file mode 100644 index 29d37c83216cd0eb4549b0911de05161a4babe90..0000000000000000000000000000000000000000 --- a/spaces/LightSY/W2L-TD/facelib/utils/misc.py +++ /dev/null @@ -1,203 +0,0 @@ -import cv2 -import os -import os.path as osp -import numpy as np -from PIL import Image -# import torch -# from torch.hub import download_url_to_file, get_dir -from urllib.parse import urlparse -# from basicsr.utils.download_util import download_file_from_google_drive - -ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - - -def download_pretrained_models(file_ids, save_path_root): - import gdown - - os.makedirs(save_path_root, exist_ok=True) - - for file_name, file_id in file_ids.items(): - file_url = 'https://drive.google.com/uc?id='+file_id - save_path = osp.abspath(osp.join(save_path_root, file_name)) - if osp.exists(save_path): - user_response = input(f'{file_name} already exist. Do you want to cover it? Y/N\n') - if user_response.lower() == 'y': - print(f'Covering {file_name} to {save_path}') - gdown.download(file_url, save_path, quiet=False) - # download_file_from_google_drive(file_id, save_path) - elif user_response.lower() == 'n': - print(f'Skipping {file_name}') - else: - raise ValueError('Wrong input. Only accepts Y/N.') - else: - print(f'Downloading {file_name} to {save_path}') - gdown.download(file_url, save_path, quiet=False) - # download_file_from_google_drive(file_id, save_path) - - -def imwrite(img, file_path, params=None, auto_mkdir=True): - """Write image to file. - - Args: - img (ndarray): Image array to be written. - file_path (str): Image file path. - params (None or list): Same as opencv's :func:`imwrite` interface. - auto_mkdir (bool): If the parent folder of `file_path` does not exist, - whether to create it automatically. - - Returns: - bool: Successful or not. - """ - if auto_mkdir: - dir_name = os.path.abspath(os.path.dirname(file_path)) - os.makedirs(dir_name, exist_ok=True) - return cv2.imwrite(file_path, img, params) - - -def img2tensor(imgs, bgr2rgb=True, float32=True): - """Numpy array to tensor. - - Args: - imgs (list[ndarray] | ndarray): Input images. - bgr2rgb (bool): Whether to change bgr to rgb. - float32 (bool): Whether to change to float32. - - Returns: - list[tensor] | tensor: Tensor images. If returned results only have - one element, just return tensor. - """ - - def _totensor(img, bgr2rgb, float32): - if img.shape[2] == 3 and bgr2rgb: - if img.dtype == 'float64': - img = img.astype('float32') - img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) - # img = torch.from_numpy(img.transpose(2, 0, 1)) - img = img.transpose(2, 0, 1) - if float32: - img = img.float() - return img - - if isinstance(imgs, list): - return [_totensor(img, bgr2rgb, float32) for img in imgs] - else: - return _totensor(imgs, bgr2rgb, float32) - - -# def load_file_from_url(url, model_dir=None, progress=True, file_name=None): -# """Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py -# """ -# if model_dir is None: -# hub_dir = get_dir() -# model_dir = os.path.join(hub_dir, 'checkpoints') -# -# os.makedirs(os.path.join(ROOT_DIR, model_dir), exist_ok=True) -# -# parts = urlparse(url) -# filename = os.path.basename(parts.path) -# if file_name is not None: -# filename = file_name -# cached_file = os.path.abspath(os.path.join(ROOT_DIR, model_dir, filename)) -# if not os.path.exists(cached_file): -# print(f'Downloading: "{url}" to {cached_file}\n') -# download_url_to_file(url, cached_file, hash_prefix=None, progress=progress) -# return cached_file - - -def scandir(dir_path, suffix=None, recursive=False, full_path=False): - """Scan a directory to find the interested files. - Args: - dir_path (str): Path of the directory. - suffix (str | tuple(str), optional): File suffix that we are - interested in. Default: None. - recursive (bool, optional): If set to True, recursively scan the - directory. Default: False. - full_path (bool, optional): If set to True, include the dir_path. - Default: False. - Returns: - A generator for all the interested files with relative paths. - """ - - if (suffix is not None) and not isinstance(suffix, (str, tuple)): - raise TypeError('"suffix" must be a string or tuple of strings') - - root = dir_path - - def _scandir(dir_path, suffix, recursive): - for entry in os.scandir(dir_path): - if not entry.name.startswith('.') and entry.is_file(): - if full_path: - return_path = entry.path - else: - return_path = osp.relpath(entry.path, root) - - if suffix is None: - yield return_path - elif return_path.endswith(suffix): - yield return_path - else: - if recursive: - yield from _scandir(entry.path, suffix=suffix, recursive=recursive) - else: - continue - - return _scandir(dir_path, suffix=suffix, recursive=recursive) - - -def is_gray(img, threshold=10): - img = Image.fromarray(img) - if len(img.getbands()) == 1: - return True - img1 = np.asarray(img.getchannel(channel=0), dtype=np.int16) - img2 = np.asarray(img.getchannel(channel=1), dtype=np.int16) - img3 = np.asarray(img.getchannel(channel=2), dtype=np.int16) - diff1 = (img1 - img2).var() - diff2 = (img2 - img3).var() - diff3 = (img3 - img1).var() - diff_sum = (diff1 + diff2 + diff3) / 3.0 - if diff_sum <= threshold: - return True - else: - return False - -def rgb2gray(img, out_channel=3): - r, g, b = img[:,:,0], img[:,:,1], img[:,:,2] - gray = 0.2989 * r + 0.5870 * g + 0.1140 * b - if out_channel == 3: - gray = gray[:,:,np.newaxis].repeat(3, axis=2) - return gray - -def bgr2gray(img, out_channel=3): - b, g, r = img[:,:,0], img[:,:,1], img[:,:,2] - gray = 0.2989 * r + 0.5870 * g + 0.1140 * b - if out_channel == 3: - gray = gray[:,:,np.newaxis].repeat(3, axis=2) - return gray - - -def calc_mean_std(feat, eps=1e-5): - """ - Args: - feat (numpy): 3D [w h c]s - """ - size = feat.shape - assert len(size) == 3, 'The input feature should be 3D tensor.' - c = size[2] - feat_var = feat.reshape(-1, c).var(axis=0) + eps - feat_std = np.sqrt(feat_var).reshape(1, 1, c) - feat_mean = feat.reshape(-1, c).mean(axis=0).reshape(1, 1, c) - return feat_mean, feat_std - - -def adain_npy(content_feat, style_feat): - """Adaptive instance normalization for numpy. - - Args: - content_feat (numpy): The input feature. - style_feat (numpy): The reference feature. - """ - size = content_feat.shape - style_mean, style_std = calc_mean_std(style_feat) - content_mean, content_std = calc_mean_std(content_feat) - normalized_feat = (content_feat - np.broadcast_to(content_mean, size)) / np.broadcast_to(content_std, size) - return normalized_feat * np.broadcast_to(style_std, size) + np.broadcast_to(style_mean, size) \ No newline at end of file diff --git a/spaces/Lippmann/White-box-Cartoonization/README.md b/spaces/Lippmann/White-box-Cartoonization/README.md deleted file mode 100644 index 9860239cf42c94e385faaaa75a85311e010d64f7..0000000000000000000000000000000000000000 --- a/spaces/Lippmann/White-box-Cartoonization/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -python_version: 3.7 -title: White Box Cartoonization -emoji: 📚 -colorFrom: purple -colorTo: green -sdk: gradio -sdk_version: 2.9.4 -app_file: app.py -pinned: false -license: apache-2.0 -duplicated_from: hylee/White-box-Cartoonization ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/LittleYuan/My-Real-Bot/realesrgan/__init__.py b/spaces/LittleYuan/My-Real-Bot/realesrgan/__init__.py deleted file mode 100644 index bfea78f284116dee22510d4aa91f9e44afb7d472..0000000000000000000000000000000000000000 --- a/spaces/LittleYuan/My-Real-Bot/realesrgan/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# flake8: noqa -from .archs import * -from .data import * -from .models import * -from .utils import * -#from .version import * diff --git a/spaces/LucasCodeBreak/MusicGen/audiocraft/models/__init__.py b/spaces/LucasCodeBreak/MusicGen/audiocraft/models/__init__.py deleted file mode 100644 index 92c7a48a200eba455044cd66e0d2c1efe6494f5c..0000000000000000000000000000000000000000 --- a/spaces/LucasCodeBreak/MusicGen/audiocraft/models/__init__.py +++ /dev/null @@ -1,10 +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 .musicgen import MusicGen -from .lm import LMModel -from .encodec import CompressionModel, EncodecModel diff --git a/spaces/Marshalls/testmtd/feature_extraction/madmom/features/notes_hmm.py b/spaces/Marshalls/testmtd/feature_extraction/madmom/features/notes_hmm.py deleted file mode 100644 index a56e4a01d9dcdc10eaee17536313dcddc50ab364..0000000000000000000000000000000000000000 --- a/spaces/Marshalls/testmtd/feature_extraction/madmom/features/notes_hmm.py +++ /dev/null @@ -1,179 +0,0 @@ -# encoding: utf-8 -# pylint: disable=no-member -# pylint: disable=invalid-name -# pylint: disable=too-many-arguments -""" -This module contains HMM state spaces, transition and observation models used -for note transcription. - -Notes ------ -Please note that (almost) everything within this module is discretised to -integer values because of performance reasons. - -""" - -from __future__ import absolute_import, division, print_function - -import numpy as np - -from madmom.ml.hmm import TransitionModel, ObservationModel - - -class ADSRStateSpace(object): - """ - Map state numbers to actual states. - - State 0 refers to silence, the ADSR states (attack, decay, sustain, - release) are numbered from 1 onwards. - - Parameters - ---------- - attack_length : int, optional - Length of the attack phase. - decay_length : int, optional - Length of the decay phase. - release_length : int, optional - Length of the release phase. - - Sustain phase has no specific minimum length, since self-transitions from - this state are used to model the note length. - - """ - - def __init__(self, attack_length=1, decay_length=1, release_length=1): - - # define note with states which must be transitioned - self.silence = 0 - self.attack = 1 - self.decay = self.attack + attack_length - self.sustain = self.decay + decay_length - self.release = self.sustain + release_length - - @property - def num_states(self): - return self.release + 1 - - -class ADSRTransitionModel(TransitionModel): - """ - Transition model for note transcription with a HMM. - - Parameters - ---------- - state_space : :class:`ADSRStateSpace` instance - ADSRStateSpace which maps state numbers to states. - onset_prob : float, optional - Probability to enter/stay in the attack and decay phase. When entering - this phase from a previously sounding note, this probability will be - divided by the sum of `onset_prob`, `note_prob`, and `offset_prob`. - note_prob : float, optional - Probability to enter the sustain phase. Notes can stay in the sustain - phase given by this probability divided by the sum of `onset_prob`, - `note_prob`, and `offset_prob`. - offset_prob : float, optional - Probability to enter/stay in the release phase. - end_prob : float, optional - Probability to go back from release to silence. - - """ - - def __init__(self, state_space, onset_prob=0.8, note_prob=0.8, - offset_prob=0.2, end_prob=1.): - # save attributes - self.state_space = state_space - # states - silence = state_space.silence - attack = state_space.attack - decay = state_space.decay - sustain = state_space.sustain - release = state_space.release - # transitions = [(from_state, to_state, prob), ...] - # onset phase & min_onset_length - t = [(silence, silence, 1. - onset_prob), - (silence, attack, onset_prob)] - for s in range(attack, decay): - t.append((s, silence, 1. - onset_prob)) - t.append((s, s + 1, onset_prob)) - # transition to note & min_note_duration - for s in range(decay, sustain): - t.append((s, silence, 1. - note_prob)) - t.append((s, s + 1, note_prob)) - # 3 possibilities to continue note - prob_sum = onset_prob + note_prob + offset_prob - # 1) sustain note (keep sounding) - t.append((sustain, sustain, note_prob / prob_sum)) - # 2) new note - t.append((sustain, attack, onset_prob / prob_sum)) - # 3) release note (end note) - t.append((sustain, sustain + 1, offset_prob / prob_sum)) - # release phase - for s in range(sustain + 1, release): - t.append((s, sustain, offset_prob)) - t.append((s, s + 1, 1. - offset_prob)) - # after releasing a note, go back to silence or start new note - t.append((release, silence, end_prob)) - t.append((release, release, 1. - end_prob)) - t = np.array(t) - # make the transitions sparse - t = self.make_sparse(t[:, 1].astype(np.int), t[:, 0].astype(np.int), - t[:, 2]) - # instantiate a TransitionModel - super(ADSRTransitionModel, self).__init__(*t) - - -class ADSRObservationModel(ObservationModel): - """ - Observation model for note transcription tracking with a HMM. - - Parameters - ---------- - state_space : :class:`ADSRStateSpace` instance - ADSRStateSpace instance. - - The observed probabilities for note onsets, sounding notes, and offsets are - mapped to the states defined in the state space. The observation for - 'silence' is defined as 1 - p(onset), 'onset' as p(onset), 'decay' and - 'sustain' as p(note) and 'offset' as p(offset). - - """ - - def __init__(self, state_space): - # define observation pointers - pointers = np.zeros(state_space.num_states, dtype=np.uint32) - # map from densities to states - pointers[state_space.silence:] = 0 - pointers[state_space.attack:] = 1 - pointers[state_space.decay:] = 2 - # Note: sustain uses the same observations as decay - pointers[state_space.release:] = 3 - # instantiate a ObservationModel with the pointers - super(ADSRObservationModel, self).__init__(pointers) - - def log_densities(self, observations): - """ - Computes the log densities of the observations. - - Parameters - ---------- - observations : tuple with two numpy arrays - Observations (i.e. 3d activations of the CNN). - - Returns - ------- - numpy array - Log densities of the observations. - - """ - # observations: notes, onsets, offsets - densities = np.ones((len(observations), 4), dtype=np.float) - # silence (not onset) - densities[:, 0] = 1. - observations[:, 1] - # attack: onset - densities[:, 1] = observations[:, 1] - # decay + sustain: note - densities[:, 2] = observations[:, 0] - # release: offset - densities[:, 3] = observations[:, 2] - # return the log densities - return np.log(densities) diff --git a/spaces/MathysL/AutoGPT4/autogpt/commands/audio_text.py b/spaces/MathysL/AutoGPT4/autogpt/commands/audio_text.py deleted file mode 100644 index cae32d4eb78c4268bf6ef1bae3c15a399af046bf..0000000000000000000000000000000000000000 --- a/spaces/MathysL/AutoGPT4/autogpt/commands/audio_text.py +++ /dev/null @@ -1,36 +0,0 @@ -import json - -import requests - -from autogpt.config import Config -from autogpt.workspace import path_in_workspace - -cfg = Config() - - -def read_audio_from_file(audio_path): - audio_path = path_in_workspace(audio_path) - with open(audio_path, "rb") as audio_file: - audio = audio_file.read() - return read_audio(audio) - - -def read_audio(audio): - model = cfg.huggingface_audio_to_text_model - api_url = f"https://api-inference.huggingface.co/models/{model}" - api_token = cfg.huggingface_api_token - headers = {"Authorization": f"Bearer {api_token}"} - - if api_token is None: - raise ValueError( - "You need to set your Hugging Face API token in the config file." - ) - - response = requests.post( - api_url, - headers=headers, - data=audio, - ) - - text = json.loads(response.content.decode("utf-8"))["text"] - return "The audio says: " + text diff --git a/spaces/Mecca/whisper-webui/docs/options.md b/spaces/Mecca/whisper-webui/docs/options.md deleted file mode 100644 index 6979fca4d9d4c98a626a2953c2573ff23898a37e..0000000000000000000000000000000000000000 --- a/spaces/Mecca/whisper-webui/docs/options.md +++ /dev/null @@ -1,134 +0,0 @@ -# Standard Options -To transcribe or translate an audio file, you can either copy an URL from a website (all [websites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md) -supported by YT-DLP will work, including YouTube). Otherwise, upload an audio file (choose "All Files (*.*)" -in the file selector to select any file type, including video files) or use the microphone. - -For longer audio files (>10 minutes), it is recommended that you select Silero VAD (Voice Activity Detector) in the VAD option, especially if you are using the `large-v1` model. Note that `large-v2` is a lot more forgiving, but you may still want to use a VAD with a slightly higher "VAD - Max Merge Size (s)" (60 seconds or more). - -## Model -Select the model that Whisper will use to transcribe the audio: - -| Size | Parameters | English-only model | Multilingual model | Required VRAM | Relative speed | -|-----------|------------|--------------------|--------------------|---------------|----------------| -| tiny | 39 M | tiny.en | tiny | ~1 GB | ~32x | -| base | 74 M | base.en | base | ~1 GB | ~16x | -| small | 244 M | small.en | small | ~2 GB | ~6x | -| medium | 769 M | medium.en | medium | ~5 GB | ~2x | -| large | 1550 M | N/A | large | ~10 GB | 1x | -| large-v2 | 1550 M | N/A | large | ~10 GB | 1x | - -## Language - -Select the language, or leave it empty for Whisper to automatically detect it. - -Note that if the selected language and the language in the audio differs, Whisper may start to translate the audio to the selected -language. For instance, if the audio is in English but you select Japaneese, the model may translate the audio to Japanese. - -## Inputs -The options "URL (YouTube, etc.)", "Upload Files" or "Micriphone Input" allows you to send an audio input to the model. - -### Multiple Files -Note that the UI will only process either the given URL or the upload files (including microphone) - not both. - -But you can upload multiple files either through the "Upload files" option, or as a playlist on YouTube. Each audio file will then be processed in turn, and the resulting SRT/VTT/Transcript will be made available in the "Download" section. When more than one file is processed, the UI will also generate a "All_Output" zip file containing all the text output files. - -## Task -Select the task - either "transcribe" to transcribe the audio to text, or "translate" to translate it to English. - -## Vad -Using a VAD will improve the timing accuracy of each transcribed line, as well as prevent Whisper getting into an infinite -loop detecting the same sentence over and over again. The downside is that this may be at a cost to text accuracy, especially -with regards to unique words or names that appear in the audio. You can compensate for this by increasing the prompt window. - -Note that English is very well handled by Whisper, and it's less susceptible to issues surrounding bad timings and infinite loops. -So you may only need to use a VAD for other languages, such as Japanese, or when the audio is very long. - -* none - * Run whisper on the entire audio input -* silero-vad - * Use Silero VAD to detect sections that contain speech, and run Whisper on independently on each section. Whisper is also run - on the gaps between each speech section, by either expanding the section up to the max merge size, or running Whisper independently - on the non-speech section. -* silero-vad-expand-into-gaps - * Use Silero VAD to detect sections that contain speech, and run Whisper on independently on each section. Each spech section will be expanded - such that they cover any adjacent non-speech sections. For instance, if an audio file of one minute contains the speech sections - 00:00 - 00:10 (A) and 00:30 - 00:40 (B), the first section (A) will be expanded to 00:00 - 00:30, and (B) will be expanded to 00:30 - 00:60. -* silero-vad-skip-gaps - * As above, but sections that doesn't contain speech according to Silero will be skipped. This will be slightly faster, but - may cause dialogue to be skipped. -* periodic-vad - * Create sections of speech every 'VAD - Max Merge Size' seconds. This is very fast and simple, but will potentially break - a sentence or word in two. - -## VAD - Merge Window -If set, any adjacent speech sections that are at most this number of seconds apart will be automatically merged. - -## VAD - Max Merge Size (s) -Disables merging of adjacent speech sections if they are this number of seconds long. - -## VAD - Padding (s) -The number of seconds (floating point) to add to the beginning and end of each speech section. Setting this to a number -larger than zero ensures that Whisper is more likely to correctly transcribe a sentence in the beginning of -a speech section. However, this also increases the probability of Whisper assigning the wrong timestamp -to each transcribed line. The default value is 1 second. - -## VAD - Prompt Window (s) -The text of a detected line will be included as a prompt to the next speech section, if the speech section starts at most this -number of seconds after the line has finished. For instance, if a line ends at 10:00, and the next speech section starts at -10:04, the line's text will be included if the prompt window is 4 seconds or more (10:04 - 10:00 = 4 seconds). - -Note that detected lines in gaps between speech sections will not be included in the prompt -(if silero-vad or silero-vad-expand-into-gaps) is used. - -# Command Line Options - -Both `app.py` and `cli.py` also accept command line options, such as the ability to enable parallel execution on multiple -CPU/GPU cores, the default model name/VAD and so on. Consult the README in the root folder for more information. - -# Additional Options - -In addition to the above, there's also a "Full" options interface that allows you to set all the options available in the Whisper -model. The options are as follows: - -## Initial Prompt -Optional text to provide as a prompt for the first 30 seconds window. Whisper will attempt to use this as a starting point for the transcription, but you can -also get creative and specify a style or format for the output of the transcription. - -For instance, if you use the prompt "hello how is it going always use lowercase no punctuation goodbye one two three start stop i you me they", Whisper will -be biased to output lower capital letters and no punctuation, and may also be biased to output the words in the prompt more often. - -## Temperature -The temperature to use when sampling. Default is 0 (zero). A higher temperature will result in more random output, while a lower temperature will be more deterministic. - -## Best Of - Non-zero temperature -The number of candidates to sample from when sampling with non-zero temperature. Default is 5. - -## Beam Size - Zero temperature -The number of beams to use in beam search when sampling with zero temperature. Default is 5. - -## Patience - Zero temperature -The patience value to use in beam search when sampling with zero temperature. As in https://arxiv.org/abs/2204.05424, the default (1.0) is equivalent to conventional beam search. - -## Length Penalty - Any temperature -The token length penalty coefficient (alpha) to use when sampling with any temperature. As in https://arxiv.org/abs/1609.08144, uses simple length normalization by default. - -## Suppress Tokens - Comma-separated list of token IDs -A comma-separated list of token IDs to suppress during sampling. The default value of "-1" will suppress most special characters except common punctuations. - -## Condition on previous text -If True, provide the previous output of the model as a prompt for the next window. Disabling this may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop. - -## FP16 -Whether to perform inference in fp16. True by default. - -## Temperature increment on fallback -The temperature to increase when falling back when the decoding fails to meet either of the thresholds below. Default is 0.2. - -## Compression ratio threshold -If the gzip compression ratio is higher than this value, treat the decoding as failed. Default is 2.4. - -## Logprob threshold -If the average log probability is lower than this value, treat the decoding as failed. Default is -1.0. - -## No speech threshold -If the probability of the <|nospeech|> token is higher than this value AND the decoding has failed due to `logprob_threshold`, consider the segment as silence. Default is 0.6. diff --git a/spaces/MirageML/sjc/my/utils/plot.py b/spaces/MirageML/sjc/my/utils/plot.py deleted file mode 100644 index e4172311da88fbabcd107dd3f57b98db7638243a..0000000000000000000000000000000000000000 --- a/spaces/MirageML/sjc/my/utils/plot.py +++ /dev/null @@ -1,9 +0,0 @@ -import numpy as np -import matplotlib.pyplot as plt - - -def mpl_fig_to_buffer(fig): - fig.canvas.draw() - plot = np.array(fig.canvas.renderer.buffer_rgba()) - plt.close(fig) - return plot diff --git a/spaces/MrD05/text-generation-webui-space/convert-to-flexgen.py b/spaces/MrD05/text-generation-webui-space/convert-to-flexgen.py deleted file mode 100644 index 917f023c3fe395c2e3cbcad11c9cdc6b85ef1e7e..0000000000000000000000000000000000000000 --- a/spaces/MrD05/text-generation-webui-space/convert-to-flexgen.py +++ /dev/null @@ -1,60 +0,0 @@ -''' - -Converts a transformers model to a format compatible with flexgen. - -''' - -import argparse -import os -from pathlib import Path - -import numpy as np -import torch -from tqdm import tqdm -from transformers import AutoModelForCausalLM, AutoTokenizer - -parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54)) -parser.add_argument('MODEL', type=str, default=None, nargs='?', help="Path to the input model.") -args = parser.parse_args() - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - global torch_linear_init_backup - global torch_layer_norm_init_backup - - torch_linear_init_backup = torch.nn.Linear.reset_parameters - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - - torch_layer_norm_init_backup = torch.nn.LayerNorm.reset_parameters - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - -def restore_torch_init(): - """Rollback the change made by disable_torch_init.""" - import torch - setattr(torch.nn.Linear, "reset_parameters", torch_linear_init_backup) - setattr(torch.nn.LayerNorm, "reset_parameters", torch_layer_norm_init_backup) - -if __name__ == '__main__': - path = Path(args.MODEL) - model_name = path.name - - print(f"Loading {model_name}...") - #disable_torch_init() - model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.float16, low_cpu_mem_usage=True) - #restore_torch_init() - - tokenizer = AutoTokenizer.from_pretrained(path) - - out_folder = Path(f"models/{model_name}-np") - if not Path(out_folder).exists(): - os.mkdir(out_folder) - - print(f"Saving the converted model to {out_folder}...") - for name, param in tqdm(list(model.model.named_parameters())): - name = name.replace("decoder.final_layer_norm", "decoder.layer_norm") - param_path = os.path.join(out_folder, name) - with open(param_path, "wb") as f: - np.save(f, param.cpu().detach().numpy()) diff --git a/spaces/MuGeminorum/insecta/app.py b/spaces/MuGeminorum/insecta/app.py deleted file mode 100644 index b373747d173af42cd7339301995b97fb3a696abd..0000000000000000000000000000000000000000 --- a/spaces/MuGeminorum/insecta/app.py +++ /dev/null @@ -1,90 +0,0 @@ -import cv2 -import khandy -import numpy as np -import gradio as gr -from PIL import Image -from insectid import InsectDetector -from insectid import InsectIdentifier - - -def inference(filename): - detector = InsectDetector() - identifier = InsectIdentifier() - image = khandy.imread(filename) - - if image is None: - return None - - if max(image.shape[:2]) > 1280: - image = khandy.resize_image_long(image, 1280) - - image_for_draw = image.copy() - image_height, image_width = image.shape[:2] - boxes, confs, classes = detector.detect(image) - - for box, _, _ in zip(boxes, confs, classes): - box = box.astype(np.int32) - box_width = box[2] - box[0] + 1 - box_height = box[3] - box[1] + 1 - - if box_width < 30 or box_height < 30: - continue - - cropped = khandy.crop_or_pad(image, box[0], box[1], box[2], box[3]) - results = identifier.identify(cropped) - print(results[0]) - prob = results[0]['probability'] - - if prob < 0.10: - text = 'Unknown' - else: - text = '{} {}: {:.2f}%'.format( - results[0]['chinese_name'], - results[0]['latin_name'], - 100.0 * results[0]['probability'] - ) - - position = [box[0] + 2, box[1] - 20] - position[0] = min(max(position[0], 0), image_width) - position[1] = min(max(position[1], 0), image_height) - cv2.rectangle( - image_for_draw, - (box[0], box[1]), - (box[2], box[3]), - (0, 255, 0), - 2 - ) - - image_for_draw = khandy.draw_text( - image_for_draw, - text, - position, - font='simsun.ttc', - font_size=15 - ) - - return Image.fromarray(image_for_draw[:, :, ::-1], mode='RGB') - - -with gr.Blocks() as demo: - with gr.Tab("Image"): - gr.Markdown("## Insect Inference on Image") - with gr.Row(): - image_input = gr.Image( - type='filepath', - label="Input Image", - source="upload" - ) - - image_output = gr.Image( - type='pil', - label="Output Image", - source="canvas" - ) - - text_button = gr.Button("Detect") - - text_button.click(inference, inputs=image_input, outputs=image_output) - - -demo.launch() diff --git a/spaces/MuGeminorum/insecta/khandy/boxes/boxes_transform_translate.py b/spaces/MuGeminorum/insecta/khandy/boxes/boxes_transform_translate.py deleted file mode 100644 index 7994b9b56b869327bfa03ba86f382f551e3f8ac3..0000000000000000000000000000000000000000 --- a/spaces/MuGeminorum/insecta/khandy/boxes/boxes_transform_translate.py +++ /dev/null @@ -1,136 +0,0 @@ -import numpy as np -from .boxes_utils import assert_and_normalize_shape - - -def translate_boxes(boxes, x_shift=0, y_shift=0, copy=True): - """translate boxes coordinates in x and y dimensions. - - Args: - boxes: (N, 4+K) - x_shift: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - shift in x dimension - y_shift: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - shift in y dimension - copy: bool - - References: - `datasets.pipelines.RandomCrop` in mmdetection - """ - boxes = np.array(boxes, dtype=np.float32, copy=copy) - - x_shift = np.asarray(x_shift, np.float32) - y_shift = np.asarray(y_shift, np.float32) - - x_shift = assert_and_normalize_shape(x_shift, boxes.shape[0]) - y_shift = assert_and_normalize_shape(y_shift, boxes.shape[0]) - - boxes[:, 0] += x_shift - boxes[:, 1] += y_shift - boxes[:, 2] += x_shift - boxes[:, 3] += y_shift - return boxes - - -def adjust_boxes(boxes, x_min_shift, y_min_shift, x_max_shift, y_max_shift, copy=True): - """ - Args: - boxes: (N, 4+K) - x_min_shift: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - shift (x_min, y_min) in x dimension - y_min_shift: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - shift (x_min, y_min) in y dimension - x_max_shift: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - shift (x_max, y_max) in x dimension - y_max_shift: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - shift (x_max, y_max) in y dimension - copy: bool - """ - boxes = np.array(boxes, dtype=np.float32, copy=copy) - - x_min_shift = np.asarray(x_min_shift, np.float32) - y_min_shift = np.asarray(y_min_shift, np.float32) - x_max_shift = np.asarray(x_max_shift, np.float32) - y_max_shift = np.asarray(y_max_shift, np.float32) - - x_min_shift = assert_and_normalize_shape(x_min_shift, boxes.shape[0]) - y_min_shift = assert_and_normalize_shape(y_min_shift, boxes.shape[0]) - x_max_shift = assert_and_normalize_shape(x_max_shift, boxes.shape[0]) - y_max_shift = assert_and_normalize_shape(y_max_shift, boxes.shape[0]) - - boxes[:, 0] += x_min_shift - boxes[:, 1] += y_min_shift - boxes[:, 2] += x_max_shift - boxes[:, 3] += y_max_shift - return boxes - - -def inflate_or_deflate_boxes(boxes, width_delta=0, height_delta=0, copy=True): - """ - Args: - boxes: (N, 4+K) - width_delta: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - height_delta: array-like whose shape is (), (1,), (N,), (1, 1) or (N, 1) - copy: bool - """ - boxes = np.array(boxes, dtype=np.float32, copy=copy) - - width_delta = np.asarray(width_delta, np.float32) - height_delta = np.asarray(height_delta, np.float32) - - width_delta = assert_and_normalize_shape(width_delta, boxes.shape[0]) - height_delta = assert_and_normalize_shape(height_delta, boxes.shape[0]) - - half_width_delta = width_delta * 0.5 - half_height_delta = height_delta * 0.5 - boxes[:, 0] -= half_width_delta - boxes[:, 1] -= half_height_delta - boxes[:, 2] += half_width_delta - boxes[:, 3] += half_height_delta - return boxes - - -def inflate_boxes_to_square(boxes, copy=True): - """Inflate boxes to square - Args: - boxes: (N, 4+K) - copy: bool - """ - boxes = np.array(boxes, dtype=np.float32, copy=copy) - - widths = boxes[:, 2] - boxes[:, 0] - heights = boxes[:, 3] - boxes[:, 1] - max_side_lengths = np.maximum(widths, heights) - - width_deltas = np.subtract(max_side_lengths, widths, widths) - height_deltas = np.subtract(max_side_lengths, heights, heights) - width_deltas *= 0.5 - height_deltas *= 0.5 - boxes[:, 0] -= width_deltas - boxes[:, 1] -= height_deltas - boxes[:, 2] += width_deltas - boxes[:, 3] += height_deltas - return boxes - - -def deflate_boxes_to_square(boxes, copy=True): - """Deflate boxes to square - Args: - boxes: (N, 4+K) - copy: bool - """ - boxes = np.array(boxes, dtype=np.float32, copy=copy) - - widths = boxes[:, 2] - boxes[:, 0] - heights = boxes[:, 3] - boxes[:, 1] - min_side_lengths = np.minimum(widths, heights) - - width_deltas = np.subtract(min_side_lengths, widths, widths) - height_deltas = np.subtract(min_side_lengths, heights, heights) - width_deltas *= 0.5 - height_deltas *= 0.5 - boxes[:, 0] -= width_deltas - boxes[:, 1] -= height_deltas - boxes[:, 2] += width_deltas - boxes[:, 3] += height_deltas - return boxes - diff --git a/spaces/Muedgar/WeatherPrediction/app.py b/spaces/Muedgar/WeatherPrediction/app.py deleted file mode 100644 index 38919089563ce4829015a4259ba1c6b139fa91bb..0000000000000000000000000000000000000000 --- a/spaces/Muedgar/WeatherPrediction/app.py +++ /dev/null @@ -1,79 +0,0 @@ -import numpy as np -import pandas as pd -from sklearn.impute import SimpleImputer -from sklearn.preprocessing import LabelEncoder -from sklearn.preprocessing import StandardScaler -from sklearn.model_selection import train_test_split -from sklearn.ensemble import RandomForestClassifier -from sklearn.metrics import accuracy_score -import gradio as gr -def rainPrediction(fileCSVName): - #Importing necessary libraries - #Storing the values from the dataset in a variable - if fileCSVName == "weatherAUS.csv": - dataset = pd.read_csv("/weatherAUS.csv") - #D - X = dataset.iloc[:,[1,2,3,4,7,8,9,10,11,12,13,14,15,16,18,19,20,21]].values - Y = dataset.iloc[:,-1].values - - #Reshaping Y from a 1-dimensional(a[n]) array into a 2-dimensional(a[n][m]) array - Y = Y.reshape(-1,1) - - #Removing NA from the dataset and replacing it with the most frequent value in that column - - imputer = SimpleImputer(missing_values=np.nan,strategy='most_frequent') - X = imputer.fit_transform(X) - Y = imputer.fit_transform(Y) - - #Encoding non-numerical(i.e: W,WNW) values into numerical values(i.e: 1,2,3,4) - - le1 = LabelEncoder() - X[:,0] = le1.fit_transform(X[:,0]) - le2 = LabelEncoder() - X[:,4] = le2.fit_transform(X[:,4]) - le3 = LabelEncoder() - X[:,6] = le3.fit_transform(X[:,6]) - le4 = LabelEncoder() - X[:,7] = le4.fit_transform(X[:,7]) - le5 = LabelEncoder() - X[:,-1] = le5.fit_transform(X[:,-1]) - le6 = LabelEncoder() - Y = le6.fit_transform(Y) - - #Feature scaling to minimize data scattering - - sc = StandardScaler() - X = sc.fit_transform(X) - - #Dividing the dataset into 2 parts namely training data and testing data - - X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=0) - - #Training our model - - classifier = RandomForestClassifier(n_estimators=100,random_state=0) - classifier.fit(X_train,Y_train) - classifier.score(X_train,Y_train) - Y_test = Y_test.reshape(-1,1) - Y_pred = classifier.predict(X_test) - Y_pred = le6.inverse_transform(Y_pred) - Y_test = le6.inverse_transform(Y_test) - Y_test = Y_test.reshape(-1,1) - Y_pred = Y_pred.reshape(-1,1) - - #Concatenating our test and prediction result into a dataset - df = np.concatenate((Y_test,Y_pred),axis=1) - dataframe = pd.DataFrame(df,columns=['Rain Tomorrow','Rain Prediction']) - - #Checking the accuracy - - print(accuracy_score(Y_test,Y_pred)) - - #Print .csv file - #answer = dataframe.to_csv("predictions.csv") - - # return pd.read_csv("predictions.csv") - return dataframe - -app = gr.Interface(rainPrediction, "text", gr.outputs.Dataframe(headers=["Rain Tomorrow", "Rain Prediction"],label="All data")) -app.launch(debug=True) \ No newline at end of file diff --git a/spaces/NATSpeech/DiffSpeech/modules/commons/transformer.py b/spaces/NATSpeech/DiffSpeech/modules/commons/transformer.py deleted file mode 100644 index e79847edbdbcc10ef24602c8316e5826238d9256..0000000000000000000000000000000000000000 --- a/spaces/NATSpeech/DiffSpeech/modules/commons/transformer.py +++ /dev/null @@ -1,747 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import Parameter, Linear -from modules.commons.layers import LayerNorm, Embedding -from utils.nn.seq_utils import get_incremental_state, set_incremental_state, softmax, make_positions -import torch.nn.functional as F - -DEFAULT_MAX_SOURCE_POSITIONS = 2000 -DEFAULT_MAX_TARGET_POSITIONS = 2000 - - -class SinusoidalPositionalEmbedding(nn.Module): - """This module produces sinusoidal positional embeddings of any length. - - Padding symbols are ignored. - """ - - def __init__(self, embedding_dim, padding_idx, init_size=1024): - super().__init__() - self.embedding_dim = embedding_dim - self.padding_idx = padding_idx - self.weights = SinusoidalPositionalEmbedding.get_embedding( - init_size, - embedding_dim, - padding_idx, - ) - self.register_buffer('_float_tensor', torch.FloatTensor(1)) - - @staticmethod - def get_embedding(num_embeddings, embedding_dim, padding_idx=None): - """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". - """ - half_dim = embedding_dim // 2 - emb = math.log(10000) / (half_dim - 1) - emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb) - emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0) - emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1) - if embedding_dim % 2 == 1: - # zero pad - emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) - if padding_idx is not None: - emb[padding_idx, :] = 0 - return emb - - def forward(self, input, incremental_state=None, timestep=None, positions=None, **kwargs): - """Input is expected to be of size [bsz x seqlen].""" - bsz, seq_len = input.shape[:2] - max_pos = self.padding_idx + 1 + seq_len - if self.weights is None or max_pos > self.weights.size(0): - # recompute/expand embeddings if needed - self.weights = SinusoidalPositionalEmbedding.get_embedding( - max_pos, - self.embedding_dim, - self.padding_idx, - ) - self.weights = self.weights.to(self._float_tensor) - - if incremental_state is not None: - # positions is the same for every token when decoding a single step - pos = timestep.view(-1)[0] + 1 if timestep is not None else seq_len - return self.weights[self.padding_idx + pos, :].expand(bsz, 1, -1) - - positions = make_positions(input, self.padding_idx) if positions is None else positions - return self.weights.index_select(0, positions.view(-1)).view(bsz, seq_len, -1).detach() - - def max_positions(self): - """Maximum number of supported positions.""" - return int(1e5) # an arbitrary large number - - -class TransformerFFNLayer(nn.Module): - def __init__(self, hidden_size, filter_size, padding="SAME", kernel_size=1, dropout=0., act='gelu'): - super().__init__() - self.kernel_size = kernel_size - self.dropout = dropout - self.act = act - if padding == 'SAME': - self.ffn_1 = nn.Conv1d(hidden_size, filter_size, kernel_size, padding=kernel_size // 2) - elif padding == 'LEFT': - self.ffn_1 = nn.Sequential( - nn.ConstantPad1d((kernel_size - 1, 0), 0.0), - nn.Conv1d(hidden_size, filter_size, kernel_size) - ) - self.ffn_2 = Linear(filter_size, hidden_size) - - def forward(self, x, incremental_state=None): - # x: T x B x C - if incremental_state is not None: - saved_state = self._get_input_buffer(incremental_state) - if 'prev_input' in saved_state: - prev_input = saved_state['prev_input'] - x = torch.cat((prev_input, x), dim=0) - x = x[-self.kernel_size:] - saved_state['prev_input'] = x - self._set_input_buffer(incremental_state, saved_state) - - x = self.ffn_1(x.permute(1, 2, 0)).permute(2, 0, 1) - x = x * self.kernel_size ** -0.5 - - if incremental_state is not None: - x = x[-1:] - if self.act == 'gelu': - x = F.gelu(x) - if self.act == 'relu': - x = F.relu(x) - x = F.dropout(x, self.dropout, training=self.training) - x = self.ffn_2(x) - return x - - def _get_input_buffer(self, incremental_state): - return get_incremental_state( - self, - incremental_state, - 'f', - ) or {} - - def _set_input_buffer(self, incremental_state, buffer): - set_incremental_state( - self, - incremental_state, - 'f', - buffer, - ) - - def clear_buffer(self, incremental_state): - if incremental_state is not None: - saved_state = self._get_input_buffer(incremental_state) - if 'prev_input' in saved_state: - del saved_state['prev_input'] - self._set_input_buffer(incremental_state, saved_state) - - -class MultiheadAttention(nn.Module): - def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0., bias=True, - add_bias_kv=False, add_zero_attn=False, self_attention=False, - encoder_decoder_attention=False): - super().__init__() - self.embed_dim = embed_dim - self.kdim = kdim if kdim is not None else embed_dim - self.vdim = vdim if vdim is not None else embed_dim - self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim - - self.num_heads = num_heads - self.dropout = dropout - self.head_dim = embed_dim // num_heads - assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" - self.scaling = self.head_dim ** -0.5 - - self.self_attention = self_attention - self.encoder_decoder_attention = encoder_decoder_attention - - assert not self.self_attention or self.qkv_same_dim, 'Self-attention requires query, key and ' \ - 'value to be of the same size' - - if self.qkv_same_dim: - self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim)) - else: - self.k_proj_weight = Parameter(torch.Tensor(embed_dim, self.kdim)) - self.v_proj_weight = Parameter(torch.Tensor(embed_dim, self.vdim)) - self.q_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) - - if bias: - self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim)) - else: - self.register_parameter('in_proj_bias', None) - - self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) - - if add_bias_kv: - self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim)) - self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim)) - else: - self.bias_k = self.bias_v = None - - self.add_zero_attn = add_zero_attn - - self.reset_parameters() - - self.enable_torch_version = False - if hasattr(F, "multi_head_attention_forward"): - self.enable_torch_version = True - else: - self.enable_torch_version = False - self.last_attn_probs = None - - def reset_parameters(self): - if self.qkv_same_dim: - nn.init.xavier_uniform_(self.in_proj_weight) - else: - nn.init.xavier_uniform_(self.k_proj_weight) - nn.init.xavier_uniform_(self.v_proj_weight) - nn.init.xavier_uniform_(self.q_proj_weight) - - nn.init.xavier_uniform_(self.out_proj.weight) - if self.in_proj_bias is not None: - nn.init.constant_(self.in_proj_bias, 0.) - nn.init.constant_(self.out_proj.bias, 0.) - if self.bias_k is not None: - nn.init.xavier_normal_(self.bias_k) - if self.bias_v is not None: - nn.init.xavier_normal_(self.bias_v) - - def forward( - self, - query, key, value, - key_padding_mask=None, - incremental_state=None, - need_weights=True, - static_kv=False, - attn_mask=None, - before_softmax=False, - need_head_weights=False, - enc_dec_attn_constraint_mask=None, - reset_attn_weight=None - ): - """Input shape: Time x Batch x Channel - - Args: - key_padding_mask (ByteTensor, optional): mask to exclude - keys that are pads, of shape `(batch, src_len)`, where - padding elements are indicated by 1s. - need_weights (bool, optional): return the attention weights, - averaged over heads (default: False). - attn_mask (ByteTensor, optional): typically used to - implement causal attention, where the mask prevents the - attention from looking forward in time (default: None). - before_softmax (bool, optional): return the raw attention - weights and values before the attention softmax. - need_head_weights (bool, optional): return the attention - weights for each head. Implies *need_weights*. Default: - return the average attention weights over all heads. - """ - if need_head_weights: - need_weights = True - - tgt_len, bsz, embed_dim = query.size() - assert embed_dim == self.embed_dim - assert list(query.size()) == [tgt_len, bsz, embed_dim] - if self.enable_torch_version and incremental_state is None and not static_kv and reset_attn_weight is None: - if self.qkv_same_dim: - return F.multi_head_attention_forward(query, key, value, - self.embed_dim, self.num_heads, - self.in_proj_weight, - self.in_proj_bias, self.bias_k, self.bias_v, - self.add_zero_attn, self.dropout, - self.out_proj.weight, self.out_proj.bias, - self.training, key_padding_mask, need_weights, - attn_mask) - else: - return F.multi_head_attention_forward(query, key, value, - self.embed_dim, self.num_heads, - torch.empty([0]), - self.in_proj_bias, self.bias_k, self.bias_v, - self.add_zero_attn, self.dropout, - self.out_proj.weight, self.out_proj.bias, - self.training, key_padding_mask, need_weights, - attn_mask, use_separate_proj_weight=True, - q_proj_weight=self.q_proj_weight, - k_proj_weight=self.k_proj_weight, - v_proj_weight=self.v_proj_weight) - - if incremental_state is not None: - saved_state = self._get_input_buffer(incremental_state) - if 'prev_key' in saved_state: - # previous time steps are cached - no need to recompute - # key and value if they are static - if static_kv: - assert self.encoder_decoder_attention and not self.self_attention - key = value = None - else: - saved_state = None - - if self.self_attention: - # self-attention - q, k, v = self.in_proj_qkv(query) - elif self.encoder_decoder_attention: - # encoder-decoder attention - q = self.in_proj_q(query) - if key is None: - assert value is None - k = v = None - else: - k = self.in_proj_k(key) - v = self.in_proj_v(key) - - else: - q = self.in_proj_q(query) - k = self.in_proj_k(key) - v = self.in_proj_v(value) - q *= self.scaling - - if self.bias_k is not None: - assert self.bias_v is not None - k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)]) - v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)]) - if attn_mask is not None: - attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1) - if key_padding_mask is not None: - key_padding_mask = torch.cat( - [key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1)], dim=1) - - q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1) - if k is not None: - k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1) - if v is not None: - v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1) - - if saved_state is not None: - # saved states are stored with shape (bsz, num_heads, seq_len, head_dim) - if 'prev_key' in saved_state: - prev_key = saved_state['prev_key'].view(bsz * self.num_heads, -1, self.head_dim) - if static_kv: - k = prev_key - else: - k = torch.cat((prev_key, k), dim=1) - if 'prev_value' in saved_state: - prev_value = saved_state['prev_value'].view(bsz * self.num_heads, -1, self.head_dim) - if static_kv: - v = prev_value - else: - v = torch.cat((prev_value, v), dim=1) - if 'prev_key_padding_mask' in saved_state and saved_state['prev_key_padding_mask'] is not None: - prev_key_padding_mask = saved_state['prev_key_padding_mask'] - if static_kv: - key_padding_mask = prev_key_padding_mask - else: - key_padding_mask = torch.cat((prev_key_padding_mask, key_padding_mask), dim=1) - - saved_state['prev_key'] = k.view(bsz, self.num_heads, -1, self.head_dim) - saved_state['prev_value'] = v.view(bsz, self.num_heads, -1, self.head_dim) - saved_state['prev_key_padding_mask'] = key_padding_mask - - self._set_input_buffer(incremental_state, saved_state) - - src_len = k.size(1) - - # This is part of a workaround to get around fork/join parallelism - # not supporting Optional types. - if key_padding_mask is not None and key_padding_mask.shape == torch.Size([]): - key_padding_mask = None - - if key_padding_mask is not None: - assert key_padding_mask.size(0) == bsz - assert key_padding_mask.size(1) == src_len - - if self.add_zero_attn: - src_len += 1 - k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1) - v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1) - if attn_mask is not None: - attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1) - if key_padding_mask is not None: - key_padding_mask = torch.cat( - [key_padding_mask, torch.zeros(key_padding_mask.size(0), 1).type_as(key_padding_mask)], dim=1) - - attn_weights = torch.bmm(q, k.transpose(1, 2)) - attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz) - - assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] - - if attn_mask is not None: - if len(attn_mask.shape) == 2: - attn_mask = attn_mask.unsqueeze(0) - elif len(attn_mask.shape) == 3: - attn_mask = attn_mask[:, None].repeat([1, self.num_heads, 1, 1]).reshape( - bsz * self.num_heads, tgt_len, src_len) - attn_weights = attn_weights + attn_mask - - if enc_dec_attn_constraint_mask is not None: # bs x head x L_kv - attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) - attn_weights = attn_weights.masked_fill( - enc_dec_attn_constraint_mask.unsqueeze(2).bool(), - -1e8, - ) - attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) - - if key_padding_mask is not None: - # don't attend to padding symbols - attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) - attn_weights = attn_weights.masked_fill( - key_padding_mask.unsqueeze(1).unsqueeze(2), - -1e8, - ) - attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) - - attn_logits = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) - - if before_softmax: - return attn_weights, v - - attn_weights_float = softmax(attn_weights, dim=-1) - attn_weights = attn_weights_float.type_as(attn_weights) - attn_probs = F.dropout(attn_weights_float.type_as(attn_weights), p=self.dropout, training=self.training) - - if reset_attn_weight is not None: - if reset_attn_weight: - self.last_attn_probs = attn_probs.detach() - else: - assert self.last_attn_probs is not None - attn_probs = self.last_attn_probs - attn = torch.bmm(attn_probs, v) - assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim] - attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) - attn = self.out_proj(attn) - - if need_weights: - attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0) - if not need_head_weights: - # average attention weights over heads - attn_weights = attn_weights.mean(dim=0) - else: - attn_weights = None - - return attn, (attn_weights, attn_logits) - - def in_proj_qkv(self, query): - return self._in_proj(query).chunk(3, dim=-1) - - def in_proj_q(self, query): - if self.qkv_same_dim: - return self._in_proj(query, end=self.embed_dim) - else: - bias = self.in_proj_bias - if bias is not None: - bias = bias[:self.embed_dim] - return F.linear(query, self.q_proj_weight, bias) - - def in_proj_k(self, key): - if self.qkv_same_dim: - return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim) - else: - weight = self.k_proj_weight - bias = self.in_proj_bias - if bias is not None: - bias = bias[self.embed_dim:2 * self.embed_dim] - return F.linear(key, weight, bias) - - def in_proj_v(self, value): - if self.qkv_same_dim: - return self._in_proj(value, start=2 * self.embed_dim) - else: - weight = self.v_proj_weight - bias = self.in_proj_bias - if bias is not None: - bias = bias[2 * self.embed_dim:] - return F.linear(value, weight, bias) - - def _in_proj(self, input, start=0, end=None): - weight = self.in_proj_weight - bias = self.in_proj_bias - weight = weight[start:end, :] - if bias is not None: - bias = bias[start:end] - return F.linear(input, weight, bias) - - def _get_input_buffer(self, incremental_state): - return get_incremental_state( - self, - incremental_state, - 'attn_state', - ) or {} - - def _set_input_buffer(self, incremental_state, buffer): - set_incremental_state( - self, - incremental_state, - 'attn_state', - buffer, - ) - - def apply_sparse_mask(self, attn_weights, tgt_len, src_len, bsz): - return attn_weights - - def clear_buffer(self, incremental_state=None): - if incremental_state is not None: - saved_state = self._get_input_buffer(incremental_state) - if 'prev_key' in saved_state: - del saved_state['prev_key'] - if 'prev_value' in saved_state: - del saved_state['prev_value'] - self._set_input_buffer(incremental_state, saved_state) - - -class EncSALayer(nn.Module): - def __init__(self, c, num_heads, dropout, attention_dropout=0.1, - relu_dropout=0.1, kernel_size=9, padding='SAME', act='gelu'): - super().__init__() - self.c = c - self.dropout = dropout - self.num_heads = num_heads - if num_heads > 0: - self.layer_norm1 = LayerNorm(c) - self.self_attn = MultiheadAttention( - self.c, num_heads, self_attention=True, dropout=attention_dropout, bias=False) - self.layer_norm2 = LayerNorm(c) - self.ffn = TransformerFFNLayer( - c, 4 * c, kernel_size=kernel_size, dropout=relu_dropout, padding=padding, act=act) - - def forward(self, x, encoder_padding_mask=None, **kwargs): - layer_norm_training = kwargs.get('layer_norm_training', None) - if layer_norm_training is not None: - self.layer_norm1.training = layer_norm_training - self.layer_norm2.training = layer_norm_training - if self.num_heads > 0: - residual = x - x = self.layer_norm1(x) - x, _, = self.self_attn( - query=x, - key=x, - value=x, - key_padding_mask=encoder_padding_mask - ) - x = F.dropout(x, self.dropout, training=self.training) - x = residual + x - x = x * (1 - encoder_padding_mask.float()).transpose(0, 1)[..., None] - - residual = x - x = self.layer_norm2(x) - x = self.ffn(x) - x = F.dropout(x, self.dropout, training=self.training) - x = residual + x - x = x * (1 - encoder_padding_mask.float()).transpose(0, 1)[..., None] - return x - - -class DecSALayer(nn.Module): - def __init__(self, c, num_heads, dropout, attention_dropout=0.1, relu_dropout=0.1, - kernel_size=9, act='gelu'): - super().__init__() - self.c = c - self.dropout = dropout - self.layer_norm1 = LayerNorm(c) - self.self_attn = MultiheadAttention( - c, num_heads, self_attention=True, dropout=attention_dropout, bias=False - ) - self.layer_norm2 = LayerNorm(c) - self.encoder_attn = MultiheadAttention( - c, num_heads, encoder_decoder_attention=True, dropout=attention_dropout, bias=False, - ) - self.layer_norm3 = LayerNorm(c) - self.ffn = TransformerFFNLayer( - c, 4 * c, padding='LEFT', kernel_size=kernel_size, dropout=relu_dropout, act=act) - - def forward( - self, - x, - encoder_out=None, - encoder_padding_mask=None, - incremental_state=None, - self_attn_mask=None, - self_attn_padding_mask=None, - attn_out=None, - reset_attn_weight=None, - **kwargs, - ): - layer_norm_training = kwargs.get('layer_norm_training', None) - if layer_norm_training is not None: - self.layer_norm1.training = layer_norm_training - self.layer_norm2.training = layer_norm_training - self.layer_norm3.training = layer_norm_training - residual = x - x = self.layer_norm1(x) - x, _ = self.self_attn( - query=x, - key=x, - value=x, - key_padding_mask=self_attn_padding_mask, - incremental_state=incremental_state, - attn_mask=self_attn_mask - ) - x = F.dropout(x, self.dropout, training=self.training) - x = residual + x - - attn_logits = None - if encoder_out is not None or attn_out is not None: - residual = x - x = self.layer_norm2(x) - if encoder_out is not None: - x, attn = self.encoder_attn( - query=x, - key=encoder_out, - value=encoder_out, - key_padding_mask=encoder_padding_mask, - incremental_state=incremental_state, - static_kv=True, - enc_dec_attn_constraint_mask=get_incremental_state(self, incremental_state, - 'enc_dec_attn_constraint_mask'), - reset_attn_weight=reset_attn_weight - ) - attn_logits = attn[1] - elif attn_out is not None: - x = self.encoder_attn.in_proj_v(attn_out) - if encoder_out is not None or attn_out is not None: - x = F.dropout(x, self.dropout, training=self.training) - x = residual + x - - residual = x - x = self.layer_norm3(x) - x = self.ffn(x, incremental_state=incremental_state) - x = F.dropout(x, self.dropout, training=self.training) - x = residual + x - return x, attn_logits - - def clear_buffer(self, input, encoder_out=None, encoder_padding_mask=None, incremental_state=None): - self.encoder_attn.clear_buffer(incremental_state) - self.ffn.clear_buffer(incremental_state) - - def set_buffer(self, name, tensor, incremental_state): - return set_incremental_state(self, incremental_state, name, tensor) - - -class TransformerEncoderLayer(nn.Module): - def __init__(self, hidden_size, dropout, kernel_size=9, num_heads=2): - super().__init__() - self.hidden_size = hidden_size - self.dropout = dropout - self.num_heads = num_heads - self.op = EncSALayer( - hidden_size, num_heads, dropout=dropout, - attention_dropout=0.0, relu_dropout=dropout, - kernel_size=kernel_size) - - def forward(self, x, **kwargs): - return self.op(x, **kwargs) - - -class TransformerDecoderLayer(nn.Module): - def __init__(self, hidden_size, dropout, kernel_size=9, num_heads=2): - super().__init__() - self.hidden_size = hidden_size - self.dropout = dropout - self.num_heads = num_heads - self.op = DecSALayer( - hidden_size, num_heads, dropout=dropout, - attention_dropout=0.0, relu_dropout=dropout, - kernel_size=kernel_size) - - def forward(self, x, **kwargs): - return self.op(x, **kwargs) - - def clear_buffer(self, *args): - return self.op.clear_buffer(*args) - - def set_buffer(self, *args): - return self.op.set_buffer(*args) - - -class FFTBlocks(nn.Module): - def __init__(self, hidden_size, num_layers, ffn_kernel_size=9, dropout=0.0, - num_heads=2, use_pos_embed=True, use_last_norm=True, - use_pos_embed_alpha=True): - super().__init__() - self.num_layers = num_layers - embed_dim = self.hidden_size = hidden_size - self.dropout = dropout - self.use_pos_embed = use_pos_embed - self.use_last_norm = use_last_norm - if use_pos_embed: - self.max_source_positions = DEFAULT_MAX_TARGET_POSITIONS - self.padding_idx = 0 - self.pos_embed_alpha = nn.Parameter(torch.Tensor([1])) if use_pos_embed_alpha else 1 - self.embed_positions = SinusoidalPositionalEmbedding( - embed_dim, self.padding_idx, init_size=DEFAULT_MAX_TARGET_POSITIONS, - ) - - self.layers = nn.ModuleList([]) - self.layers.extend([ - TransformerEncoderLayer(self.hidden_size, self.dropout, - kernel_size=ffn_kernel_size, num_heads=num_heads) - for _ in range(self.num_layers) - ]) - if self.use_last_norm: - self.layer_norm = nn.LayerNorm(embed_dim) - else: - self.layer_norm = None - - def forward(self, x, padding_mask=None, attn_mask=None, return_hiddens=False): - """ - :param x: [B, T, C] - :param padding_mask: [B, T] - :return: [B, T, C] or [L, B, T, C] - """ - padding_mask = x.abs().sum(-1).eq(0).data if padding_mask is None else padding_mask - nonpadding_mask_TB = 1 - padding_mask.transpose(0, 1).float()[:, :, None] # [T, B, 1] - if self.use_pos_embed: - positions = self.pos_embed_alpha * self.embed_positions(x[..., 0]) - x = x + positions - x = F.dropout(x, p=self.dropout, training=self.training) - # B x T x C -> T x B x C - x = x.transpose(0, 1) * nonpadding_mask_TB - hiddens = [] - for layer in self.layers: - x = layer(x, encoder_padding_mask=padding_mask, attn_mask=attn_mask) * nonpadding_mask_TB - hiddens.append(x) - if self.use_last_norm: - x = self.layer_norm(x) * nonpadding_mask_TB - if return_hiddens: - x = torch.stack(hiddens, 0) # [L, T, B, C] - x = x.transpose(1, 2) # [L, B, T, C] - else: - x = x.transpose(0, 1) # [B, T, C] - return x - - -class FastSpeechEncoder(FFTBlocks): - def __init__(self, dict_size, hidden_size=256, num_layers=4, kernel_size=9, num_heads=2, - dropout=0.0): - super().__init__(hidden_size, num_layers, kernel_size, num_heads=num_heads, - use_pos_embed=False, dropout=dropout) # use_pos_embed_alpha for compatibility - self.embed_tokens = Embedding(dict_size, hidden_size, 0) - self.embed_scale = math.sqrt(hidden_size) - self.padding_idx = 0 - self.embed_positions = SinusoidalPositionalEmbedding( - hidden_size, self.padding_idx, init_size=DEFAULT_MAX_TARGET_POSITIONS, - ) - - def forward(self, txt_tokens, attn_mask=None): - """ - - :param txt_tokens: [B, T] - :return: { - 'encoder_out': [B x T x C] - } - """ - encoder_padding_mask = txt_tokens.eq(self.padding_idx).data - x = self.forward_embedding(txt_tokens) # [B, T, H] - if self.num_layers > 0: - x = super(FastSpeechEncoder, self).forward(x, encoder_padding_mask, attn_mask=attn_mask) - return x - - def forward_embedding(self, txt_tokens): - # embed tokens and positions - x = self.embed_scale * self.embed_tokens(txt_tokens) - if self.use_pos_embed: - positions = self.embed_positions(txt_tokens) - x = x + positions - x = F.dropout(x, p=self.dropout, training=self.training) - return x - - -class FastSpeechDecoder(FFTBlocks): - def __init__(self, hidden_size=256, num_layers=4, kernel_size=9, num_heads=2): - super().__init__(hidden_size, num_layers, kernel_size, num_heads=num_heads) diff --git a/spaces/NATSpeech/DiffSpeech/utils/audio/rnnoise.py b/spaces/NATSpeech/DiffSpeech/utils/audio/rnnoise.py deleted file mode 100644 index 47f4eb6471918ca8144f217580a71d1720cd8c36..0000000000000000000000000000000000000000 --- a/spaces/NATSpeech/DiffSpeech/utils/audio/rnnoise.py +++ /dev/null @@ -1,48 +0,0 @@ -# rnnoise.py, requirements: ffmpeg, sox, rnnoise, python -import os -import subprocess - -INSTALL_STR = """ -RNNoise library not found. Please install RNNoise (https://github.com/xiph/rnnoise) to $REPO/rnnoise: -sudo apt-get install -y autoconf automake libtool ffmpeg sox -git clone https://github.com/xiph/rnnoise.git -rm -rf rnnoise/.git -cd rnnoise -./autogen.sh && ./configure && make -cd .. -""" - - -def rnnoise(filename, out_fn=None, verbose=False, out_sample_rate=22050): - assert os.path.exists('./rnnoise/examples/rnnoise_demo'), INSTALL_STR - if out_fn is None: - out_fn = f"{filename[:-4]}.denoised.wav" - out_48k_fn = f"{out_fn}.48000.wav" - tmp0_fn = f"{out_fn}.0.wav" - tmp1_fn = f"{out_fn}.1.wav" - tmp2_fn = f"{out_fn}.2.raw" - tmp3_fn = f"{out_fn}.3.raw" - if verbose: - print("Pre-processing audio...") # wav to pcm raw - subprocess.check_call( - f'sox "{filename}" -G -r48000 "{tmp0_fn}"', shell=True, stdin=subprocess.PIPE) # convert to raw - subprocess.check_call( - f'sox -v 0.95 "{tmp0_fn}" "{tmp1_fn}"', shell=True, stdin=subprocess.PIPE) # convert to raw - subprocess.check_call( - f'ffmpeg -y -i "{tmp1_fn}" -loglevel quiet -f s16le -ac 1 -ar 48000 "{tmp2_fn}"', - shell=True, stdin=subprocess.PIPE) # convert to raw - if verbose: - print("Applying rnnoise algorithm to audio...") # rnnoise - subprocess.check_call( - f'./rnnoise/examples/rnnoise_demo "{tmp2_fn}" "{tmp3_fn}"', shell=True) - - if verbose: - print("Post-processing audio...") # pcm raw to wav - if filename == out_fn: - subprocess.check_call(f'rm -f "{out_fn}"', shell=True) - subprocess.check_call( - f'sox -t raw -r 48000 -b 16 -e signed-integer -c 1 "{tmp3_fn}" "{out_48k_fn}"', shell=True) - subprocess.check_call(f'sox "{out_48k_fn}" -G -r{out_sample_rate} "{out_fn}"', shell=True) - subprocess.check_call(f'rm -f "{tmp0_fn}" "{tmp1_fn}" "{tmp2_fn}" "{tmp3_fn}" "{out_48k_fn}"', shell=True) - if verbose: - print("Audio-filtering completed!") diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/audio/raw_audio_dataset.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/audio/raw_audio_dataset.py deleted file mode 100644 index f4e965493cdf94a1f92fa7dab45cc68973c8cdb5..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/audio/raw_audio_dataset.py +++ /dev/null @@ -1,392 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - - -import logging -import os -import sys -import io - -import numpy as np -import torch -import torch.nn.functional as F - -from .. import FairseqDataset -from ..data_utils import compute_mask_indices, get_buckets, get_bucketed_sizes -from fairseq.data.audio.audio_utils import ( - parse_path, - read_from_stored_zip, - is_sf_audio_data, -) -from fairseq.data.text_compressor import TextCompressor, TextCompressionLevel - - -logger = logging.getLogger(__name__) - - -class RawAudioDataset(FairseqDataset): - def __init__( - self, - sample_rate, - max_sample_size=None, - min_sample_size=0, - shuffle=True, - pad=False, - normalize=False, - compute_mask_indices=False, - **mask_compute_kwargs, - ): - super().__init__() - - self.sample_rate = sample_rate - self.sizes = [] - self.max_sample_size = ( - max_sample_size if max_sample_size is not None else sys.maxsize - ) - self.min_sample_size = min_sample_size - self.pad = pad - self.shuffle = shuffle - self.normalize = normalize - self.compute_mask_indices = compute_mask_indices - if self.compute_mask_indices: - self.mask_compute_kwargs = mask_compute_kwargs - self._features_size_map = {} - self._C = mask_compute_kwargs["encoder_embed_dim"] - self._conv_feature_layers = eval(mask_compute_kwargs["conv_feature_layers"]) - - def __getitem__(self, index): - raise NotImplementedError() - - def __len__(self): - return len(self.sizes) - - def postprocess(self, feats, curr_sample_rate): - if feats.dim() == 2: - feats = feats.mean(-1) - - if curr_sample_rate != self.sample_rate: - raise Exception(f"sample rate: {curr_sample_rate}, need {self.sample_rate}") - - assert feats.dim() == 1, feats.dim() - - if self.normalize: - with torch.no_grad(): - feats = F.layer_norm(feats, feats.shape) - return feats - - def crop_to_max_size(self, wav, target_size): - size = len(wav) - diff = size - target_size - if diff <= 0: - return wav - - start = np.random.randint(0, diff + 1) - end = size - diff + start - return wav[start:end] - - def _compute_mask_indices(self, dims, padding_mask): - B, T, C = dims - mask_indices, mask_channel_indices = None, None - if self.mask_compute_kwargs["mask_prob"] > 0: - mask_indices = compute_mask_indices( - (B, T), - padding_mask, - self.mask_compute_kwargs["mask_prob"], - self.mask_compute_kwargs["mask_length"], - self.mask_compute_kwargs["mask_selection"], - self.mask_compute_kwargs["mask_other"], - min_masks=2, - no_overlap=self.mask_compute_kwargs["no_mask_overlap"], - min_space=self.mask_compute_kwargs["mask_min_space"], - ) - mask_indices = torch.from_numpy(mask_indices) - if self.mask_compute_kwargs["mask_channel_prob"] > 0: - mask_channel_indices = compute_mask_indices( - (B, C), - None, - self.mask_compute_kwargs["mask_channel_prob"], - self.mask_compute_kwargs["mask_channel_length"], - self.mask_compute_kwargs["mask_channel_selection"], - self.mask_compute_kwargs["mask_channel_other"], - no_overlap=self.mask_compute_kwargs["no_mask_channel_overlap"], - min_space=self.mask_compute_kwargs["mask_channel_min_space"], - ) - mask_channel_indices = ( - torch.from_numpy(mask_channel_indices).unsqueeze(1).expand(-1, T, -1) - ) - - return mask_indices, mask_channel_indices - - @staticmethod - def _bucket_tensor(tensor, num_pad, value): - return F.pad(tensor, (0, num_pad), value=value) - - def collater(self, samples): - samples = [s for s in samples if s["source"] is not None] - if len(samples) == 0: - return {} - - sources = [s["source"] for s in samples] - sizes = [len(s) for s in sources] - - if self.pad: - target_size = min(max(sizes), self.max_sample_size) - else: - target_size = min(min(sizes), self.max_sample_size) - - collated_sources = sources[0].new_zeros(len(sources), target_size) - padding_mask = ( - torch.BoolTensor(collated_sources.shape).fill_(False) if self.pad else None - ) - for i, (source, size) in enumerate(zip(sources, sizes)): - diff = size - target_size - if diff == 0: - collated_sources[i] = source - elif diff < 0: - assert self.pad - collated_sources[i] = torch.cat( - [source, source.new_full((-diff,), 0.0)] - ) - padding_mask[i, diff:] = True - else: - collated_sources[i] = self.crop_to_max_size(source, target_size) - - input = {"source": collated_sources} - out = {"id": torch.LongTensor([s["id"] for s in samples])} - if self.pad: - input["padding_mask"] = padding_mask - - if hasattr(self, "num_buckets") and self.num_buckets > 0: - assert self.pad, "Cannot bucket without padding first." - bucket = max(self._bucketed_sizes[s["id"]] for s in samples) - num_pad = bucket - collated_sources.size(-1) - if num_pad: - input["source"] = self._bucket_tensor(collated_sources, num_pad, 0) - input["padding_mask"] = self._bucket_tensor(padding_mask, num_pad, True) - - if self.compute_mask_indices: - B = input["source"].size(0) - T = self._get_mask_indices_dims(input["source"].size(-1)) - padding_mask_reshaped = input["padding_mask"].clone() - extra = padding_mask_reshaped.size(1) % T - if extra > 0: - padding_mask_reshaped = padding_mask_reshaped[:, :-extra] - padding_mask_reshaped = padding_mask_reshaped.view( - padding_mask_reshaped.size(0), T, -1 - ) - padding_mask_reshaped = padding_mask_reshaped.all(-1) - input["padding_count"] = padding_mask_reshaped.sum(-1).max().item() - mask_indices, mask_channel_indices = self._compute_mask_indices( - (B, T, self._C), - padding_mask_reshaped, - ) - input["mask_indices"] = mask_indices - input["mask_channel_indices"] = mask_channel_indices - out["sample_size"] = mask_indices.sum().item() - - out["net_input"] = input - return out - - def _get_mask_indices_dims(self, size, padding=0, dilation=1): - if size not in self._features_size_map: - L_in = size - for (_, kernel_size, stride) in self._conv_feature_layers: - L_out = L_in + 2 * padding - dilation * (kernel_size - 1) - 1 - L_out = 1 + L_out // stride - L_in = L_out - self._features_size_map[size] = L_out - return self._features_size_map[size] - - def num_tokens(self, index): - return self.size(index) - - def size(self, index): - """Return an example's size as a float or tuple. This value is used when - filtering a dataset with ``--max-positions``.""" - if self.pad: - return self.sizes[index] - return min(self.sizes[index], self.max_sample_size) - - def ordered_indices(self): - """Return an ordered list of indices. Batches will be constructed based - on this order.""" - - if self.shuffle: - order = [np.random.permutation(len(self))] - order.append( - np.minimum( - np.array(self.sizes), - self.max_sample_size, - ) - ) - return np.lexsort(order)[::-1] - else: - return np.arange(len(self)) - - def set_bucket_info(self, num_buckets): - self.num_buckets = num_buckets - if self.num_buckets > 0: - self._collated_sizes = np.minimum( - np.array(self.sizes), - self.max_sample_size, - ) - self.buckets = get_buckets( - self._collated_sizes, - self.num_buckets, - ) - self._bucketed_sizes = get_bucketed_sizes( - self._collated_sizes, self.buckets - ) - logger.info( - f"{len(self.buckets)} bucket(s) for the audio dataset: " - f"{self.buckets}" - ) - - -class FileAudioDataset(RawAudioDataset): - def __init__( - self, - manifest_path, - sample_rate, - max_sample_size=None, - min_sample_size=0, - shuffle=True, - pad=False, - normalize=False, - num_buckets=0, - compute_mask_indices=False, - text_compression_level=TextCompressionLevel.none, - **mask_compute_kwargs, - ): - super().__init__( - sample_rate=sample_rate, - max_sample_size=max_sample_size, - min_sample_size=min_sample_size, - shuffle=shuffle, - pad=pad, - normalize=normalize, - compute_mask_indices=compute_mask_indices, - **mask_compute_kwargs, - ) - - self.text_compressor = TextCompressor(level=text_compression_level) - - skipped = 0 - self.fnames = [] - sizes = [] - self.skipped_indices = set() - - with open(manifest_path, "r") as f: - self.root_dir = f.readline().strip() - for i, line in enumerate(f): - items = line.strip().split("\t") - assert len(items) == 2, line - sz = int(items[1]) - if min_sample_size is not None and sz < min_sample_size: - skipped += 1 - self.skipped_indices.add(i) - continue - self.fnames.append(self.text_compressor.compress(items[0])) - sizes.append(sz) - logger.info(f"loaded {len(self.fnames)}, skipped {skipped} samples") - - self.sizes = np.array(sizes, dtype=np.int64) - - try: - import pyarrow - - self.fnames = pyarrow.array(self.fnames) - except: - logger.debug( - "Could not create a pyarrow array. Please install pyarrow for better performance" - ) - pass - - self.set_bucket_info(num_buckets) - - def __getitem__(self, index): - import soundfile as sf - fn = self.fnames[index] - fn = fn if isinstance(self.fnames, list) else fn.as_py() - fn = self.text_compressor.decompress(fn) - path_or_fp = os.path.join(self.root_dir, fn) - _path, slice_ptr = parse_path(path_or_fp) - if len(slice_ptr) == 2: - byte_data = read_from_stored_zip(_path, slice_ptr[0], slice_ptr[1]) - assert is_sf_audio_data(byte_data) - path_or_fp = io.BytesIO(byte_data) - - wav, curr_sample_rate = sf.read(path_or_fp, dtype="float32") - - feats = torch.from_numpy(wav).float() - feats = self.postprocess(feats, curr_sample_rate) - return {"id": index, "source": feats} - - -class BinarizedAudioDataset(RawAudioDataset): - def __init__( - self, - data_dir, - split, - sample_rate, - max_sample_size=None, - min_sample_size=0, - shuffle=True, - pad=False, - normalize=False, - num_buckets=0, - compute_mask_indices=False, - **mask_compute_kwargs, - ): - super().__init__( - sample_rate=sample_rate, - max_sample_size=max_sample_size, - min_sample_size=min_sample_size, - shuffle=shuffle, - pad=pad, - normalize=normalize, - compute_mask_indices=compute_mask_indices, - **mask_compute_kwargs, - ) - - from fairseq.data import data_utils, Dictionary - - self.fnames_dict = Dictionary.load(os.path.join(data_dir, "dict.txt")) - - root_path = os.path.join(data_dir, f"{split}.root") - if os.path.exists(root_path): - with open(root_path, "r") as f: - self.root_dir = next(f).strip() - else: - self.root_dir = None - - fnames_path = os.path.join(data_dir, split) - self.fnames = data_utils.load_indexed_dataset(fnames_path, self.fnames_dict) - lengths_path = os.path.join(data_dir, f"{split}.lengths") - - with open(lengths_path, "r") as f: - for line in f: - sz = int(line.rstrip()) - assert ( - sz >= min_sample_size - ), f"Min sample size is not supported for binarized dataset, but found a sample with size {sz}" - self.sizes.append(sz) - - self.sizes = np.array(self.sizes, dtype=np.int64) - - self.set_bucket_info(num_buckets) - logger.info(f"loaded {len(self.fnames)} samples") - - def __getitem__(self, index): - import soundfile as sf - - fname = self.fnames_dict.string(self.fnames[index], separator="") - if self.root_dir: - fname = os.path.join(self.root_dir, fname) - - wav, curr_sample_rate = sf.read(fname) - feats = torch.from_numpy(wav).float() - feats = self.postprocess(feats, curr_sample_rate) - return {"id": index, "source": feats} diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/model_parallel/models/roberta/__init__.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/model_parallel/models/roberta/__init__.py deleted file mode 100644 index 117827c3e9c176477f33e3a6fd7fe19a922411a2..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/model_parallel/models/roberta/__init__.py +++ /dev/null @@ -1,6 +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 .model import * # noqa diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/hubert/simple_kmeans/README.md b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/hubert/simple_kmeans/README.md deleted file mode 100644 index cd17da3b3e6f3e39083f7a76a56ff46c3a63b929..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/hubert/simple_kmeans/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# Sharded Feature Extraction and K-means Application - -This folder contains scripts for preparing HUBERT labels from tsv files, the -steps are: -1. feature extraction -2. k-means clustering -3. k-means application - - -## Data preparation - -`*.tsv` files contains a list of audio, where each line is the root, and -following lines are the subpath for each audio: -``` - - - -... -``` - - -## Feature extraction - -### MFCC feature -Suppose the tsv file is at `${tsv_dir}/${split}.tsv`. To extract 39-D -mfcc+delta+ddelta features for the 1st iteration HUBERT training, run: -```sh -python dump_mfcc_feature.py ${tsv_dir} ${split} ${nshard} ${rank} ${feat_dir} -``` -This would shard the tsv file into `${nshard}` and extract features for the -`${rank}`-th shard, where rank is an integer in `[0, nshard-1]`. Features would -be saved at `${feat_dir}/${split}_${rank}_${nshard}.{npy,len}`. - - -### HUBERT feature -To extract features from the `${layer}`-th transformer layer of a trained -HUBERT model saved at `${ckpt_path}`, run: -```sh -python dump_hubert_feature.py ${tsv_dir} ${split} ${ckpt_path} ${layer} ${nshard} ${rank} ${feat_dir} -``` -Features would also be saved at `${feat_dir}/${split}_${rank}_${nshard}.{npy,len}`. - -- if out-of-memory, decrease the chunk size with `--max_chunk` - - -## K-means clustering -To fit a k-means model with `${n_clusters}` clusters on 10% of the `${split}` data, run -```sh -python learn_kmeans.py ${feat_dir} ${split} ${nshard} ${km_path} ${n_cluster} --percent 0.1 -``` -This saves the k-means model to `${km_path}`. - -- set `--precent -1` to use all data -- more kmeans options can be found with `-h` flag - - -## K-means application -To apply a trained k-means model `${km_path}` to obtain labels for `${split}`, run -```sh -python dump_km_label.py ${feat_dir} ${split} ${km_path} ${nshard} ${rank} ${lab_dir} -``` -This would extract labels for the `${rank}`-th shard out of `${nshard}` shards -and dump them to `${lab_dir}/${split}_${rank}_${shard}.km` - - -Finally, merge shards for `${split}` by running -```sh -for rank in $(seq 0 $((nshard - 1))); do - cat $lab_dir/${split}_${rank}_${nshard}.km -done > $lab_dir/${split}.km -``` diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/multilingual/finetune_multilingual_model.sh b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/multilingual/finetune_multilingual_model.sh deleted file mode 100644 index 25960c5dc8a02e5580b61837099770a082b4dd83..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/multilingual/finetune_multilingual_model.sh +++ /dev/null @@ -1,32 +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. - -path_2_data=$1 # which contains binarized data for each directions -lang_list=$2 # -lang_pairs=$3 #a list language pairs to train multilingual models, e.g. "en-fr,en-cs,fr-en,cs-en" -# pretrained can be an mBART pretrained model as well -pretrained_model=$4 # - - -fairseq-train "$path_2_data" \ - --encoder-normalize-before --decoder-normalize-before \ - --arch transformer --layernorm-embedding \ - --task translation_multi_simple_epoch \ - --finetune-from-model "$pretrained_model" \ - --sampling-method "temperature" \ - --sampling-temperature "1.5" \ - --encoder-langtok "src" \ - --decoder-langtok \ - --lang-dict "$lang_list" \ - --lang-pairs "$lang_pairs" \ - --criterion label_smoothed_cross_entropy --label-smoothing 0.2 \ - --optimizer adam --adam-eps 1e-06 --adam-betas '(0.9, 0.98)' \ - --lr-scheduler inverse_sqrt --lr 3e-05 --warmup-updates 2500 --max-update 40000 \ - --dropout 0.3 --attention-dropout 0.1 --weight-decay 0.0 \ - --max-tokens 1024 --update-freq 2 \ - --save-interval 1 --save-interval-updates 5000 --keep-interval-updates 10 --no-epoch-checkpoints \ - --seed 222 --log-format simple --log-interval 2 diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/dictionary.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/dictionary.py deleted file mode 100644 index d6495389f0102156f0b2dc6f892946d572911bbe..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/dictionary.py +++ /dev/null @@ -1,401 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import os -from collections import Counter -from multiprocessing import Pool - -import torch -from fairseq import utils -from fairseq.data import data_utils -from fairseq.file_chunker_utils import Chunker, find_offsets -from fairseq.file_io import PathManager -from fairseq.tokenizer import tokenize_line - - -class Dictionary: - """A mapping from symbols to consecutive integers""" - - def __init__( - self, - *, # begin keyword-only arguments - bos="", - pad="", - eos="", - unk="", - extra_special_symbols=None, - ): - self.bos_word, self.unk_word, self.pad_word, self.eos_word = bos, unk, pad, eos - self.symbols = [] - self.count = [] - self.indices = {} - self.bos_index = self.add_symbol(bos) - self.pad_index = self.add_symbol(pad) - self.eos_index = self.add_symbol(eos) - self.unk_index = self.add_symbol(unk) - if extra_special_symbols: - for s in extra_special_symbols: - self.add_symbol(s) - self.nspecial = len(self.symbols) - - def __eq__(self, other): - return self.indices == other.indices - - def __getitem__(self, idx): - if idx < len(self.symbols): - return self.symbols[idx] - return self.unk_word - - def get_count(self, idx): - return self.count[idx] - - def __len__(self): - """Returns the number of symbols in the dictionary""" - return len(self.symbols) - - def __contains__(self, sym): - return sym in self.indices - - def index(self, sym): - """Returns the index of the specified symbol""" - assert isinstance(sym, str) - if sym in self.indices: - return self.indices[sym] - return self.unk_index - - def string( - self, - tensor, - bpe_symbol=None, - escape_unk=False, - extra_symbols_to_ignore=None, - unk_string=None, - include_eos=False, - separator=" ", - ): - """Helper for converting a tensor of token indices to a string. - - Can optionally remove BPE symbols or escape words. - """ - if torch.is_tensor(tensor) and tensor.dim() == 2: - return "\n".join( - self.string( - t, - bpe_symbol, - escape_unk, - extra_symbols_to_ignore, - include_eos=include_eos, - ) - for t in tensor - ) - - extra_symbols_to_ignore = set(extra_symbols_to_ignore or []) - if not include_eos: - extra_symbols_to_ignore.add(self.eos()) - - def token_string(i): - if i == self.unk(): - if unk_string is not None: - return unk_string - else: - return self.unk_string(escape_unk) - else: - return self[i] - - if hasattr(self, "bos_index"): - extra_symbols_to_ignore.add(self.bos()) - - sent = separator.join( - token_string(i) - for i in tensor - if utils.item(i) not in extra_symbols_to_ignore - ) - - return data_utils.post_process(sent, bpe_symbol) - - def unk_string(self, escape=False): - """Return unknown string, optionally escaped as: <>""" - if escape: - return "<{}>".format(self.unk_word) - else: - return self.unk_word - - def add_symbol(self, word, n=1, overwrite=False): - """Adds a word to the dictionary""" - if word in self.indices and not overwrite: - idx = self.indices[word] - self.count[idx] = self.count[idx] + n - return idx - else: - idx = len(self.symbols) - self.indices[word] = idx - self.symbols.append(word) - self.count.append(n) - return idx - - def update(self, new_dict): - """Updates counts from new dictionary.""" - for word in new_dict.symbols: - idx2 = new_dict.indices[word] - if word in self.indices: - idx = self.indices[word] - self.count[idx] = self.count[idx] + new_dict.count[idx2] - else: - idx = len(self.symbols) - self.indices[word] = idx - self.symbols.append(word) - self.count.append(new_dict.count[idx2]) - - def finalize(self, threshold=-1, nwords=-1, padding_factor=8): - """Sort symbols by frequency in descending order, ignoring special ones. - - Args: - - threshold defines the minimum word count - - nwords defines the total number of words in the final dictionary, - including special symbols - - padding_factor can be used to pad the dictionary size to be a - multiple of 8, which is important on some hardware (e.g., Nvidia - Tensor Cores). - """ - if nwords <= 0: - nwords = len(self) - - new_indices = dict(zip(self.symbols[: self.nspecial], range(self.nspecial))) - new_symbols = self.symbols[: self.nspecial] - new_count = self.count[: self.nspecial] - - c = Counter( - dict( - sorted(zip(self.symbols[self.nspecial :], self.count[self.nspecial :])) - ) - ) - for symbol, count in c.most_common(nwords - self.nspecial): - if count >= threshold: - new_indices[symbol] = len(new_symbols) - new_symbols.append(symbol) - new_count.append(count) - else: - break - - assert len(new_symbols) == len(new_indices) - - self.count = list(new_count) - self.symbols = list(new_symbols) - self.indices = new_indices - - self.pad_to_multiple_(padding_factor) - - def pad_to_multiple_(self, padding_factor): - """Pad Dictionary size to be a multiple of *padding_factor*.""" - if padding_factor > 1: - i = 0 - while len(self) % padding_factor != 0: - symbol = "madeupword{:04d}".format(i) - self.add_symbol(symbol, n=0) - i += 1 - - def bos(self): - """Helper to get index of beginning-of-sentence symbol""" - return self.bos_index - - def pad(self): - """Helper to get index of pad symbol""" - return self.pad_index - - def eos(self): - """Helper to get index of end-of-sentence symbol""" - return self.eos_index - - def unk(self): - """Helper to get index of unk symbol""" - return self.unk_index - - @classmethod - def load(cls, f): - """Loads the dictionary from a text file with the format: - - ``` - - - ... - ``` - """ - d = cls() - d.add_from_file(f) - return d - - def add_from_file(self, f): - """ - Loads a pre-existing dictionary from a text file and adds its symbols - to this instance. - """ - if isinstance(f, str): - try: - with open(PathManager.get_local_path(f), "r", encoding="utf-8") as fd: - self.add_from_file(fd) - except FileNotFoundError as fnfe: - raise fnfe - except UnicodeError: - raise Exception( - "Incorrect encoding detected in {}, please " - "rebuild the dataset".format(f) - ) - return - - lines = f.readlines() - indices_start_line = self._load_meta(lines) - - for line in lines[indices_start_line:]: - try: - line, field = line.rstrip().rsplit(" ", 1) - if field == "#fairseq:overwrite": - overwrite = True - line, field = line.rsplit(" ", 1) - else: - overwrite = False - count = int(field) - word = line - if word in self and not overwrite: - raise RuntimeError( - "Duplicate word found when loading Dictionary: '{}'. " - "Duplicate words can overwrite earlier ones by adding the " - "#fairseq:overwrite flag at the end of the corresponding row " - "in the dictionary file. If using the Camembert model, please " - "download an updated copy of the model file.".format(word) - ) - self.add_symbol(word, n=count, overwrite=overwrite) - except ValueError: - raise ValueError( - f"Incorrect dictionary format, expected ' [flags]': \"{line}\"" - ) - - def _save(self, f, kv_iterator): - if isinstance(f, str): - PathManager.mkdirs(os.path.dirname(f)) - with PathManager.open(f, "w", encoding="utf-8") as fd: - return self.save(fd) - for k, v in kv_iterator: - print("{} {}".format(k, v), file=f) - - def _get_meta(self): - return [], [] - - def _load_meta(self, lines): - return 0 - - def save(self, f): - """Stores dictionary into a text file""" - ex_keys, ex_vals = self._get_meta() - self._save( - f, - zip( - ex_keys + self.symbols[self.nspecial :], - ex_vals + self.count[self.nspecial :], - ), - ) - - def dummy_sentence(self, length): - t = torch.Tensor(length).uniform_(self.nspecial + 1, len(self)).long() - t[-1] = self.eos() - return t - - def encode_line( - self, - line, - line_tokenizer=tokenize_line, - add_if_not_exist=True, - consumer=None, - append_eos=True, - reverse_order=False, - ) -> torch.IntTensor: - words = line_tokenizer(line) - if reverse_order: - words = list(reversed(words)) - nwords = len(words) - ids = torch.IntTensor(nwords + 1 if append_eos else nwords) - - for i, word in enumerate(words): - if add_if_not_exist: - idx = self.add_symbol(word) - else: - idx = self.index(word) - if consumer is not None: - consumer(word, idx) - ids[i] = idx - if append_eos: - ids[nwords] = self.eos_index - return ids - - @staticmethod - def _add_file_to_dictionary_single_worker( - filename, - tokenize, - eos_word, - start_offset, - end_offset, - ): - counter = Counter() - with Chunker(filename, start_offset, end_offset) as line_iterator: - for line in line_iterator: - for word in tokenize(line): - counter.update([word]) - counter.update([eos_word]) - return counter - - @staticmethod - def add_file_to_dictionary(filename, dict, tokenize, num_workers): - def merge_result(counter): - for w, c in sorted(counter.items()): - dict.add_symbol(w, c) - - local_file = PathManager.get_local_path(filename) - offsets = find_offsets(local_file, num_workers) - if num_workers > 1: - chunks = zip(offsets, offsets[1:]) - pool = Pool(processes=num_workers) - results = [] - for (start_offset, end_offset) in chunks: - results.append( - pool.apply_async( - Dictionary._add_file_to_dictionary_single_worker, - ( - local_file, - tokenize, - dict.eos_word, - start_offset, - end_offset, - ), - ) - ) - pool.close() - pool.join() - for r in results: - merge_result(r.get()) - else: - merge_result( - Dictionary._add_file_to_dictionary_single_worker( - local_file, tokenize, dict.eos_word, offsets[0], offsets[1] - ) - ) - - -class TruncatedDictionary(object): - def __init__(self, wrapped_dict, length): - self.__class__ = type( - wrapped_dict.__class__.__name__, - (self.__class__, wrapped_dict.__class__), - {}, - ) - self.__dict__ = wrapped_dict.__dict__ - self.wrapped_dict = wrapped_dict - self.length = min(len(self.wrapped_dict), length) - - def __len__(self): - return self.length - - def __getitem__(self, i): - if i < self.length: - return self.wrapped_dict[i] - return self.wrapped_dict.unk() diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/wav2vec/scripts/binarize_manifest.sh b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/wav2vec/scripts/binarize_manifest.sh deleted file mode 100644 index 6f201bdb524fad51a69d8c45889eaa1578efc62d..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/wav2vec/scripts/binarize_manifest.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash - -# usage: bash binarize_manifest - -DEST_DIR=$1 -TRAIN_SPLIT=$2 -VALID_SPLIT=$3 -FAIRSEQ_ROOT=$4 - -mkdir -p $DEST_DIR - -# split file path and lengths into separate files -cut -f1 $TRAIN_SPLIT.tsv > $DEST_DIR/train_fnames.txt -cut -f1 $VALID_SPLIT.tsv > $DEST_DIR/valid_fnames.txt -cut -f2 $TRAIN_SPLIT.tsv > $DEST_DIR/train.lengths -cut -f2 $VALID_SPLIT.tsv > $DEST_DIR/valid.lengths - -# copy root directory -head -1 $TRAIN_SPLIT.tsv > $DEST_DIR/train.root -head -1 $VALID_SPLIT.tsv > $DEST_DIR/valid.root - -# remove root directory -sed -i '1d' $DEST_DIR/train_fnames.txt -sed -i '1d' $DEST_DIR/valid_fnames.txt -sed -i '1d' $DEST_DIR/train.lengths -sed -i '1d' $DEST_DIR/valid.lengths - -# insert spaces between characters -sed -i -e 's/\(.\)/\1 /g' $DEST_DIR/train_fnames.txt -sed -i -e 's/\(.\)/\1 /g' $DEST_DIR/valid_fnames.txt - -# run preprocessor -PYTHONPATH=$FAIRSEQ_ROOT python $FAIRSEQ_ROOT/fairseq_cli/preprocess.py --dataset-impl mmap --trainpref $DEST_DIR/train_fnames.txt --validpref $DEST_DIR/valid_fnames.txt --workers 60 --only-source --destdir $DEST_DIR diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/__init__.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/__init__.py deleted file mode 100644 index dc9fd1886d55756b5bdfeccf1ad329bd419a706e..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/__init__.py +++ /dev/null @@ -1,44 +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. -"""isort:skip_file""" - -import os -import sys - -try: - from .version import __version__ # noqa -except ImportError: - version_txt = os.path.join(os.path.dirname(__file__), "version.txt") - with open(version_txt) as f: - __version__ = f.read().strip() - -__all__ = ["pdb"] - -# backwards compatibility to support `from fairseq.X import Y` -from fairseq.distributed import utils as distributed_utils -from fairseq.logging import meters, metrics, progress_bar # noqa - -sys.modules["fairseq.distributed_utils"] = distributed_utils -sys.modules["fairseq.meters"] = meters -sys.modules["fairseq.metrics"] = metrics -sys.modules["fairseq.progress_bar"] = progress_bar - -# initialize hydra -from fairseq.dataclass.initialize import hydra_init -hydra_init() - -import fairseq.criterions # noqa -import fairseq.distributed # noqa -import fairseq.models # noqa -import fairseq.modules # noqa -import fairseq.optim # noqa -import fairseq.optim.lr_scheduler # noqa -import fairseq.pdb # noqa -import fairseq.scoring # noqa -import fairseq.tasks # noqa -import fairseq.token_generation_constraints # noqa - -import fairseq.benchmark # noqa -import fairseq.model_parallel # noqa diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/modules/lightconv_layer/setup.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/modules/lightconv_layer/setup.py deleted file mode 100644 index 052635be79b466d0ad56cf5cf607bd10c2297ecf..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/modules/lightconv_layer/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from setuptools import setup -from torch.utils.cpp_extension import BuildExtension, CUDAExtension - - -setup( - name="lightconv_layer", - ext_modules=[ - CUDAExtension( - "lightconv_cuda", - [ - "lightconv_cuda.cpp", - "lightconv_cuda_kernel.cu", - ], - ), - ], - cmdclass={"build_ext": BuildExtension}, -) diff --git a/spaces/OIUGLK/bingo/src/components/chat-suggestions.tsx b/spaces/OIUGLK/bingo/src/components/chat-suggestions.tsx deleted file mode 100644 index 00c2fee295c9e010946046eb71705a5e131f7a5a..0000000000000000000000000000000000000000 --- a/spaces/OIUGLK/bingo/src/components/chat-suggestions.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import React, { useMemo } from 'react' -import Image from 'next/image' -import HelpIcon from '@/assets/images/help.svg' -import { SuggestedResponse } from '@/lib/bots/bing/types' -import { useBing } from '@/lib/hooks/use-bing' -import { atom, useAtom } from 'jotai' - -type Suggestions = SuggestedResponse[] -const helpSuggestions = ['为什么不回应某些主题', '告诉我更多关于必应的资迅', '必应如何使用 AI?'].map((text) => ({ text })) -const suggestionsAtom = atom([]) - -type ChatSuggestionsProps = React.ComponentProps<'div'> & Pick, 'setInput'> & { suggestions?: Suggestions } - -export function ChatSuggestions({ setInput, suggestions = [] }: ChatSuggestionsProps) { - const [currentSuggestions, setSuggestions] = useAtom(suggestionsAtom) - const toggleSuggestions = (() => { - if (currentSuggestions === helpSuggestions) { - setSuggestions(suggestions) - } else { - setSuggestions(helpSuggestions) - } - }) - - useMemo(() => { - setSuggestions(suggestions) - window.scrollBy(0, 2000) - }, [suggestions.length]) - - return currentSuggestions?.length ? ( -
-
- - { - currentSuggestions.map(suggestion => ( - - )) - } -
-
- ) : null -} diff --git a/spaces/Open-Orca/LlongOrca-13B-16k/README.md b/spaces/Open-Orca/LlongOrca-13B-16k/README.md deleted file mode 100644 index 8aaa53a4f8729894da54a2f2dc5a51eba7aee90f..0000000000000000000000000000000000000000 --- a/spaces/Open-Orca/LlongOrca-13B-16k/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: LlongOrca-13B-16k -emoji: 🐳 -colorFrom: red -colorTo: purple -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false -duplicated_from: Open-Orca/LlongOrca-7B-16k ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/tests/layers/test_roi_align_rotated.py b/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/tests/layers/test_roi_align_rotated.py deleted file mode 100644 index 7323d7d5a86816f337571221313c428238c439f4..0000000000000000000000000000000000000000 --- a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/tests/layers/test_roi_align_rotated.py +++ /dev/null @@ -1,176 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import logging -import unittest -import cv2 -import torch -from torch.autograd import Variable, gradcheck - -from detectron2.layers.roi_align import ROIAlign -from detectron2.layers.roi_align_rotated import ROIAlignRotated - -logger = logging.getLogger(__name__) - - -class ROIAlignRotatedTest(unittest.TestCase): - def _box_to_rotated_box(self, box, angle): - return [ - (box[0] + box[2]) / 2.0, - (box[1] + box[3]) / 2.0, - box[2] - box[0], - box[3] - box[1], - angle, - ] - - def _rot90(self, img, num): - num = num % 4 # note: -1 % 4 == 3 - for _ in range(num): - img = img.transpose(0, 1).flip(0) - return img - - def test_forward_output_0_90_180_270(self): - for i in range(4): - # i = 0, 1, 2, 3 corresponding to 0, 90, 180, 270 degrees - img = torch.arange(25, dtype=torch.float32).reshape(5, 5) - """ - 0 1 2 3 4 - 5 6 7 8 9 - 10 11 12 13 14 - 15 16 17 18 19 - 20 21 22 23 24 - """ - box = [1, 1, 3, 3] - rotated_box = self._box_to_rotated_box(box=box, angle=90 * i) - - result = self._simple_roi_align_rotated(img=img, box=rotated_box, resolution=(4, 4)) - - # Here's an explanation for 0 degree case: - # point 0 in the original input lies at [0.5, 0.5] - # (the center of bin [0, 1] x [0, 1]) - # point 1 in the original input lies at [1.5, 0.5], etc. - # since the resolution is (4, 4) that divides [1, 3] x [1, 3] - # into 4 x 4 equal bins, - # the top-left bin is [1, 1.5] x [1, 1.5], and its center - # (1.25, 1.25) lies at the 3/4 position - # between point 0 and point 1, point 5 and point 6, - # point 0 and point 5, point 1 and point 6, so it can be calculated as - # 0.25*(0*0.25+1*0.75)+(5*0.25+6*0.75)*0.75 = 4.5 - result_expected = torch.tensor( - [ - [4.5, 5.0, 5.5, 6.0], - [7.0, 7.5, 8.0, 8.5], - [9.5, 10.0, 10.5, 11.0], - [12.0, 12.5, 13.0, 13.5], - ] - ) - # This is also an upsampled version of [[6, 7], [11, 12]] - - # When the box is rotated by 90 degrees CCW, - # the result would be rotated by 90 degrees CW, thus it's -i here - result_expected = self._rot90(result_expected, -i) - - assert torch.allclose(result, result_expected) - - def test_resize(self): - H, W = 30, 30 - input = torch.rand(H, W) * 100 - box = [10, 10, 20, 20] - rotated_box = self._box_to_rotated_box(box, angle=0) - output = self._simple_roi_align_rotated(img=input, box=rotated_box, resolution=(5, 5)) - - input2x = cv2.resize(input.numpy(), (W // 2, H // 2), interpolation=cv2.INTER_LINEAR) - input2x = torch.from_numpy(input2x) - box2x = [x / 2 for x in box] - rotated_box2x = self._box_to_rotated_box(box2x, angle=0) - output2x = self._simple_roi_align_rotated(img=input2x, box=rotated_box2x, resolution=(5, 5)) - assert torch.allclose(output2x, output) - - def _simple_roi_align_rotated(self, img, box, resolution): - """ - RoiAlignRotated with scale 1.0 and 0 sample ratio. - """ - op = ROIAlignRotated(output_size=resolution, spatial_scale=1.0, sampling_ratio=0) - input = img[None, None, :, :] - - rois = [0] + list(box) - rois = torch.tensor(rois, dtype=torch.float32)[None, :] - result_cpu = op.forward(input, rois) - if torch.cuda.is_available(): - result_cuda = op.forward(input.cuda(), rois.cuda()) - assert torch.allclose(result_cpu, result_cuda.cpu()) - return result_cpu[0, 0] - - def test_empty_box(self): - img = torch.rand(5, 5) - out = self._simple_roi_align_rotated(img, [2, 3, 0, 0, 0], (7, 7)) - self.assertTrue((out == 0).all()) - - def test_roi_align_rotated_gradcheck_cpu(self): - dtype = torch.float64 - device = torch.device("cpu") - roi_align_rotated_op = ROIAlignRotated( - output_size=(5, 5), spatial_scale=0.5, sampling_ratio=1 - ).to(dtype=dtype, device=device) - x = torch.rand(1, 1, 10, 10, dtype=dtype, device=device, requires_grad=True) - # roi format is (batch index, x_center, y_center, width, height, angle) - rois = torch.tensor( - [[0, 4.5, 4.5, 9, 9, 0], [0, 2, 7, 4, 4, 0], [0, 7, 7, 4, 4, 0]], - dtype=dtype, - device=device, - ) - - def func(input): - return roi_align_rotated_op(input, rois) - - assert gradcheck(func, (x,)), "gradcheck failed for RoIAlignRotated CPU" - assert gradcheck(func, (x.transpose(2, 3),)), "gradcheck failed for RoIAlignRotated CPU" - - @unittest.skipIf(not torch.cuda.is_available(), "CUDA not available") - def test_roi_align_rotated_gradient_cuda(self): - """ - Compute gradients for ROIAlignRotated with multiple bounding boxes on the GPU, - and compare the result with ROIAlign - """ - # torch.manual_seed(123) - dtype = torch.float64 - device = torch.device("cuda") - pool_h, pool_w = (5, 5) - - roi_align = ROIAlign(output_size=(pool_h, pool_w), spatial_scale=1, sampling_ratio=2).to( - device=device - ) - - roi_align_rotated = ROIAlignRotated( - output_size=(pool_h, pool_w), spatial_scale=1, sampling_ratio=2 - ).to(device=device) - - x = torch.rand(1, 1, 10, 10, dtype=dtype, device=device, requires_grad=True) - # x_rotated = x.clone() won't work (will lead to grad_fun=CloneBackward)! - x_rotated = Variable(x.data.clone(), requires_grad=True) - - # roi_rotated format is (batch index, x_center, y_center, width, height, angle) - rois_rotated = torch.tensor( - [[0, 4.5, 4.5, 9, 9, 0], [0, 2, 7, 4, 4, 0], [0, 7, 7, 4, 4, 0]], - dtype=dtype, - device=device, - ) - - y_rotated = roi_align_rotated(x_rotated, rois_rotated) - s_rotated = y_rotated.sum() - s_rotated.backward() - - # roi format is (batch index, x1, y1, x2, y2) - rois = torch.tensor( - [[0, 0, 0, 9, 9], [0, 0, 5, 4, 9], [0, 5, 5, 9, 9]], dtype=dtype, device=device - ) - - y = roi_align(x, rois) - s = y.sum() - s.backward() - - assert torch.allclose( - x.grad, x_rotated.grad - ), "gradients for ROIAlign and ROIAlignRotated mismatch on CUDA" - - -if __name__ == "__main__": - unittest.main() diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/inpainting_src/ldm_inpainting/ldm/modules/distributions/distributions.py b/spaces/OpenGVLab/InternGPT/iGPT/models/inpainting_src/ldm_inpainting/ldm/modules/distributions/distributions.py deleted file mode 100644 index f2b8ef901130efc171aa69742ca0244d94d3f2e9..0000000000000000000000000000000000000000 --- a/spaces/OpenGVLab/InternGPT/iGPT/models/inpainting_src/ldm_inpainting/ldm/modules/distributions/distributions.py +++ /dev/null @@ -1,92 +0,0 @@ -import torch -import numpy as np - - -class AbstractDistribution: - def sample(self): - raise NotImplementedError() - - def mode(self): - raise NotImplementedError() - - -class DiracDistribution(AbstractDistribution): - def __init__(self, value): - self.value = value - - def sample(self): - return self.value - - def mode(self): - return self.value - - -class DiagonalGaussianDistribution(object): - def __init__(self, parameters, deterministic=False): - self.parameters = parameters - self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) - self.logvar = torch.clamp(self.logvar, -30.0, 20.0) - self.deterministic = deterministic - self.std = torch.exp(0.5 * self.logvar) - self.var = torch.exp(self.logvar) - if self.deterministic: - self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device) - - def sample(self): - x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device) - return x - - def kl(self, other=None): - if self.deterministic: - return torch.Tensor([0.]) - else: - if other is None: - return 0.5 * torch.sum(torch.pow(self.mean, 2) - + self.var - 1.0 - self.logvar, - dim=[1, 2, 3]) - else: - return 0.5 * torch.sum( - torch.pow(self.mean - other.mean, 2) / other.var - + self.var / other.var - 1.0 - self.logvar + other.logvar, - dim=[1, 2, 3]) - - def nll(self, sample, dims=[1,2,3]): - if self.deterministic: - return torch.Tensor([0.]) - logtwopi = np.log(2.0 * np.pi) - return 0.5 * torch.sum( - logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, - dim=dims) - - def mode(self): - return self.mean - - -def normal_kl(mean1, logvar1, mean2, logvar2): - """ - source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12 - Compute the KL divergence between two gaussians. - Shapes are automatically broadcasted, so batches can be compared to - scalars, among other use cases. - """ - tensor = None - for obj in (mean1, logvar1, mean2, logvar2): - if isinstance(obj, torch.Tensor): - tensor = obj - break - assert tensor is not None, "at least one argument must be a Tensor" - - # Force variances to be Tensors. Broadcasting helps convert scalars to - # Tensors, but it does not work for torch.exp(). - logvar1, logvar2 = [ - x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor) - for x in (logvar1, logvar2) - ] - - return 0.5 * ( - -1.0 - + logvar2 - - logvar1 - + torch.exp(logvar1 - logvar2) - + ((mean1 - mean2) ** 2) * torch.exp(-logvar2) - ) diff --git a/spaces/PAIR/PAIR-Diffusion/annotator/OneFormer/oneformer/modeling/__init__.py b/spaces/PAIR/PAIR-Diffusion/annotator/OneFormer/oneformer/modeling/__init__.py deleted file mode 100644 index 29e09f4e888e0c73c49d1db7d10ef6a82ba79488..0000000000000000000000000000000000000000 --- a/spaces/PAIR/PAIR-Diffusion/annotator/OneFormer/oneformer/modeling/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .backbone.swin import D2SwinTransformer -# from .backbone.dinat import D2DiNAT -from .backbone.convnext import D2ConvNeXt -from .pixel_decoder.fpn import BasePixelDecoder -from .pixel_decoder.msdeformattn import MSDeformAttnPixelDecoder -from .meta_arch.oneformer_head import OneFormerHead diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/utils/misc.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/utils/misc.py deleted file mode 100644 index 2c58d0d7fee9fe3d4519270ad8c1e998d0d8a18c..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/utils/misc.py +++ /dev/null @@ -1,377 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import collections.abc -import functools -import itertools -import subprocess -import warnings -from collections import abc -from importlib import import_module -from inspect import getfullargspec -from itertools import repeat - - -# From PyTorch internals -def _ntuple(n): - - def parse(x): - if isinstance(x, collections.abc.Iterable): - return x - return tuple(repeat(x, n)) - - return parse - - -to_1tuple = _ntuple(1) -to_2tuple = _ntuple(2) -to_3tuple = _ntuple(3) -to_4tuple = _ntuple(4) -to_ntuple = _ntuple - - -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 import_modules_from_strings(imports, allow_failed_imports=False): - """Import modules from the given list of strings. - - Args: - imports (list | str | None): The given module names to be imported. - allow_failed_imports (bool): If True, the failed imports will return - None. Otherwise, an ImportError is raise. Default: False. - - Returns: - list[module] | module | None: The imported modules. - - Examples: - >>> osp, sys = import_modules_from_strings( - ... ['os.path', 'sys']) - >>> import os.path as osp_ - >>> import sys as sys_ - >>> assert osp == osp_ - >>> assert sys == sys_ - """ - if not imports: - return - single_import = False - if isinstance(imports, str): - single_import = True - imports = [imports] - if not isinstance(imports, list): - raise TypeError( - f'custom_imports must be a list but got type {type(imports)}') - imported = [] - for imp in imports: - if not isinstance(imp, str): - raise TypeError( - f'{imp} is of type {type(imp)} and cannot be imported.') - try: - imported_tmp = import_module(imp) - except ImportError: - if allow_failed_imports: - warnings.warn(f'{imp} failed to import and is ignored.', - UserWarning) - imported_tmp = None - else: - raise ImportError - imported.append(imported_tmp) - if single_import: - imported = imported[0] - return imported - - -def iter_cast(inputs, dst_type, return_type=None): - """Cast elements of an iterable object into some type. - - Args: - inputs (Iterable): The input object. - dst_type (type): Destination type. - return_type (type, optional): If specified, the output object will be - converted to this type, otherwise an iterator. - - Returns: - iterator or specified type: The converted object. - """ - if not isinstance(inputs, abc.Iterable): - raise TypeError('inputs must be an iterable object') - if not isinstance(dst_type, type): - raise TypeError('"dst_type" must be a valid type') - - out_iterable = map(dst_type, inputs) - - if return_type is None: - return out_iterable - else: - return return_type(out_iterable) - - -def list_cast(inputs, dst_type): - """Cast elements of an iterable object into a list of some type. - - A partial method of :func:`iter_cast`. - """ - return iter_cast(inputs, dst_type, return_type=list) - - -def tuple_cast(inputs, dst_type): - """Cast elements of an iterable object into a tuple of some type. - - A partial method of :func:`iter_cast`. - """ - return iter_cast(inputs, dst_type, return_type=tuple) - - -def is_seq_of(seq, expected_type, seq_type=None): - """Check whether it is a sequence of some type. - - Args: - seq (Sequence): The sequence to be checked. - expected_type (type): Expected type of sequence items. - seq_type (type, optional): Expected sequence type. - - Returns: - bool: Whether the sequence is valid. - """ - if seq_type is None: - exp_seq_type = abc.Sequence - else: - assert isinstance(seq_type, type) - exp_seq_type = seq_type - if not isinstance(seq, exp_seq_type): - return False - for item in seq: - if not isinstance(item, expected_type): - return False - return True - - -def is_list_of(seq, expected_type): - """Check whether it is a list of some type. - - A partial method of :func:`is_seq_of`. - """ - return is_seq_of(seq, expected_type, seq_type=list) - - -def is_tuple_of(seq, expected_type): - """Check whether it is a tuple of some type. - - A partial method of :func:`is_seq_of`. - """ - return is_seq_of(seq, expected_type, seq_type=tuple) - - -def slice_list(in_list, lens): - """Slice a list into several sub lists by a list of given length. - - Args: - in_list (list): The list to be sliced. - lens(int or list): The expected length of each out list. - - Returns: - list: A list of sliced list. - """ - if isinstance(lens, int): - assert len(in_list) % lens == 0 - lens = [lens] * int(len(in_list) / lens) - if not isinstance(lens, list): - raise TypeError('"indices" must be an integer or a list of integers') - elif sum(lens) != len(in_list): - raise ValueError('sum of lens and list length does not ' - f'match: {sum(lens)} != {len(in_list)}') - out_list = [] - idx = 0 - for i in range(len(lens)): - out_list.append(in_list[idx:idx + lens[i]]) - idx += lens[i] - return out_list - - -def concat_list(in_list): - """Concatenate a list of list into a single list. - - Args: - in_list (list): The list of list to be merged. - - Returns: - list: The concatenated flat list. - """ - return list(itertools.chain(*in_list)) - - -def check_prerequisites( - prerequisites, - checker, - msg_tmpl='Prerequisites "{}" are required in method "{}" but not ' - 'found, please install them first.'): # yapf: disable - """A decorator factory to check if prerequisites are satisfied. - - Args: - prerequisites (str of list[str]): Prerequisites to be checked. - checker (callable): The checker method that returns True if a - prerequisite is meet, False otherwise. - msg_tmpl (str): The message template with two variables. - - Returns: - decorator: A specific decorator. - """ - - def wrap(func): - - @functools.wraps(func) - def wrapped_func(*args, **kwargs): - requirements = [prerequisites] if isinstance( - prerequisites, str) else prerequisites - missing = [] - for item in requirements: - if not checker(item): - missing.append(item) - if missing: - print(msg_tmpl.format(', '.join(missing), func.__name__)) - raise RuntimeError('Prerequisites not meet.') - else: - return func(*args, **kwargs) - - return wrapped_func - - return wrap - - -def _check_py_package(package): - try: - import_module(package) - except ImportError: - return False - else: - return True - - -def _check_executable(cmd): - if subprocess.call(f'which {cmd}', shell=True) != 0: - return False - else: - return True - - -def requires_package(prerequisites): - """A decorator to check if some python packages are installed. - - Example: - >>> @requires_package('numpy') - >>> func(arg1, args): - >>> return numpy.zeros(1) - array([0.]) - >>> @requires_package(['numpy', 'non_package']) - >>> func(arg1, args): - >>> return numpy.zeros(1) - ImportError - """ - return check_prerequisites(prerequisites, checker=_check_py_package) - - -def requires_executable(prerequisites): - """A decorator to check if some executable files are installed. - - Example: - >>> @requires_executable('ffmpeg') - >>> func(arg1, args): - >>> print(1) - 1 - """ - return check_prerequisites(prerequisites, checker=_check_executable) - - -def deprecated_api_warning(name_dict, cls_name=None): - """A decorator to check if some arguments are deprecate and try to replace - deprecate src_arg_name to dst_arg_name. - - Args: - name_dict(dict): - key (str): Deprecate argument names. - val (str): Expected argument names. - - Returns: - func: New function. - """ - - def api_warning_wrapper(old_func): - - @functools.wraps(old_func) - def new_func(*args, **kwargs): - # get the arg spec of the decorated method - args_info = getfullargspec(old_func) - # get name of the function - func_name = old_func.__name__ - if cls_name is not None: - func_name = f'{cls_name}.{func_name}' - if args: - arg_names = args_info.args[:len(args)] - for src_arg_name, dst_arg_name in name_dict.items(): - if src_arg_name in arg_names: - warnings.warn( - f'"{src_arg_name}" is deprecated in ' - f'`{func_name}`, please use "{dst_arg_name}" ' - 'instead') - arg_names[arg_names.index(src_arg_name)] = dst_arg_name - if kwargs: - for src_arg_name, dst_arg_name in name_dict.items(): - if src_arg_name in kwargs: - - assert dst_arg_name not in kwargs, ( - f'The expected behavior is to replace ' - f'the deprecated key `{src_arg_name}` to ' - f'new key `{dst_arg_name}`, but got them ' - f'in the arguments at the same time, which ' - f'is confusing. `{src_arg_name} will be ' - f'deprecated in the future, please ' - f'use `{dst_arg_name}` instead.') - - warnings.warn( - f'"{src_arg_name}" is deprecated in ' - f'`{func_name}`, please use "{dst_arg_name}" ' - 'instead') - kwargs[dst_arg_name] = kwargs.pop(src_arg_name) - - # apply converted arguments to the decorated method - output = old_func(*args, **kwargs) - return output - - return new_func - - return api_warning_wrapper - - -def is_method_overridden(method, base_class, derived_class): - """Check if a method of base class is overridden in derived class. - - Args: - method (str): the method name to check. - base_class (type): the class of the base class. - derived_class (type | Any): the class or instance of the derived class. - """ - assert isinstance(base_class, type), \ - "base_class doesn't accept instance, Please pass class instead." - - if not isinstance(derived_class, type): - derived_class = derived_class.__class__ - - base_method = getattr(base_class, method) - derived_method = getattr(derived_class, method) - return derived_method != base_method - - -def has_method(obj: object, method: str) -> bool: - """Check whether the object has a method. - - Args: - method (str): The method name to check. - obj (object): The object to check. - - Returns: - bool: True if the object has the method else False. - """ - return hasattr(obj, method) and callable(getattr(obj, method)) diff --git a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/web/http.go b/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/web/http.go deleted file mode 100644 index 5bbf98b07140775e773c8ab85fbf2349a5c2ed5b..0000000000000000000000000000000000000000 Binary files a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/web/http.go and /dev/null differ diff --git a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/data/datasets/imagenet.py b/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/data/datasets/imagenet.py deleted file mode 100644 index 5ecab0d9a52ad8351bfc92d8877d217cb583a0e6..0000000000000000000000000000000000000000 --- a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/data/datasets/imagenet.py +++ /dev/null @@ -1,63 +0,0 @@ -import os -import os.path -import json -from PIL import Image - -import torch.utils.data as data - -def pil_loader(path): - # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) - with open(path, 'rb') as f: - img = Image.open(f) - return img.convert('RGB') - -class ImageNet(data.Dataset): - """ ImageNet - - Args: - root (string): Root directory where images are downloaded to. - annFile (string): Path to json annotation file. - transform (callable, optional): A function/transform that takes in an PIL image - and returns a transformed version. E.g, ``transforms.ToTensor`` - """ - - def __init__(self, ann_file, root, remove_images_without_annotations=None, transforms=None): - - - self.root = root - self.transform = transforms - - meta_file = os.path.join(root, ann_file) - assert os.path.exists(meta_file), 'meta file %s under root %s not found' % (os.path.basename(meta_file), root) - - with open(meta_file, 'r') as f: - meta = json.load(f) - - self.classes = meta['classes'] - self.class_to_idx = meta['class_to_idx'] - self.samples = meta['samples'] - self.num_sample = len(self.samples) - self.allsamples = self.samples - - def select_class(self, cls): - new_samples = [sample for sample in self.allsamples if sample[-1] in cls] - self.samples = new_samples - self.num_sample = len(self.samples) - - def __getitem__(self, index): - """ - Args: - index (int): Index - - Returns: - tuple: (sample, target) where target is class_index of the target class. - """ - img_path, target = self.samples[index] - sample = pil_loader(self.root + '/' + img_path) - if self.transform is not None: - sample = self.transform(sample) - - return sample, target, index - - def __len__(self): - return len(self.samples) \ No newline at end of file diff --git a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/modeling/rpn/retina.py b/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/modeling/rpn/retina.py deleted file mode 100644 index 7c7f6a1b4b2190ee6dc41df175efe67399ddf73b..0000000000000000000000000000000000000000 --- a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/modeling/rpn/retina.py +++ /dev/null @@ -1,156 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -import math -import torch -import torch.nn.functional as F -from torch import nn - -from maskrcnn_benchmark.modeling import registry -from maskrcnn_benchmark.modeling.box_coder import BoxCoder -from .loss import make_focal_loss_evaluator -from .anchor_generator import make_anchor_generator_complex -from .inference import make_retina_postprocessor - - -@registry.RPN_HEADS.register("RetinaNetHead") -class RetinaNetHead(torch.nn.Module): - """ - Adds a RetinNet head with classification and regression heads - """ - - def __init__(self, cfg): - """ - Arguments: - in_channels (int): number of channels of the input feature - num_anchors (int): number of anchors to be predicted - """ - super(RetinaNetHead, self).__init__() - # TODO: Implement the sigmoid version first. - num_classes = cfg.MODEL.RETINANET.NUM_CLASSES - 1 - in_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS - if cfg.MODEL.RPN.USE_FPN: - num_anchors = len(cfg.MODEL.RPN.ASPECT_RATIOS) * cfg.MODEL.RPN.SCALES_PER_OCTAVE - else: - num_anchors = len(cfg.MODEL.RPN.ASPECT_RATIOS) * len(cfg.MODEL.RPN.ANCHOR_SIZES) - - cls_tower = [] - bbox_tower = [] - for i in range(cfg.MODEL.RETINANET.NUM_CONVS): - cls_tower.append( - nn.Conv2d( - in_channels, - in_channels, - kernel_size=3, - stride=1, - padding=1 - ) - ) - cls_tower.append(nn.ReLU()) - bbox_tower.append( - nn.Conv2d( - in_channels, - in_channels, - kernel_size=3, - stride=1, - padding=1 - ) - ) - bbox_tower.append(nn.ReLU()) - - self.add_module('cls_tower', nn.Sequential(*cls_tower)) - self.add_module('bbox_tower', nn.Sequential(*bbox_tower)) - self.cls_logits = nn.Conv2d( - in_channels, num_anchors * num_classes, kernel_size=3, stride=1, - padding=1 - ) - self.bbox_pred = nn.Conv2d( - in_channels, num_anchors * 4, kernel_size=3, stride=1, - padding=1 - ) - - # Initialization - for modules in [self.cls_tower, self.bbox_tower, self.cls_logits, - self.bbox_pred]: - for l in modules.modules(): - if isinstance(l, nn.Conv2d): - torch.nn.init.normal_(l.weight, std=0.01) - torch.nn.init.constant_(l.bias, 0) - - - # retinanet_bias_init - prior_prob = cfg.MODEL.RETINANET.PRIOR_PROB - bias_value = -math.log((1 - prior_prob) / prior_prob) - torch.nn.init.constant_(self.cls_logits.bias, bias_value) - - def forward(self, x): - logits = [] - bbox_reg = [] - for feature in x: - logits.append(self.cls_logits(self.cls_tower(feature))) - bbox_reg.append(self.bbox_pred(self.bbox_tower(feature))) - return logits, bbox_reg - - -class RetinaNetModule(torch.nn.Module): - """ - Module for RetinaNet computation. Takes feature maps from the backbone and - RetinaNet outputs and losses. Only Test on FPN now. - """ - - def __init__(self, cfg): - super(RetinaNetModule, self).__init__() - - self.cfg = cfg.clone() - - anchor_generator = make_anchor_generator_complex(cfg) - head = RetinaNetHead(cfg) - - box_coder = BoxCoder(weights=(10., 10., 5., 5.)) - - box_selector_test = make_retina_postprocessor(cfg, box_coder, is_train=False) - - loss_evaluator = make_focal_loss_evaluator(cfg, box_coder) - - self.anchor_generator = anchor_generator - self.head = head - self.box_selector_test = box_selector_test - self.loss_evaluator = loss_evaluator - - def forward(self, images, features, targets=None): - """ - Arguments: - images (ImageList): images for which we want to compute the predictions - features (list[Tensor]): features computed from the images that are - used for computing the predictions. Each tensor in the list - correspond to different feature levels - targets (list[BoxList): ground-truth boxes present in the image (optional) - - Returns: - boxes (list[BoxList]): the predicted boxes from the RPN, one BoxList per - image. - losses (dict[Tensor]): the losses for the model during training. During - testing, it is an empty dict. - """ - box_cls, box_regression = self.head(features) - anchors = self.anchor_generator(images, features) - - if self.training: - return self._forward_train(anchors, box_cls, box_regression, targets) - else: - return self._forward_test(anchors, box_cls, box_regression) - - def _forward_train(self, anchors, box_cls, box_regression, targets): - - loss_box_cls, loss_box_reg = self.loss_evaluator( - anchors, box_cls, box_regression, targets - ) - losses = { - "loss_retina_cls": loss_box_cls, - "loss_retina_reg": loss_box_reg, - } - return anchors, losses - - def _forward_test(self, anchors, box_cls, box_regression): - boxes = self.box_selector_test(anchors, box_cls, box_regression) - return boxes, {} - - diff --git a/spaces/PixelistStudio/3dart-Models/README.md b/spaces/PixelistStudio/3dart-Models/README.md deleted file mode 100644 index 7ff07b4425c10df38c41f7cd3ad9b54dac599ad5..0000000000000000000000000000000000000000 --- a/spaces/PixelistStudio/3dart-Models/README.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Pixelist Ai Photo Generation -emoji: 📚 -colorFrom: gray -colorTo: gray -sdk: gradio -sdk_version: 3.15.0 -app_file: app.py ---- \ No newline at end of file diff --git a/spaces/Plachta/VITS-Umamusume-voice-synthesizer/text/mandarin.py b/spaces/Plachta/VITS-Umamusume-voice-synthesizer/text/mandarin.py deleted file mode 100644 index 093d8826809aa2681f6088174427337a59e0c882..0000000000000000000000000000000000000000 --- a/spaces/Plachta/VITS-Umamusume-voice-synthesizer/text/mandarin.py +++ /dev/null @@ -1,329 +0,0 @@ -import os -import sys -import re -from pypinyin import lazy_pinyin, BOPOMOFO -import jieba -import cn2an -import logging - -logging.getLogger('jieba').setLevel(logging.WARNING) -jieba.initialize() - - -# List of (Latin alphabet, bopomofo) pairs: -_latin_to_bopomofo = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ - ('a', 'ㄟˉ'), - ('b', 'ㄅㄧˋ'), - ('c', 'ㄙㄧˉ'), - ('d', 'ㄉㄧˋ'), - ('e', 'ㄧˋ'), - ('f', 'ㄝˊㄈㄨˋ'), - ('g', 'ㄐㄧˋ'), - ('h', 'ㄝˇㄑㄩˋ'), - ('i', 'ㄞˋ'), - ('j', 'ㄐㄟˋ'), - ('k', 'ㄎㄟˋ'), - ('l', 'ㄝˊㄛˋ'), - ('m', 'ㄝˊㄇㄨˋ'), - ('n', 'ㄣˉ'), - ('o', 'ㄡˉ'), - ('p', 'ㄆㄧˉ'), - ('q', 'ㄎㄧㄡˉ'), - ('r', 'ㄚˋ'), - ('s', 'ㄝˊㄙˋ'), - ('t', 'ㄊㄧˋ'), - ('u', 'ㄧㄡˉ'), - ('v', 'ㄨㄧˉ'), - ('w', 'ㄉㄚˋㄅㄨˋㄌㄧㄡˋ'), - ('x', 'ㄝˉㄎㄨˋㄙˋ'), - ('y', 'ㄨㄞˋ'), - ('z', 'ㄗㄟˋ') -]] - -# List of (bopomofo, romaji) pairs: -_bopomofo_to_romaji = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('ㄅㄛ', 'p⁼wo'), - ('ㄆㄛ', 'pʰwo'), - ('ㄇㄛ', 'mwo'), - ('ㄈㄛ', 'fwo'), - ('ㄅ', 'p⁼'), - ('ㄆ', 'pʰ'), - ('ㄇ', 'm'), - ('ㄈ', 'f'), - ('ㄉ', 't⁼'), - ('ㄊ', 'tʰ'), - ('ㄋ', 'n'), - ('ㄌ', 'l'), - ('ㄍ', 'k⁼'), - ('ㄎ', 'kʰ'), - ('ㄏ', 'h'), - ('ㄐ', 'ʧ⁼'), - ('ㄑ', 'ʧʰ'), - ('ㄒ', 'ʃ'), - ('ㄓ', 'ʦ`⁼'), - ('ㄔ', 'ʦ`ʰ'), - ('ㄕ', 's`'), - ('ㄖ', 'ɹ`'), - ('ㄗ', 'ʦ⁼'), - ('ㄘ', 'ʦʰ'), - ('ㄙ', 's'), - ('ㄚ', 'a'), - ('ㄛ', 'o'), - ('ㄜ', 'ə'), - ('ㄝ', 'e'), - ('ㄞ', 'ai'), - ('ㄟ', 'ei'), - ('ㄠ', 'au'), - ('ㄡ', 'ou'), - ('ㄧㄢ', 'yeNN'), - ('ㄢ', 'aNN'), - ('ㄧㄣ', 'iNN'), - ('ㄣ', 'əNN'), - ('ㄤ', 'aNg'), - ('ㄧㄥ', 'iNg'), - ('ㄨㄥ', 'uNg'), - ('ㄩㄥ', 'yuNg'), - ('ㄥ', 'əNg'), - ('ㄦ', 'əɻ'), - ('ㄧ', 'i'), - ('ㄨ', 'u'), - ('ㄩ', 'ɥ'), - ('ˉ', '→'), - ('ˊ', '↑'), - ('ˇ', '↓↑'), - ('ˋ', '↓'), - ('˙', ''), - (',', ','), - ('。', '.'), - ('!', '!'), - ('?', '?'), - ('—', '-') -]] - -# List of (romaji, ipa) pairs: -_romaji_to_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ - ('ʃy', 'ʃ'), - ('ʧʰy', 'ʧʰ'), - ('ʧ⁼y', 'ʧ⁼'), - ('NN', 'n'), - ('Ng', 'ŋ'), - ('y', 'j'), - ('h', 'x') -]] - -# List of (bopomofo, ipa) pairs: -_bopomofo_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('ㄅㄛ', 'p⁼wo'), - ('ㄆㄛ', 'pʰwo'), - ('ㄇㄛ', 'mwo'), - ('ㄈㄛ', 'fwo'), - ('ㄅ', 'p⁼'), - ('ㄆ', 'pʰ'), - ('ㄇ', 'm'), - ('ㄈ', 'f'), - ('ㄉ', 't⁼'), - ('ㄊ', 'tʰ'), - ('ㄋ', 'n'), - ('ㄌ', 'l'), - ('ㄍ', 'k⁼'), - ('ㄎ', 'kʰ'), - ('ㄏ', 'x'), - ('ㄐ', 'tʃ⁼'), - ('ㄑ', 'tʃʰ'), - ('ㄒ', 'ʃ'), - ('ㄓ', 'ts`⁼'), - ('ㄔ', 'ts`ʰ'), - ('ㄕ', 's`'), - ('ㄖ', 'ɹ`'), - ('ㄗ', 'ts⁼'), - ('ㄘ', 'tsʰ'), - ('ㄙ', 's'), - ('ㄚ', 'a'), - ('ㄛ', 'o'), - ('ㄜ', 'ə'), - ('ㄝ', 'ɛ'), - ('ㄞ', 'aɪ'), - ('ㄟ', 'eɪ'), - ('ㄠ', 'ɑʊ'), - ('ㄡ', 'oʊ'), - ('ㄧㄢ', 'jɛn'), - ('ㄩㄢ', 'ɥæn'), - ('ㄢ', 'an'), - ('ㄧㄣ', 'in'), - ('ㄩㄣ', 'ɥn'), - ('ㄣ', 'ən'), - ('ㄤ', 'ɑŋ'), - ('ㄧㄥ', 'iŋ'), - ('ㄨㄥ', 'ʊŋ'), - ('ㄩㄥ', 'jʊŋ'), - ('ㄥ', 'əŋ'), - ('ㄦ', 'əɻ'), - ('ㄧ', 'i'), - ('ㄨ', 'u'), - ('ㄩ', 'ɥ'), - ('ˉ', '→'), - ('ˊ', '↑'), - ('ˇ', '↓↑'), - ('ˋ', '↓'), - ('˙', ''), - (',', ','), - ('。', '.'), - ('!', '!'), - ('?', '?'), - ('—', '-') -]] - -# List of (bopomofo, ipa2) pairs: -_bopomofo_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('ㄅㄛ', 'pwo'), - ('ㄆㄛ', 'pʰwo'), - ('ㄇㄛ', 'mwo'), - ('ㄈㄛ', 'fwo'), - ('ㄅ', 'p'), - ('ㄆ', 'pʰ'), - ('ㄇ', 'm'), - ('ㄈ', 'f'), - ('ㄉ', 't'), - ('ㄊ', 'tʰ'), - ('ㄋ', 'n'), - ('ㄌ', 'l'), - ('ㄍ', 'k'), - ('ㄎ', 'kʰ'), - ('ㄏ', 'h'), - ('ㄐ', 'tɕ'), - ('ㄑ', 'tɕʰ'), - ('ㄒ', 'ɕ'), - ('ㄓ', 'tʂ'), - ('ㄔ', 'tʂʰ'), - ('ㄕ', 'ʂ'), - ('ㄖ', 'ɻ'), - ('ㄗ', 'ts'), - ('ㄘ', 'tsʰ'), - ('ㄙ', 's'), - ('ㄚ', 'a'), - ('ㄛ', 'o'), - ('ㄜ', 'ɤ'), - ('ㄝ', 'ɛ'), - ('ㄞ', 'aɪ'), - ('ㄟ', 'eɪ'), - ('ㄠ', 'ɑʊ'), - ('ㄡ', 'oʊ'), - ('ㄧㄢ', 'jɛn'), - ('ㄩㄢ', 'yæn'), - ('ㄢ', 'an'), - ('ㄧㄣ', 'in'), - ('ㄩㄣ', 'yn'), - ('ㄣ', 'ən'), - ('ㄤ', 'ɑŋ'), - ('ㄧㄥ', 'iŋ'), - ('ㄨㄥ', 'ʊŋ'), - ('ㄩㄥ', 'jʊŋ'), - ('ㄥ', 'ɤŋ'), - ('ㄦ', 'əɻ'), - ('ㄧ', 'i'), - ('ㄨ', 'u'), - ('ㄩ', 'y'), - ('ˉ', '˥'), - ('ˊ', '˧˥'), - ('ˇ', '˨˩˦'), - ('ˋ', '˥˩'), - ('˙', ''), - (',', ','), - ('。', '.'), - ('!', '!'), - ('?', '?'), - ('—', '-') -]] - - -def number_to_chinese(text): - numbers = re.findall(r'\d+(?:\.?\d+)?', text) - for number in numbers: - text = text.replace(number, cn2an.an2cn(number), 1) - return text - - -def chinese_to_bopomofo(text): - text = text.replace('、', ',').replace(';', ',').replace(':', ',') - words = jieba.lcut(text, cut_all=False) - text = '' - for word in words: - bopomofos = lazy_pinyin(word, BOPOMOFO) - if not re.search('[\u4e00-\u9fff]', word): - text += word - continue - for i in range(len(bopomofos)): - bopomofos[i] = re.sub(r'([\u3105-\u3129])$', r'\1ˉ', bopomofos[i]) - if text != '': - text += ' ' - text += ''.join(bopomofos) - return text - - -def latin_to_bopomofo(text): - for regex, replacement in _latin_to_bopomofo: - text = re.sub(regex, replacement, text) - return text - - -def bopomofo_to_romaji(text): - for regex, replacement in _bopomofo_to_romaji: - text = re.sub(regex, replacement, text) - return text - - -def bopomofo_to_ipa(text): - for regex, replacement in _bopomofo_to_ipa: - text = re.sub(regex, replacement, text) - return text - - -def bopomofo_to_ipa2(text): - for regex, replacement in _bopomofo_to_ipa2: - text = re.sub(regex, replacement, text) - return text - - -def chinese_to_romaji(text): - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - text = bopomofo_to_romaji(text) - text = re.sub('i([aoe])', r'y\1', text) - text = re.sub('u([aoəe])', r'w\1', text) - text = re.sub('([ʦsɹ]`[⁼ʰ]?)([→↓↑ ]+|$)', - r'\1ɹ`\2', text).replace('ɻ', 'ɹ`') - text = re.sub('([ʦs][⁼ʰ]?)([→↓↑ ]+|$)', r'\1ɹ\2', text) - return text - - -def chinese_to_lazy_ipa(text): - text = chinese_to_romaji(text) - for regex, replacement in _romaji_to_ipa: - text = re.sub(regex, replacement, text) - return text - - -def chinese_to_ipa(text): - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - text = bopomofo_to_ipa(text) - text = re.sub('i([aoe])', r'j\1', text) - text = re.sub('u([aoəe])', r'w\1', text) - text = re.sub('([sɹ]`[⁼ʰ]?)([→↓↑ ]+|$)', - r'\1ɹ`\2', text).replace('ɻ', 'ɹ`') - text = re.sub('([s][⁼ʰ]?)([→↓↑ ]+|$)', r'\1ɹ\2', text) - return text - - -def chinese_to_ipa2(text): - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - text = bopomofo_to_ipa2(text) - text = re.sub(r'i([aoe])', r'j\1', text) - text = re.sub(r'u([aoəe])', r'w\1', text) - text = re.sub(r'([ʂɹ]ʰ?)([˩˨˧˦˥ ]+|$)', r'\1ʅ\2', text) - text = re.sub(r'(sʰ?)([˩˨˧˦˥ ]+|$)', r'\1ɿ\2', text) - return text \ No newline at end of file diff --git a/spaces/Rakot2223/faster-whisper-webui/tests/segments_test.py b/spaces/Rakot2223/faster-whisper-webui/tests/segments_test.py deleted file mode 100644 index d829f1c77f74b3c96513fe4965d532cf2d1dceb4..0000000000000000000000000000000000000000 --- a/spaces/Rakot2223/faster-whisper-webui/tests/segments_test.py +++ /dev/null @@ -1,48 +0,0 @@ -import sys -import unittest - -sys.path.append('../whisper-webui') - -from src.segments import merge_timestamps - -class TestSegments(unittest.TestCase): - def __init__(self, *args, **kwargs): - super(TestSegments, self).__init__(*args, **kwargs) - - def test_merge_segments(self): - segments = [ - {'start': 10.0, 'end': 20.0}, - {'start': 22.0, 'end': 27.0}, - {'start': 31.0, 'end': 35.0}, - {'start': 45.0, 'end': 60.0}, - {'start': 61.0, 'end': 65.0}, - {'start': 68.0, 'end': 98.0}, - {'start': 100.0, 'end': 102.0}, - {'start': 110.0, 'end': 112.0} - ] - - result = merge_timestamps(segments, merge_window=5, max_merge_size=30, padding_left=1, padding_right=1) - - self.assertListEqual(result, [ - {'start': 9.0, 'end': 36.0}, - {'start': 44.0, 'end': 66.0}, - {'start': 67.0, 'end': 99.0}, - {'start': 99.0, 'end': 103.0}, - {'start': 109.0, 'end': 113.0} - ]) - - def test_overlap_next(self): - segments = [ - {'start': 5.0, 'end': 39.182}, - {'start': 39.986, 'end': 40.814} - ] - - result = merge_timestamps(segments, merge_window=5, max_merge_size=30, padding_left=1, padding_right=1) - - self.assertListEqual(result, [ - {'start': 4.0, 'end': 39.584}, - {'start': 39.584, 'end': 41.814} - ]) - -if __name__ == '__main__': - unittest.main() \ No newline at end of file diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/rich/styled.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/rich/styled.py deleted file mode 100644 index 91cd0db31c14e30d4c1e2e9f36382b7a5e022870..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/rich/styled.py +++ /dev/null @@ -1,42 +0,0 @@ -from typing import TYPE_CHECKING - -from .measure import Measurement -from .segment import Segment -from .style import StyleType - -if TYPE_CHECKING: - from .console import Console, ConsoleOptions, RenderResult, RenderableType - - -class Styled: - """Apply a style to a renderable. - - Args: - renderable (RenderableType): Any renderable. - style (StyleType): A style to apply across the entire renderable. - """ - - def __init__(self, renderable: "RenderableType", style: "StyleType") -> None: - self.renderable = renderable - self.style = style - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - style = console.get_style(self.style) - rendered_segments = console.render(self.renderable, options) - segments = Segment.apply_style(rendered_segments, style) - return segments - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> Measurement: - return Measurement.get(console, options, self.renderable) - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich import print - from pip._vendor.rich.panel import Panel - - panel = Styled(Panel("hello"), "on blue") - print(panel) diff --git a/spaces/Redgon/bingo/Dockerfile b/spaces/Redgon/bingo/Dockerfile deleted file mode 100644 index 3aa2b29b5fc4fa8b8238955acd7f1fde13ce5e1a..0000000000000000000000000000000000000000 --- a/spaces/Redgon/bingo/Dockerfile +++ /dev/null @@ -1,36 +0,0 @@ -FROM node:18 - - -ARG DEBIAN_FRONTEND=noninteractive - -ENV BING_HEADER "" - -# Set home to the user's home directory -ENV HOME=/home/user \ - PATH=/home/user/.local/bin:$PATH - -# Set up a new user named "user" with user ID 1000 -RUN useradd -o -u 1000 user && mkdir -p $HOME/app && chown -R user $HOME - -# Switch to the "user" user -USER user - -# Set the working directory to the user's home directory -WORKDIR $HOME/app - -# Install app dependencies -# A wildcard is used to ensure both package.json AND package-lock.json are copied -# where available (npm@5+) -COPY --chown=user package*.json $HOME/app/ - -RUN npm install - -# Copy the current directory contents into the container at $HOME/app setting the owner to the user -COPY --chown=user . $HOME/app/ - -RUN npm run build - -ENV PORT 7860 -EXPOSE 7860 - -CMD npm start diff --git a/spaces/Reeve/Ohayou_Face/dnnlib/__init__.py b/spaces/Reeve/Ohayou_Face/dnnlib/__init__.py deleted file mode 100644 index 2f08cf36f11f9b0fd94c1b7caeadf69b98375b04..0000000000000000000000000000000000000000 --- a/spaces/Reeve/Ohayou_Face/dnnlib/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -from .util import EasyDict, make_cache_dir_path diff --git a/spaces/Rekanice/hf_minimal_sushi/app.py b/spaces/Rekanice/hf_minimal_sushi/app.py deleted file mode 100644 index 28656333ecd48b728394192a80c313a3dedb5449..0000000000000000000000000000000000000000 --- a/spaces/Rekanice/hf_minimal_sushi/app.py +++ /dev/null @@ -1,16 +0,0 @@ -from fastai.vision.all import * -import gradio as gr -import glob - -learn = load_learner("export.pkl") -categories = learn.dls.vocab - -def classify_image(img): - pred,idx,probs = learn.predict(img) - return dict(zip(categories, map(float,probs))) - -image = gr.inputs.Image(shape=(192,192)) -label = gr.outputs.Label() -examples = glob.glob("./images/*.jpg") -intf= gr.Interface(fn=classify_image, inputs=image, outputs=label, examples=examples) -intf.launch(inline=False) \ No newline at end of file diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/parallel/distributed.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/parallel/distributed.py deleted file mode 100644 index 1e4c27903db58a54d37ea1ed9ec0104098b486f2..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/parallel/distributed.py +++ /dev/null @@ -1,112 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -from torch.nn.parallel.distributed import (DistributedDataParallel, - _find_tensors) - -from annotator.uniformer.mmcv import print_log -from annotator.uniformer.mmcv.utils import TORCH_VERSION, digit_version -from .scatter_gather import scatter_kwargs - - -class MMDistributedDataParallel(DistributedDataParallel): - """The DDP module that supports DataContainer. - - MMDDP has two main differences with PyTorch DDP: - - - It supports a custom type :class:`DataContainer` which allows more - flexible control of input data. - - It implement two APIs ``train_step()`` and ``val_step()``. - """ - - def to_kwargs(self, inputs, kwargs, device_id): - # Use `self.to_kwargs` instead of `self.scatter` in pytorch1.8 - # to move all tensors to device_id - return scatter_kwargs(inputs, kwargs, [device_id], dim=self.dim) - - def scatter(self, inputs, kwargs, device_ids): - return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim) - - def train_step(self, *inputs, **kwargs): - """train_step() API for module wrapped by DistributedDataParallel. - - This method is basically the same as - ``DistributedDataParallel.forward()``, while replacing - ``self.module.forward()`` with ``self.module.train_step()``. - It is compatible with PyTorch 1.1 - 1.5. - """ - - # In PyTorch >= 1.7, ``reducer._rebuild_buckets()`` is moved from the - # end of backward to the beginning of forward. - if ('parrots' not in TORCH_VERSION - and digit_version(TORCH_VERSION) >= digit_version('1.7') - and self.reducer._rebuild_buckets()): - print_log( - 'Reducer buckets have been rebuilt in this iteration.', - logger='mmcv') - - if getattr(self, 'require_forward_param_sync', True): - self._sync_params() - if self.device_ids: - inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids) - if len(self.device_ids) == 1: - output = self.module.train_step(*inputs[0], **kwargs[0]) - else: - outputs = self.parallel_apply( - self._module_copies[:len(inputs)], inputs, kwargs) - output = self.gather(outputs, self.output_device) - else: - output = self.module.train_step(*inputs, **kwargs) - - if torch.is_grad_enabled() and getattr( - self, 'require_backward_grad_sync', True): - if self.find_unused_parameters: - self.reducer.prepare_for_backward(list(_find_tensors(output))) - else: - self.reducer.prepare_for_backward([]) - else: - if ('parrots' not in TORCH_VERSION - and digit_version(TORCH_VERSION) > digit_version('1.2')): - self.require_forward_param_sync = False - return output - - def val_step(self, *inputs, **kwargs): - """val_step() API for module wrapped by DistributedDataParallel. - - This method is basically the same as - ``DistributedDataParallel.forward()``, while replacing - ``self.module.forward()`` with ``self.module.val_step()``. - It is compatible with PyTorch 1.1 - 1.5. - """ - # In PyTorch >= 1.7, ``reducer._rebuild_buckets()`` is moved from the - # end of backward to the beginning of forward. - if ('parrots' not in TORCH_VERSION - and digit_version(TORCH_VERSION) >= digit_version('1.7') - and self.reducer._rebuild_buckets()): - print_log( - 'Reducer buckets have been rebuilt in this iteration.', - logger='mmcv') - - if getattr(self, 'require_forward_param_sync', True): - self._sync_params() - if self.device_ids: - inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids) - if len(self.device_ids) == 1: - output = self.module.val_step(*inputs[0], **kwargs[0]) - else: - outputs = self.parallel_apply( - self._module_copies[:len(inputs)], inputs, kwargs) - output = self.gather(outputs, self.output_device) - else: - output = self.module.val_step(*inputs, **kwargs) - - if torch.is_grad_enabled() and getattr( - self, 'require_backward_grad_sync', True): - if self.find_unused_parameters: - self.reducer.prepare_for_backward(list(_find_tensors(output))) - else: - self.reducer.prepare_for_backward([]) - else: - if ('parrots' not in TORCH_VERSION - and digit_version(TORCH_VERSION) > digit_version('1.2')): - self.require_forward_param_sync = False - return output diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/models/detectors/fovea.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/models/detectors/fovea.py deleted file mode 100644 index 22a578efffbd108db644d907bae95c7c8df31f2e..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/models/detectors/fovea.py +++ /dev/null @@ -1,17 +0,0 @@ -from ..builder import DETECTORS -from .single_stage import SingleStageDetector - - -@DETECTORS.register_module() -class FOVEA(SingleStageDetector): - """Implementation of `FoveaBox `_""" - - def __init__(self, - backbone, - neck, - bbox_head, - train_cfg=None, - test_cfg=None, - pretrained=None): - super(FOVEA, self).__init__(backbone, neck, bbox_head, train_cfg, - test_cfg, pretrained) diff --git a/spaces/Rongjiehuang/GenerSpeech/modules/parallel_wavegan/utils/__init__.py b/spaces/Rongjiehuang/GenerSpeech/modules/parallel_wavegan/utils/__init__.py deleted file mode 100644 index e8fa95a020706b5412c3959fbf6e5980019c0d5f..0000000000000000000000000000000000000000 --- a/spaces/Rongjiehuang/GenerSpeech/modules/parallel_wavegan/utils/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .utils import * # NOQA diff --git a/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/stft_loss.py b/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/stft_loss.py deleted file mode 100644 index 229e6c777dc9ec7f710842d1e648dba1189ec8b4..0000000000000000000000000000000000000000 --- a/spaces/Rongjiehuang/ProDiff/modules/parallel_wavegan/stft_loss.py +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2019 Tomoki Hayashi -# MIT License (https://opensource.org/licenses/MIT) - -"""STFT-based Loss modules.""" -import librosa -import torch - -from modules.parallel_wavegan.losses import LogSTFTMagnitudeLoss, SpectralConvergengeLoss, stft - - -class STFTLoss(torch.nn.Module): - """STFT loss module.""" - - def __init__(self, fft_size=1024, shift_size=120, win_length=600, window="hann_window", - use_mel_loss=False): - """Initialize STFT loss module.""" - super(STFTLoss, self).__init__() - self.fft_size = fft_size - self.shift_size = shift_size - self.win_length = win_length - self.window = getattr(torch, window)(win_length) - self.spectral_convergenge_loss = SpectralConvergengeLoss() - self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss() - self.use_mel_loss = use_mel_loss - self.mel_basis = None - - def forward(self, x, y): - """Calculate forward propagation. - - Args: - x (Tensor): Predicted signal (B, T). - y (Tensor): Groundtruth signal (B, T). - - Returns: - Tensor: Spectral convergence loss value. - Tensor: Log STFT magnitude loss value. - - """ - x_mag = stft(x, self.fft_size, self.shift_size, self.win_length, self.window) - y_mag = stft(y, self.fft_size, self.shift_size, self.win_length, self.window) - if self.use_mel_loss: - if self.mel_basis is None: - self.mel_basis = torch.from_numpy(librosa.filters.mel(22050, self.fft_size, 80)).cuda().T - x_mag = x_mag @ self.mel_basis - y_mag = y_mag @ self.mel_basis - - sc_loss = self.spectral_convergenge_loss(x_mag, y_mag) - mag_loss = self.log_stft_magnitude_loss(x_mag, y_mag) - - return sc_loss, mag_loss - - -class MultiResolutionSTFTLoss(torch.nn.Module): - """Multi resolution STFT loss module.""" - - def __init__(self, - fft_sizes=[1024, 2048, 512], - hop_sizes=[120, 240, 50], - win_lengths=[600, 1200, 240], - window="hann_window", - use_mel_loss=False): - """Initialize Multi resolution STFT loss module. - - Args: - fft_sizes (list): List of FFT sizes. - hop_sizes (list): List of hop sizes. - win_lengths (list): List of window lengths. - window (str): Window function type. - - """ - super(MultiResolutionSTFTLoss, self).__init__() - assert len(fft_sizes) == len(hop_sizes) == len(win_lengths) - self.stft_losses = torch.nn.ModuleList() - for fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths): - self.stft_losses += [STFTLoss(fs, ss, wl, window, use_mel_loss)] - - def forward(self, x, y): - """Calculate forward propagation. - - Args: - x (Tensor): Predicted signal (B, T). - y (Tensor): Groundtruth signal (B, T). - - Returns: - Tensor: Multi resolution spectral convergence loss value. - Tensor: Multi resolution log STFT magnitude loss value. - - """ - sc_loss = 0.0 - mag_loss = 0.0 - for f in self.stft_losses: - sc_l, mag_l = f(x, y) - sc_loss += sc_l - mag_loss += mag_l - sc_loss /= len(self.stft_losses) - mag_loss /= len(self.stft_losses) - - return sc_loss, mag_loss diff --git a/spaces/SUPERSHANKY/ControlNet_Colab/app.py b/spaces/SUPERSHANKY/ControlNet_Colab/app.py deleted file mode 100644 index 7025778c0fe5d7c92c2afb96f1a98b7bf342eb4d..0000000000000000000000000000000000000000 --- a/spaces/SUPERSHANKY/ControlNet_Colab/app.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python - -from __future__ import annotations - -import os -import pathlib -import shlex -import subprocess - -import gradio as gr - -if os.getenv('SYSTEM') == 'spaces': - with open('patch') as f: - subprocess.run(shlex.split('patch -p1'), stdin=f, cwd='ControlNet') - -base_url = 'https://huggingface.co/lllyasviel/ControlNet/tree/resolve/annotator/ckpts' -names = [ - 'body_pose_model.pth', - 'dpt_hybrid-midas-501f0c75.pt', - 'hand_pose_model.pth', - 'mlsd_large_512_fp32.pth', - 'mlsd_tiny_512_fp32.pth', - 'network-bsds500.pth', - 'upernet_global_small.pth', -] -for name in names: - command = f'wget https://huggingface.co/lllyasviel/ControlNet/tree/resolve/annotator/ckpts/{name} -O {name}' - out_path = pathlib.Path(f'ControlNet/annotator/ckpts/{name}') - if out_path.exists(): - continue - subprocess.run(shlex.split(command), cwd='ControlNet/annotator/ckpts/') - -from gradio_canny2image import create_demo as create_demo_canny -from gradio_depth2image import create_demo as create_demo_depth -from gradio_fake_scribble2image import create_demo as create_demo_fake_scribble -from gradio_hed2image import create_demo as create_demo_hed -from gradio_hough2image import create_demo as create_demo_hough -from gradio_normal2image import create_demo as create_demo_normal -from gradio_pose2image import create_demo as create_demo_pose -from gradio_scribble2image import create_demo as create_demo_scribble -from gradio_scribble2image_interactive import \ - create_demo as create_demo_scribble_interactive -from gradio_seg2image import create_demo as create_demo_seg -from model import (DEFAULT_BASE_MODEL_FILENAME, DEFAULT_BASE_MODEL_REPO, - DEFAULT_BASE_MODEL_URL, Model) - -MAX_IMAGES = 1 -DESCRIPTION = '''# [ControlNet](https://github.com/lllyasviel/ControlNet) - -This Space is a modified version of [this Space](https://huggingface.co/spaces/hysts/ControlNet). -The original Space uses [Stable Diffusion v1.5](https://huggingface.co/runwayml/stable-diffusion-v1-5) as the base model, but [Anything v4.0](https://huggingface.co/andite/anything-v4.0) is used in this Space. -''' - -SPACE_ID = os.getenv('SPACE_ID') -ALLOW_CHANGING_BASE_MODEL = SPACE_ID != 'hysts/ControlNet-with-other-models' - -if not ALLOW_CHANGING_BASE_MODEL: - DESCRIPTION += 'In this Space, the base model is not allowed to be changed so as not to slow down the demo, but it can be changed if you duplicate the Space.' - -if SPACE_ID is not None: - DESCRIPTION += f'''

For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.
- -Duplicate Space -

-''' - -model = Model() - -with gr.Blocks(css='style.css') as demo: - gr.Markdown(DESCRIPTION) - - with gr.Tabs(): - with gr.TabItem('Canny'): - create_demo_canny(model.process_canny, max_images=MAX_IMAGES) - with gr.TabItem('Hough'): - create_demo_hough(model.process_hough, max_images=MAX_IMAGES) - with gr.TabItem('HED'): - create_demo_hed(model.process_hed, max_images=MAX_IMAGES) - with gr.TabItem('Scribble'): - create_demo_scribble(model.process_scribble, max_images=MAX_IMAGES) - with gr.TabItem('Scribble Interactive'): - create_demo_scribble_interactive( - model.process_scribble_interactive, max_images=MAX_IMAGES) - with gr.TabItem('Fake Scribble'): - create_demo_fake_scribble(model.process_fake_scribble, - max_images=MAX_IMAGES) - with gr.TabItem('Pose'): - create_demo_pose(model.process_pose, max_images=MAX_IMAGES) - with gr.TabItem('Segmentation'): - create_demo_seg(model.process_seg, max_images=MAX_IMAGES) - with gr.TabItem('Depth'): - create_demo_depth(model.process_depth, max_images=MAX_IMAGES) - with gr.TabItem('Normal map'): - create_demo_normal(model.process_normal, max_images=MAX_IMAGES) - - with gr.Accordion(label='Base model', open=False): - current_base_model = gr.Text(label='Current base model', - value=DEFAULT_BASE_MODEL_URL) - with gr.Row(): - base_model_repo = gr.Text(label='Base model repo', - max_lines=1, - placeholder=DEFAULT_BASE_MODEL_REPO, - interactive=ALLOW_CHANGING_BASE_MODEL) - base_model_filename = gr.Text( - label='Base model file', - max_lines=1, - placeholder=DEFAULT_BASE_MODEL_FILENAME, - interactive=ALLOW_CHANGING_BASE_MODEL) - change_base_model_button = gr.Button('Change base model') - gr.Markdown( - '''- You can use other base models by specifying the repository name and filename. -The base model must be compatible with Stable Diffusion v1.5.''') - - change_base_model_button.click(fn=model.set_base_model, - inputs=[ - base_model_repo, - base_model_filename, - ], - outputs=current_base_model) - -demo.queue(api_open=False).launch() -demo.launch(debug=is_colab, share=is_colab) diff --git a/spaces/SeViLA/SeViLA/lavis/datasets/datasets/coco_caption_datasets.py b/spaces/SeViLA/SeViLA/lavis/datasets/datasets/coco_caption_datasets.py deleted file mode 100644 index 400750a75ea947ff5ae230747c5de6f5fe721e55..0000000000000000000000000000000000000000 --- a/spaces/SeViLA/SeViLA/lavis/datasets/datasets/coco_caption_datasets.py +++ /dev/null @@ -1,70 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import os -import json - -from PIL import Image -from PIL import ImageFile - -ImageFile.LOAD_TRUNCATED_IMAGES = True - -from lavis.datasets.datasets.caption_datasets import CaptionDataset, CaptionEvalDataset - -COCOCapDataset = CaptionDataset - - -class COCOCapEvalDataset(CaptionEvalDataset): - def __init__(self, vis_processor, text_processor, vis_root, ann_paths): - """ - vis_root (string): Root directory of images (e.g. coco/images/) - ann_root (string): directory to store the annotation file - split (string): val or test - """ - super().__init__(vis_processor, text_processor, vis_root, ann_paths) - - def __getitem__(self, index): - ann = self.annotation[index] - - image_path = os.path.join(self.vis_root, ann["image"]) - image = Image.open(image_path).convert("RGB") - - image = self.vis_processor(image) - - img_id = ann["image"].split("/")[-1].strip(".jpg").split("_")[-1] - - return { - "image": image, - "image_id": img_id, - "instance_id": ann["instance_id"], - } - - -class NoCapsEvalDataset(CaptionEvalDataset): - def __init__(self, vis_processor, text_processor, vis_root, ann_paths): - """ - vis_root (string): Root directory of images (e.g. coco/images/) - ann_root (string): directory to store the annotation file - split (string): val or test - """ - super().__init__(vis_processor, text_processor, vis_root, ann_paths) - - def __getitem__(self, index): - ann = self.annotation[index] - - image_path = os.path.join(self.vis_root, ann["image"]) - image = Image.open(image_path).convert("RGB") - - image = self.vis_processor(image) - - img_id = ann["img_id"] - - return { - "image": image, - "image_id": img_id, - "instance_id": ann["instance_id"], - } diff --git a/spaces/SerdarHelli/ThyroidTumorClassification/app.py b/spaces/SerdarHelli/ThyroidTumorClassification/app.py deleted file mode 100644 index d4f3028d795ebb535ca9194199b53ac0b08d8e79..0000000000000000000000000000000000000000 --- a/spaces/SerdarHelli/ThyroidTumorClassification/app.py +++ /dev/null @@ -1,42 +0,0 @@ -import gradio as gr - -title="Thyroid Tumor Classification On Ultrasound Images" -article = "This study was made by S.Serdar Helli using HF Transformers ConvNext" - -description=f''' - -Thyroid nodule is one of the most common endocrine carcinomas. Due to its higher reveal ability and ability to distinguish between benign and malignant nodules in pathological features, ultrasonography has become the most widely used modality for finding and diagnosing thyroid cancer when compared to CT and MRI. - -In this study, the purpose is the classification of thyroid tumors on ultrasound images with 2 different categories: - -- Malign(1) -- Benign(0) - -SubClasses - -- 1 Normal thyroid glandle -- 2 Effectively certainly benign Simple cyst - % 0 Risk of malignancy (Benign) -- 3 Very probably benigped - %0.25 Risk of malignancy (Benign) -- 4A Suspicious nodules; low risk of malignancy - % 6 Risk of malignancy (Malign) -- 4B Suspicious nodules; high risk of malignancy One or two features of high suspicion - %69 Risk of malignancy (Malign) -- 5 Effectively certainly malignant nodules - % 100 Risk of malignancy (Malign) - -This study was made using HF Transformers : - -- [ On Google Colab](https://colab.research.google.com/drive/1ueSq8Y_NmFr7NGdtS8FStI3d2HR-43LD?usp=sharing) - -- [On Github](https://github.com/SerdarHelli/The-Classification-of-Thyroid-Tumors-on-UltraSound-Images-using-Deep-Learning-Methods) - -- [ Using Keras and GradCam With MultiClasses Medium Article](https://serdarhelli.medium.com/the-basic-classification-of-thyroid-tumors-on-ultrasound-images-using-deep-learning-methods-46f812d859ea) - -The Dataset: -[Colombia National University presented an open access database of thyroid ultrasound images.](http://cimalab.unal.edu.co/?lang=es&mod=program&id=5) -Ref : Pedraza, Lina & Vargas, Carlos & Narváez, Fabián & Durán, Oscar & Muñoz, Emma & Romero, Eduardo. (2015). An open access thyroid ultrasound-image Database. Progress in Biomedical Optics and Imaging — Proceedings of SPIE. 9287. 10.1117/12.2073532. - -''' - - - -examples=["example_Benign1.png" ,"example_Benign2.png", "example_Malign2.png"] -gr.Interface.load("huggingface/SerdarHelli/ThyroidTumorClassificationModel", - title=title,description=description,article=article,examples=examples, cache_examples=False).launch() \ No newline at end of file diff --git a/spaces/Sevenlee/bert-Chinese/README.md b/spaces/Sevenlee/bert-Chinese/README.md deleted file mode 100644 index b5e9b11c847c3594ff73c9e73a580cbfa634b2cf..0000000000000000000000000000000000000000 --- a/spaces/Sevenlee/bert-Chinese/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Bert Chinese -emoji: 🌍 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.17.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/Starkate/zo/Dockerfile b/spaces/Starkate/zo/Dockerfile deleted file mode 100644 index 3a4dc66fdb50519fca2a6eaf64cbe0ea05b09a3f..0000000000000000000000000000000000000000 --- a/spaces/Starkate/zo/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM python:3.9 - -WORKDIR /code - -COPY ./requirements.txt /code/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -COPY . . - -EXPOSE 7860 - -CMD ["shiny", "run", "app.py", "--host", "0.0.0.0", "--port", "7860"] \ No newline at end of file diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/chromadb/types.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/chromadb/types.py deleted file mode 100644 index d254a10ab7d2a097a6dd12161ae49f32dc629ceb..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/chromadb/types.py +++ /dev/null @@ -1,145 +0,0 @@ -from typing import Optional, Union, Sequence, Dict, Mapping, List -from typing_extensions import Literal, TypedDict, TypeVar -from uuid import UUID -from enum import Enum - -Metadata = Mapping[str, Union[str, int, float]] -UpdateMetadata = Mapping[str, Union[int, float, str, None]] - -# Namespaced Names are mechanically just strings, but we use this type to indicate that -# the intent is for the value to be globally unique and semantically meaningful. -NamespacedName = str - - -class ScalarEncoding(Enum): - FLOAT32 = "FLOAT32" - INT32 = "INT32" - - -class SegmentScope(Enum): - VECTOR = "VECTOR" - METADATA = "METADATA" - - -class Collection(TypedDict): - id: UUID - name: str - topic: str - metadata: Optional[Metadata] - - -class Segment(TypedDict): - id: UUID - type: NamespacedName - scope: SegmentScope - # If a segment has a topic, it implies that this segment is a consumer of the topic - # and indexes the contents of the topic. - topic: Optional[str] - # If a segment has a collection, it implies that this segment implements the full - # collection and can be used to service queries (for it's given scope.) - collection: Optional[UUID] - metadata: Optional[Metadata] - - -# SeqID can be one of three types of value in our current and future plans: -# 1. A Pulsar MessageID encoded as a 192-bit integer -# 2. A Pulsar MessageIndex (a 64-bit integer) -# 3. A SQL RowID (a 64-bit integer) - -# All three of these types can be expressed as a Python int, so that is the type we -# use in the internal Python API. However, care should be taken that the larger 192-bit -# values are stored correctly when persisting to DBs. -SeqId = int - - -class Operation(Enum): - ADD = "ADD" - UPDATE = "UPDATE" - UPSERT = "UPSERT" - DELETE = "DELETE" - - -Vector = Union[Sequence[float], Sequence[int]] - - -class VectorEmbeddingRecord(TypedDict): - id: str - seq_id: SeqId - embedding: Vector - - -class MetadataEmbeddingRecord(TypedDict): - id: str - seq_id: SeqId - metadata: Optional[Metadata] - - -class EmbeddingRecord(TypedDict): - id: str - seq_id: SeqId - embedding: Optional[Vector] - encoding: Optional[ScalarEncoding] - metadata: Optional[UpdateMetadata] - operation: Operation - - -class SubmitEmbeddingRecord(TypedDict): - id: str - embedding: Optional[Vector] - encoding: Optional[ScalarEncoding] - metadata: Optional[UpdateMetadata] - operation: Operation - - -class VectorQuery(TypedDict): - """A KNN/ANN query""" - - vectors: Sequence[Vector] - k: int - allowed_ids: Optional[Sequence[str]] - options: Optional[Dict[str, Union[str, int, float]]] - - -class VectorQueryResult(TypedDict): - """A KNN/ANN query result""" - - id: str - seq_id: SeqId - distance: float - - -# Metadata Query Grammar -LiteralValue = Union[str, int, float] -LogicalOperator = Union[Literal["$and"], Literal["$or"]] -WhereOperator = Union[ - Literal["$gt"], - Literal["$gte"], - Literal["$lt"], - Literal["$lte"], - Literal["$ne"], - Literal["$eq"], -] -OperatorExpression = Dict[Union[WhereOperator, LogicalOperator], LiteralValue] - -Where = Dict[ - Union[str, LogicalOperator], Union[LiteralValue, OperatorExpression, List["Where"]] -] - -WhereDocumentOperator = Union[Literal["$contains"], LogicalOperator] -WhereDocument = Dict[WhereDocumentOperator, Union[str, List["WhereDocument"]]] - - -class Unspecified: - """A sentinel value used to indicate that a value should not be updated""" - - _instance: Optional["Unspecified"] = None - - def __new__(cls) -> "Unspecified": - if cls._instance is None: - cls._instance = super(Unspecified, cls).__new__(cls) - - return cls._instance - - -T = TypeVar("T") -OptionalArgument = Union[T, Unspecified] diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_coverage.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_coverage.py deleted file mode 100644 index a8359250039f97adc6bee8fe2947e15df3325896..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_coverage.py +++ /dev/null @@ -1,76 +0,0 @@ -import os.path -import sys -from _pydevd_bundle.pydevd_constants import Null - - -#======================================================================================================================= -# get_coverage_files -#======================================================================================================================= -def get_coverage_files(coverage_output_dir, number_of_files): - base_dir = coverage_output_dir - ret = [] - i = 0 - while len(ret) < number_of_files: - while True: - f = os.path.join(base_dir, '.coverage.%s' % i) - i += 1 - if not os.path.exists(f): - ret.append(f) - break #Break only inner for. - return ret - - -#======================================================================================================================= -# start_coverage_support -#======================================================================================================================= -def start_coverage_support(configuration): - return start_coverage_support_from_params( - configuration.coverage_output_dir, - configuration.coverage_output_file, - configuration.jobs, - configuration.coverage_include, - ) - - -#======================================================================================================================= -# start_coverage_support_from_params -#======================================================================================================================= -def start_coverage_support_from_params(coverage_output_dir, coverage_output_file, jobs, coverage_include): - coverage_files = [] - coverage_instance = Null() - if coverage_output_dir or coverage_output_file: - try: - import coverage #@UnresolvedImport - except: - sys.stderr.write('Error: coverage module could not be imported\n') - sys.stderr.write('Please make sure that the coverage module (http://nedbatchelder.com/code/coverage/)\n') - sys.stderr.write('is properly installed in your interpreter: %s\n' % (sys.executable,)) - - import traceback;traceback.print_exc() - else: - if coverage_output_dir: - if not os.path.exists(coverage_output_dir): - sys.stderr.write('Error: directory for coverage output (%s) does not exist.\n' % (coverage_output_dir,)) - - elif not os.path.isdir(coverage_output_dir): - sys.stderr.write('Error: expected (%s) to be a directory.\n' % (coverage_output_dir,)) - - else: - n = jobs - if n <= 0: - n += 1 - n += 1 #Add 1 more for the current process (which will do the initial import). - coverage_files = get_coverage_files(coverage_output_dir, n) - os.environ['COVERAGE_FILE'] = coverage_files.pop(0) - - coverage_instance = coverage.coverage(source=[coverage_include]) - coverage_instance.start() - - elif coverage_output_file: - #Client of parallel run. - os.environ['COVERAGE_FILE'] = coverage_output_file - coverage_instance = coverage.coverage(source=[coverage_include]) - coverage_instance.start() - - return coverage_files, coverage_instance - diff --git a/spaces/Suniilkumaar/MusicGen-updated/tests/modules/test_transformer.py b/spaces/Suniilkumaar/MusicGen-updated/tests/modules/test_transformer.py deleted file mode 100644 index ff7dfe4c2de05112aec55ddea9c8fd978668f80b..0000000000000000000000000000000000000000 --- a/spaces/Suniilkumaar/MusicGen-updated/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(): - for backend in ['torch', 'xformers']: - torch.manual_seed(1234) - 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(): - for backend in ['torch', 'xformers']: - torch.manual_seed(1234) - 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/Superlang/ImageProcessor/annotator/oneformer/detectron2/modeling/roi_heads/box_head.py b/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/modeling/roi_heads/box_head.py deleted file mode 100644 index 1e598af4f08af6618997607e1633f2b842eb6da0..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/modeling/roi_heads/box_head.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import numpy as np -from typing import List -import fvcore.nn.weight_init as weight_init -import torch -from torch import nn - -from annotator.oneformer.detectron2.config import configurable -from annotator.oneformer.detectron2.layers import Conv2d, ShapeSpec, get_norm -from annotator.oneformer.detectron2.utils.registry import Registry - -__all__ = ["FastRCNNConvFCHead", "build_box_head", "ROI_BOX_HEAD_REGISTRY"] - -ROI_BOX_HEAD_REGISTRY = Registry("ROI_BOX_HEAD") -ROI_BOX_HEAD_REGISTRY.__doc__ = """ -Registry for box heads, which make box predictions from per-region features. - -The registered object will be called with `obj(cfg, input_shape)`. -""" - - -# To get torchscript support, we make the head a subclass of `nn.Sequential`. -# Therefore, to add new layers in this head class, please make sure they are -# added in the order they will be used in forward(). -@ROI_BOX_HEAD_REGISTRY.register() -class FastRCNNConvFCHead(nn.Sequential): - """ - A head with several 3x3 conv layers (each followed by norm & relu) and then - several fc layers (each followed by relu). - """ - - @configurable - def __init__( - self, input_shape: ShapeSpec, *, conv_dims: List[int], fc_dims: List[int], conv_norm="" - ): - """ - NOTE: this interface is experimental. - - Args: - input_shape (ShapeSpec): shape of the input feature. - conv_dims (list[int]): the output dimensions of the conv layers - fc_dims (list[int]): the output dimensions of the fc layers - conv_norm (str or callable): normalization for the conv layers. - See :func:`detectron2.layers.get_norm` for supported types. - """ - super().__init__() - assert len(conv_dims) + len(fc_dims) > 0 - - self._output_size = (input_shape.channels, input_shape.height, input_shape.width) - - self.conv_norm_relus = [] - for k, conv_dim in enumerate(conv_dims): - conv = Conv2d( - self._output_size[0], - conv_dim, - kernel_size=3, - padding=1, - bias=not conv_norm, - norm=get_norm(conv_norm, conv_dim), - activation=nn.ReLU(), - ) - self.add_module("conv{}".format(k + 1), conv) - self.conv_norm_relus.append(conv) - self._output_size = (conv_dim, self._output_size[1], self._output_size[2]) - - self.fcs = [] - for k, fc_dim in enumerate(fc_dims): - if k == 0: - self.add_module("flatten", nn.Flatten()) - fc = nn.Linear(int(np.prod(self._output_size)), fc_dim) - self.add_module("fc{}".format(k + 1), fc) - self.add_module("fc_relu{}".format(k + 1), nn.ReLU()) - self.fcs.append(fc) - self._output_size = fc_dim - - for layer in self.conv_norm_relus: - weight_init.c2_msra_fill(layer) - for layer in self.fcs: - weight_init.c2_xavier_fill(layer) - - @classmethod - def from_config(cls, cfg, input_shape): - num_conv = cfg.MODEL.ROI_BOX_HEAD.NUM_CONV - conv_dim = cfg.MODEL.ROI_BOX_HEAD.CONV_DIM - num_fc = cfg.MODEL.ROI_BOX_HEAD.NUM_FC - fc_dim = cfg.MODEL.ROI_BOX_HEAD.FC_DIM - return { - "input_shape": input_shape, - "conv_dims": [conv_dim] * num_conv, - "fc_dims": [fc_dim] * num_fc, - "conv_norm": cfg.MODEL.ROI_BOX_HEAD.NORM, - } - - def forward(self, x): - for layer in self: - x = layer(x) - return x - - @property - @torch.jit.unused - def output_shape(self): - """ - Returns: - ShapeSpec: the output feature shape - """ - o = self._output_size - if isinstance(o, int): - return ShapeSpec(channels=o) - else: - return ShapeSpec(channels=o[0], height=o[1], width=o[2]) - - -def build_box_head(cfg, input_shape): - """ - Build a box head defined by `cfg.MODEL.ROI_BOX_HEAD.NAME`. - """ - name = cfg.MODEL.ROI_BOX_HEAD.NAME - return ROI_BOX_HEAD_REGISTRY.get(name)(cfg, input_shape) diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/utils/path.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/utils/path.py deleted file mode 100644 index 7dab4b3041413b1432b0f434b8b14783097d33c6..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/utils/path.py +++ /dev/null @@ -1,101 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import os -import os.path as osp -from pathlib import Path - -from .misc import is_str - - -def is_filepath(x): - return is_str(x) or isinstance(x, Path) - - -def fopen(filepath, *args, **kwargs): - if is_str(filepath): - return open(filepath, *args, **kwargs) - elif isinstance(filepath, Path): - return filepath.open(*args, **kwargs) - raise ValueError('`filepath` should be a string or a Path') - - -def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): - if not osp.isfile(filename): - raise FileNotFoundError(msg_tmpl.format(filename)) - - -def mkdir_or_exist(dir_name, mode=0o777): - if dir_name == '': - return - dir_name = osp.expanduser(dir_name) - os.makedirs(dir_name, mode=mode, exist_ok=True) - - -def symlink(src, dst, overwrite=True, **kwargs): - if os.path.lexists(dst) and overwrite: - os.remove(dst) - os.symlink(src, dst, **kwargs) - - -def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True): - """Scan a directory to find the interested files. - - Args: - dir_path (str | obj:`Path`): Path of the directory. - suffix (str | tuple(str), optional): File suffix that we are - interested in. Default: None. - recursive (bool, optional): If set to True, recursively scan the - directory. Default: False. - case_sensitive (bool, optional) : If set to False, ignore the case of - suffix. Default: True. - - Returns: - A generator for all the interested files with relative paths. - """ - if isinstance(dir_path, (str, Path)): - dir_path = str(dir_path) - else: - raise TypeError('"dir_path" must be a string or Path object') - - if (suffix is not None) and not isinstance(suffix, (str, tuple)): - raise TypeError('"suffix" must be a string or tuple of strings') - - if suffix is not None and not case_sensitive: - suffix = suffix.lower() if isinstance(suffix, str) else tuple( - item.lower() for item in suffix) - - root = dir_path - - def _scandir(dir_path, suffix, recursive, case_sensitive): - for entry in os.scandir(dir_path): - if not entry.name.startswith('.') and entry.is_file(): - rel_path = osp.relpath(entry.path, root) - _rel_path = rel_path if case_sensitive else rel_path.lower() - if suffix is None or _rel_path.endswith(suffix): - yield rel_path - elif recursive and os.path.isdir(entry.path): - # scan recursively if entry.path is a directory - yield from _scandir(entry.path, suffix, recursive, - case_sensitive) - - return _scandir(dir_path, suffix, recursive, case_sensitive) - - -def find_vcs_root(path, markers=('.git', )): - """Finds the root directory (including itself) of specified markers. - - Args: - path (str): Path of directory or file. - markers (list[str], optional): List of file or directory names. - - Returns: - The directory contained one of the markers or None if not found. - """ - if osp.isfile(path): - path = osp.dirname(path) - - prev, cur = None, osp.abspath(osp.expanduser(path)) - while cur != prev: - if any(osp.exists(osp.join(cur, marker)) for marker in markers): - return cur - prev, cur = cur, osp.split(cur)[0] - return None diff --git a/spaces/TRI-ML/risk_biased_prediction/risk_biased/utils/planner_utils.py b/spaces/TRI-ML/risk_biased_prediction/risk_biased/utils/planner_utils.py deleted file mode 100644 index 9b780d44c6bc3f49cf9e6c8ee65ecfe2c33ee867..0000000000000000000000000000000000000000 --- a/spaces/TRI-ML/risk_biased_prediction/risk_biased/utils/planner_utils.py +++ /dev/null @@ -1,462 +0,0 @@ -from __future__ import annotations - -from abc import ABC, abstractmethod -from typing import Optional, Tuple -from numpy import isin - -import torch - -from risk_biased.mpc_planner.planner_cost import TrackingCost -from risk_biased.utils.cost import BaseCostTorch -from risk_biased.utils.risk import AbstractMonteCarloRiskEstimator - - -def get_rotation_matrix(angle, device): - c = torch.cos(angle) - s = torch.sin(angle) - rot_matrix = torch.stack( - (torch.stack((c, s), -1), torch.stack((-s, c), -1)), -1 - ).to(device) - return rot_matrix - - -class AbstractState(ABC): - """ - State representation using an underlying tensor. Position, Velocity, and Angle can be accessed. - """ - - @property - @abstractmethod - def position(self) -> torch.Tensor: - """Extract position information from the state tensor - - Returns: - position_tensor of size (..., 2) - """ - - @property - @abstractmethod - def velocity(self) -> torch.Tensor: - """Extract velocity information from the state tensor - - Returns: - velocity_tensor of size (..., 2) - """ - - @property - @abstractmethod - def angle(self) -> torch.Tensor: - """Extract velocity information from the state tensor - - Returns: - velocity_tensor of size (..., 1) - """ - - @abstractmethod - def get_states(self, dim: int) -> torch.Tensor: - """Return the underlying states tensor with dim 2, 4 or 5 ([x, y], [x, y, vx, vy], or [x, y, angle, vx, vy]).""" - - @abstractmethod - def rotate(self, angle: float, in_place: bool) -> AbstractState: - """Rotate the state by the given angle - Args: - angle: in radiants - in_place: wether to change the object itself or return a rotated copy - Returns: - rotated self or rotated copy of self - """ - - @abstractmethod - def translate(self, translation: torch.Tensor, in_place: bool) -> AbstractState: - """Translate the state by the given tranlation - Args: - translation: translation vector in 2 dimensions - in_place: wether to change the object itself or return a rotated copy - """ - - # Define overloading operators to behave as a tensor for some operations - def __getitem__(self, key) -> AbstractState: - """ - Use get item on the underlying tensor to get the item at the given key. - Allways returns a velocity state so that if the underlying time sequence is reduced to one step, the velocity is still accessible. - """ - if isinstance(key, int): - key = (key, Ellipsis, slice(None, None, None)) - elif Ellipsis not in key: - key = (*key, Ellipsis, slice(None, None, None)) - else: - key = (*key, slice(None, None, None)) - - return to_state( - torch.cat( - ( - self.position[key], - self.velocity[key], - ), - dim=-1, - ), - self.dt, - ) - - @property - def shape(self): - return self._states.shape[:-1] - - -def to_state(in_tensor: torch.Tensor, dt: float) -> AbstractState: - if in_tensor.shape[-1] == 2: - return PositionSequenceState(in_tensor, dt) - elif in_tensor.shape[-1] == 4: - return PositionVelocityState(in_tensor, dt) - else: - assert in_tensor.shape[-1] > 4 - return PositionAngleVelocityState(in_tensor, dt) - - -class PositionSequenceState(AbstractState): - """ - State representation with an underlying tensor defining only positions. - """ - - def __init__(self, states: torch.Tensor, dt: float) -> None: - super().__init__() - assert ( - states.shape[-1] == 2 - ) # Check that the input tensor defines only the position - assert ( - states.ndim > 1 and states.shape[-2] > 1 - ) # Check that the input tensor defines a sequence of positions (otherwise velocity cannot be computed) - self.dt = dt - self._states = states.clone() - - @property - def position(self) -> torch.Tensor: - return self._states - - @property - def velocity(self) -> torch.Tensor: - vel = (self._states[..., 1:, :] - self._states[..., :-1, :]) / self.dt - vel = torch.cat((vel[..., 0:1, :], vel), dim=-2) - return vel.clone() - - @property - def angle(self) -> torch.Tensor: - vel = self.velocity - angle = torch.arctan2(vel[..., 1:2], vel[..., 0:1]) - return angle - - def get_states(self, dim: int = 2) -> torch.Tensor: - if dim == 2: - return self._states.clone() - elif dim == 4: - return torch.cat((self._states.clone(), self.velocity), dim=-1) - elif dim == 5: - return torch.cat((self._states.clone(), self.angle, self.velocity), dim=-1) - else: - raise RuntimeError(f"State dimension must be either 2, 4, or 5. Got {dim}") - - def rotate(self, angle: float, in_place: bool = False) -> PositionSequenceState: - """Rotate the state by the given angle in radiants""" - rot_matrix = get_rotation_matrix(angle, self._states.device) - if in_place: - self._states = (rot_matrix @ self._states.unsqueeze(-1)).squeeze(-1) - return self - else: - return to_state( - (rot_matrix @ self._states.unsqueeze(-1).clone()).squeeze(-1), self.dt - ) - - def translate( - self, translation: torch.Tensor, in_place: bool = False - ) -> PositionSequenceState: - """Translate the state by the given tranlation""" - if in_place: - self._states[..., :2] += translation.expand_as(self._states[..., :2]) - return self - else: - return to_state( - self._states[..., :2].clone() - + translation.expand_as(self._states[..., :2]), - self.dt, - ) - - -class PositionVelocityState(AbstractState): - """ - State representation with an underlying tensor defining position and velocity. - """ - - def __init__(self, states: torch.Tensor, dt) -> None: - super().__init__() - assert states.shape[-1] == 4 - self._states = states.clone() - self.dt = dt - - @property - def position(self) -> torch.Tensor: - return self._states[..., :2] - - @property - def velocity(self) -> torch.Tensor: - return self._states[..., 2:4] - - @property - def angle(self) -> torch.Tensor: - vel = self.velocity - angle = torch.arctan2(vel[..., 1:2], vel[..., 0:1]) - return angle - - def get_states(self, dim: int = 4) -> torch.Tensor: - if dim == 2: - return self._states[..., :2].clone() - elif dim == 4: - return self._states.clone() - elif dim == 5: - return torch.cat( - ( - self._states[..., :2].clone(), - self.angle, - self._states[..., 2:].clone(), - ), - dim=-1, - ) - else: - raise RuntimeError(f"State dimension must be either 2, 4, or 5. Got {dim}") - - def rotate( - self, angle: torch.Tensor, in_place: bool = False - ) -> PositionVelocityState: - """Rotate the state by the given angle in radiants""" - rot_matrix = get_rotation_matrix(angle, self._states.device) - rotated_pos = (rot_matrix @ self.position.unsqueeze(-1)).squeeze(-1) - rotated_vel = (rot_matrix @ self.velocity.unsqueeze(-1)).squeeze(-1) - if in_place: - self._states = torch.cat((rotated_pos, rotated_vel), dim=-1) - return self - else: - return to_state(torch.cat((rotated_pos, rotated_vel), dim=-1), self.dt) - - def translate( - self, translation: torch.Tensor, in_place: bool = False - ) -> PositionVelocityState: - """Translate the state by the given tranlation""" - if in_place: - self._states[..., :2] += translation.expand_as(self._states[..., :2]) - return self - else: - return to_state( - torch.cat( - ( - self._states[..., :2].clone() - + translation.expand_as(self._states[..., :2]), - self._states[..., 2:].clone(), - ), - dim=-1, - ), - self.dt, - ) - - -class PositionAngleVelocityState(AbstractState): - """ - State representation with an underlying tensor representing position angle and velocity. - """ - - def __init__(self, states: torch.Tensor, dt: float) -> None: - super().__init__() - assert states.shape[-1] == 5 - self._states = states.clone() - self.dt = dt - - @property - def position(self) -> torch.Tensor: - return self._states[..., :2].clone() - - @property - def velocity(self) -> torch.Tensor: - return self._states[..., 3:5].clone() - - @property - def angle(self) -> torch.Tensor: - return self._states[..., 2:3].clone() - - def get_states(self, dim: int = 5) -> torch.Tensor: - if dim == 2: - return self._states[..., :2].clone() - elif dim == 4: - return torch.cat( - (self._states[..., :2].clone(), self._states[..., 3:].clone()), dim=-1 - ) - elif dim == 5: - return self._states.clone() - else: - raise RuntimeError(f"State dimension must be either 2, 4, or 5. Got {dim}") - - def rotate( - self, angle: float, in_place: bool = False - ) -> PositionAngleVelocityState: - """Rotate the state by the given angle in radiants""" - rot_matrix = get_rotation_matrix(angle, self._states.device) - rotated_pos = (rot_matrix @ self.position.unsqueeze(-1)).squeeze(-1) - rotated_angle = self.angle + angle - rotated_vel = (rot_matrix @ self.velocity.unsqueeze(-1)).squeeze(-1) - if in_place: - self._states = torch.cat(rotated_pos, rotated_angle, rotated_vel, -1) - return self - else: - return to_state( - torch.cat(rotated_pos, rotated_angle, rotated_vel, -1), self.dt - ) - - def translate( - self, translation: torch.Tensor, in_place: bool = False - ) -> PositionAngleVelocityState: - """Translate the state by the given tranlation""" - if in_place: - self._states[..., :2] += translation.expand_as(self._states[..., :2]) - return self - else: - return to_state( - torch.cat( - ( - self._states[..., :2] - + translation.expand_as(self._states[..., :2]), - self._states[..., 2:], - ), - dim=-1, - ), - self.dt, - ) - - -def get_interaction_cost( - ego_state_future: AbstractState, - ado_state_future_samples: AbstractState, - interaction_cost_function: BaseCostTorch, -) -> torch.Tensor: - """Computes interaction cost samples from predicted ado future trajectories and a batch of ego - future trajectories - - Args: - ego_state_future: ((num_control_samples), num_agents, num_steps_future) ego state future - future trajectory - ado_state_future_samples: (num_prediction_samples, num_agents, num_steps_future) - predicted ado state trajectory samples - interaction_cost_function: interaction cost function between ego and (stochastic) ado - dt: time differential between two discrete timesteps in seconds - - Returns: - (num_control_samples, num_agents, num_prediction_samples) interaction cost tensor - """ - if len(ego_state_future.shape) == 2: - x_ego = ego_state_future.position.unsqueeze(0) - v_ego = ego_state_future.velocity.unsqueeze(0) - else: - x_ego = ego_state_future.position - v_ego = ego_state_future.velocity - - num_control_samples = ego_state_future.shape[0] - ado_position_future_samples = ado_state_future_samples.position.unsqueeze(0).expand( - num_control_samples, -1, -1, -1, -1 - ) - - v_samples = ado_state_future_samples.velocity.unsqueeze(0).expand( - num_control_samples, -1, -1, -1, -1 - ) - - interaction_cost, _ = interaction_cost_function( - x1=x_ego.unsqueeze(1), - x2=ado_position_future_samples, - v1=v_ego.unsqueeze(1), - v2=v_samples, - ) - return interaction_cost.permute(0, 2, 1) - - -def evaluate_risk( - risk_level: float, - cost: torch.Tensor, - weights: torch.Tensor, - risk_estimator: Optional[AbstractMonteCarloRiskEstimator] = None, -) -> torch.Tensor: - """Returns a risk tensor given costs and optionally a risk level - - Args: - risk_level (optional): a risk-level float. If 0.0, risk-neutral expectation will be - returned. Defaults to 0.0. - cost: (num_control_samples, num_agents, num_prediction_samples) cost tensor - weights: (num_control_samples, num_agents, num_prediction_samples) probability weight of the cost tensor - risk_estimator (optional): a Monte Carlo risk estimator. Defaults to None. - - Returns: - (num_control_samples, num_agents) risk tensor - """ - num_control_samples, num_agents, _ = cost.shape - - if risk_level == 0.0: - risk = cost.mean(dim=-1) - else: - assert risk_estimator is not None, "no risk estimator is specified" - risk = risk_estimator( - risk_level * torch.ones(num_control_samples, num_agents), - cost, - weights=weights, - ) - return risk - - -def evaluate_control_sequence( - control_sequence: torch.Tensor, - dynamics_model, - ego_state_history: AbstractState, - ego_state_target_trajectory: AbstractState, - ado_state_future_samples: AbstractState, - sample_weights: torch.Tensor, - interaction_cost_function: BaseCostTorch, - tracking_cost_function: TrackingCost, - risk_level: float = 0.0, - risk_estimator: Optional[AbstractMonteCarloRiskEstimator] = None, -) -> Tuple[float, float]: - """Returns the risk and tracking cost evaluation of the given control sequence - - Args: - control_sequence: (num_steps_future, control_dim) tensor of control sequence - dynamics_model: dynamics model for control - ego_state_target_trajectory: (num_steps_future) tensor of ego target - state trajectory - ado_state_future_samples: (num_prediction_samples, num_agents, num_steps_future) - of predicted ado trajectory samples states - sample_weights: (num_prediction_samples, num_agents) tensor of probability weights of the samples - intraction_cost_function: interaction cost function between ego and (stochastic) ado - tracking_cost_function: deterministic tracking cost that does not involve ado - risk_level: risk_level (optional): a risk-level float. If 0.0, risk-neutral expectation - is used. Defaults to 0.0. - risk_estimator (optional): a Monte Carlo risk estimator. Defaults to None. - - Returns: - tuple of (interaction risk, tracking_cost) - """ - ego_state_current = ego_state_history[..., -1] - ego_state_future = dynamics_model.simulate(ego_state_current, control_sequence) - # state starts with x, y, angle, vx, vy - tracking_cost = tracking_cost_function( - ego_state_future.position, - ego_state_target_trajectory.position, - ego_state_target_trajectory.velocity, - ) - - interaction_cost = get_interaction_cost( - ego_state_future, - ado_state_future_samples, - interaction_cost_function, - ) - - interaction_risk = evaluate_risk( - risk_level, - interaction_cost, - sample_weights.permute(1, 0).unsqueeze(0).expand_as(interaction_cost), - risk_estimator, - ) - - # TODO: averaging over agents but we might want to reduce a different way - return (interaction_risk.mean().item(), tracking_cost.mean().item()) diff --git a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/detectron2/structures/instances.py b/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/detectron2/structures/instances.py deleted file mode 100644 index 612e66f527397b0e940d716f4ad4f799b962954a..0000000000000000000000000000000000000000 --- a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/detectron2/structures/instances.py +++ /dev/null @@ -1,192 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import itertools -from typing import Any, Dict, List, Tuple, Union -import torch - - -class Instances: - """ - This class represents a list of instances in an image. - It stores the attributes of instances (e.g., boxes, masks, labels, scores) as "fields". - All fields must have the same ``__len__`` which is the number of instances. - - All other (non-field) attributes of this class are considered private: - they must start with '_' and are not modifiable by a user. - - Some basic usage: - - 1. Set/get/check a field: - - .. code-block:: python - - instances.gt_boxes = Boxes(...) - print(instances.pred_masks) # a tensor of shape (N, H, W) - print('gt_masks' in instances) - - 2. ``len(instances)`` returns the number of instances - 3. Indexing: ``instances[indices]`` will apply the indexing on all the fields - and returns a new :class:`Instances`. - Typically, ``indices`` is a integer vector of indices, - or a binary mask of length ``num_instances`` - - .. code-block:: python - - category_3_detections = instances[instances.pred_classes == 3] - confident_detections = instances[instances.scores > 0.9] - """ - - def __init__(self, image_size: Tuple[int, int], **kwargs: Any): - """ - Args: - image_size (height, width): the spatial size of the image. - kwargs: fields to add to this `Instances`. - """ - self._image_size = image_size - self._fields: Dict[str, Any] = {} - for k, v in kwargs.items(): - self.set(k, v) - - @property - def image_size(self) -> Tuple[int, int]: - """ - Returns: - tuple: height, width - """ - return self._image_size - - def __setattr__(self, name: str, val: Any) -> None: - if name.startswith("_"): - super().__setattr__(name, val) - else: - self.set(name, val) - - def __getattr__(self, name: str) -> Any: - if name == "_fields" or name not in self._fields: - raise AttributeError("Cannot find field '{}' in the given Instances!".format(name)) - return self._fields[name] - - def set(self, name: str, value: Any) -> None: - """ - Set the field named `name` to `value`. - The length of `value` must be the number of instances, - and must agree with other existing fields in this object. - """ - data_len = len(value) - if len(self._fields): - assert ( - len(self) == data_len - ), "Adding a field of length {} to a Instances of length {}".format(data_len, len(self)) - self._fields[name] = value - - def has(self, name: str) -> bool: - """ - Returns: - bool: whether the field called `name` exists. - """ - return name in self._fields - - def remove(self, name: str) -> None: - """ - Remove the field called `name`. - """ - del self._fields[name] - - def get(self, name: str) -> Any: - """ - Returns the field called `name`. - """ - return self._fields[name] - - def get_fields(self) -> Dict[str, Any]: - """ - Returns: - dict: a dict which maps names (str) to data of the fields - - Modifying the returned dict will modify this instance. - """ - return self._fields - - # Tensor-like methods - def to(self, *args: Any, **kwargs: Any) -> "Instances": - """ - Returns: - Instances: all fields are called with a `to(device)`, if the field has this method. - """ - ret = Instances(self._image_size) - for k, v in self._fields.items(): - if hasattr(v, "to"): - v = v.to(*args, **kwargs) - ret.set(k, v) - return ret - - def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Instances": - """ - Args: - item: an index-like object and will be used to index all the fields. - - Returns: - If `item` is a string, return the data in the corresponding field. - Otherwise, returns an `Instances` where all fields are indexed by `item`. - """ - if type(item) == int: - if item >= len(self) or item < -len(self): - raise IndexError("Instances index out of range!") - else: - item = slice(item, None, len(self)) - - ret = Instances(self._image_size) - for k, v in self._fields.items(): - ret.set(k, v[item]) - return ret - - def __len__(self) -> int: - for v in self._fields.values(): - # use __len__ because len() has to be int and is not friendly to tracing - return v.__len__() - raise NotImplementedError("Empty Instances does not support __len__!") - - def __iter__(self): - raise NotImplementedError("`Instances` object is not iterable!") - - @staticmethod - def cat(instance_lists: List["Instances"]) -> "Instances": - """ - Args: - instance_lists (list[Instances]) - - Returns: - Instances - """ - assert all(isinstance(i, Instances) for i in instance_lists) - assert len(instance_lists) > 0 - if len(instance_lists) == 1: - return instance_lists[0] - - image_size = instance_lists[0].image_size - if not isinstance(image_size, torch.Tensor): # could be a tensor in tracing - for i in instance_lists[1:]: - assert i.image_size == image_size - ret = Instances(image_size) - for k in instance_lists[0]._fields.keys(): - values = [i.get(k) for i in instance_lists] - v0 = values[0] - if isinstance(v0, torch.Tensor): - values = torch.cat(values, dim=0) - elif isinstance(v0, list): - values = list(itertools.chain(*values)) - elif hasattr(type(v0), "cat"): - values = type(v0).cat(values) - else: - raise ValueError("Unsupported type {} for concatenation".format(type(v0))) - ret.set(k, values) - return ret - - def __str__(self) -> str: - s = self.__class__.__name__ + "(" - s += "num_instances={}, ".format(len(self)) - s += "image_height={}, ".format(self._image_size[0]) - s += "image_width={}, ".format(self._image_size[1]) - s += "fields=[{}])".format(", ".join((f"{k}: {v}" for k, v in self._fields.items()))) - return s - - __repr__ = __str__ diff --git a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/docker/Dockerfile b/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/docker/Dockerfile deleted file mode 100644 index 4eec16dd0beac8b80c5446c9dd6cf15feaf87303..0000000000000000000000000000000000000000 --- a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/docker/Dockerfile +++ /dev/null @@ -1,47 +0,0 @@ -FROM nvidia/cuda:11.1.1-cudnn8-devel-ubuntu18.04 -# use an older system (18.04) to avoid opencv incompatibility (issue#3524) - -ENV DEBIAN_FRONTEND noninteractive -RUN apt-get update && apt-get install -y \ - python3-opencv ca-certificates python3-dev git wget sudo ninja-build -RUN ln -sv /usr/bin/python3 /usr/bin/python - -# create a non-root user -ARG USER_ID=1000 -RUN useradd -m --no-log-init --system --uid ${USER_ID} appuser -g sudo -RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers -USER appuser -WORKDIR /home/appuser - -ENV PATH="/home/appuser/.local/bin:${PATH}" -RUN wget https://bootstrap.pypa.io/get-pip.py && \ - python3 get-pip.py --user && \ - rm get-pip.py - -# install dependencies -# See https://pytorch.org/ for other options if you use a different version of CUDA -RUN pip install --user tensorboard cmake # cmake from apt-get is too old -RUN pip install --user torch==1.10 torchvision==0.11.1 -f https://download.pytorch.org/whl/cu111/torch_stable.html - -RUN pip install --user 'git+https://github.com/facebookresearch/fvcore' -# install detectron2 -RUN git clone https://github.com/facebookresearch/detectron2 detectron2_repo -# set FORCE_CUDA because during `docker build` cuda is not accessible -ENV FORCE_CUDA="1" -# This will by default build detectron2 for all common cuda architectures and take a lot more time, -# because inside `docker build`, there is no way to tell which architecture will be used. -ARG TORCH_CUDA_ARCH_LIST="Kepler;Kepler+Tesla;Maxwell;Maxwell+Tegra;Pascal;Volta;Turing" -ENV TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST}" - -RUN pip install --user -e detectron2_repo - -# Set a fixed model cache directory. -ENV FVCORE_CACHE="/tmp" -WORKDIR /home/appuser/detectron2_repo - -# run detectron2 under user "appuser": -# wget http://images.cocodataset.org/val2017/000000439715.jpg -O input.jpg -# python3 demo/demo.py \ - #--config-file configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \ - #--input input.jpg --output outputs/ \ - #--opts MODEL.WEIGHTS detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl diff --git a/spaces/Vasanthgx/Pet_Classifier_vasanth/app.py b/spaces/Vasanthgx/Pet_Classifier_vasanth/app.py deleted file mode 100644 index a058d698f6713f5adf74e893813b1b94494f2a96..0000000000000000000000000000000000000000 --- a/spaces/Vasanthgx/Pet_Classifier_vasanth/app.py +++ /dev/null @@ -1,19 +0,0 @@ -from fastai.vision.all import* -import gradio as gr -import timm - -learn = load_learner('model_convnext.pkl') - -categories = learn.dls.vocab - -def classify_img(img): - pred,idx,probs= learn.predict(img) - return dict(zip(categories,map(float,probs))) - -image = gr.inputs.Image(shape=(192, 192)) -label = gr.outputs.Label() -examples = ['basset.jpg','dog_saint_bernard.jpg','cat_russian_blue.jpg','cat_bombay.jpg','cat_british_shorthair.jpg','dog_chiihuahua.jpg','dog_basenji.jpg', 'cat_abyssinian.jpg', 'dog_frenchBulldog.jpg','dog_english_crocker_spaniel.jpg'] - -intf = gr.Interface(fn = classify_img, inputs = image, outputs = label, examples = examples) -intf.launch(inline =False) - diff --git a/spaces/Vijish/Image_generator/README.md b/spaces/Vijish/Image_generator/README.md deleted file mode 100644 index f0c1a7ed3d1d538791885f0af70efd60780a93a3..0000000000000000000000000000000000000000 --- a/spaces/Vijish/Image_generator/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Image Generator -emoji: 🐠 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 3.24.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/VoiceHero69/changer/webui/modules/implementations/rvc/utils.py b/spaces/VoiceHero69/changer/webui/modules/implementations/rvc/utils.py deleted file mode 100644 index 5617e363e2dd13bb18bb811a427026874b16cd5b..0000000000000000000000000000000000000000 --- a/spaces/VoiceHero69/changer/webui/modules/implementations/rvc/utils.py +++ /dev/null @@ -1,143 +0,0 @@ -import os -import traceback -from collections import OrderedDict - -import torch - - -def savee(ckpt, sr, if_f0, name, epoch, version): - try: - opt = OrderedDict() - opt["weight"] = {} - for key in ckpt.keys(): - if "enc_q" in key: - continue - opt["weight"][key] = ckpt[key].half() - if sr == "40k": - opt["config"] = [ - 1025, - 32, - 192, - 192, - 768, - 2, - 6, - 3, - 0, - "1", - [3, 7, 11], - [[1, 3, 5], [1, 3, 5], [1, 3, 5]], - [10, 10, 2, 2], - 512, - [16, 16, 4, 4], - 109, - 256, - 40000, - ] - elif sr == "48k": - opt["config"] = [ - 1025, - 32, - 192, - 192, - 768, - 2, - 6, - 3, - 0, - "1", - [3, 7, 11], - [[1, 3, 5], [1, 3, 5], [1, 3, 5]], - [10, 6, 2, 2, 2], - 512, - [16, 16, 4, 4, 4], - 109, - 256, - 48000, - ] - elif sr == "32k": - opt["config"] = [ - 513, - 32, - 192, - 192, - 768, - 2, - 6, - 3, - 0, - "1", - [3, 7, 11], - [[1, 3, 5], [1, 3, 5], [1, 3, 5]], - [10, 4, 2, 2, 2], - 512, - [16, 16, 4, 4, 4], - 109, - 256, - 32000, - ] - opt["info"] = "%sepoch" % epoch - opt["sr"] = sr - opt["f0"] = if_f0 - opt["version"] = version - os.makedirs(os.path.dirname(name), exist_ok=True) - torch.save(opt, name) - return "Success." - except: - return traceback.format_exc() - - -def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path): - if hasattr(model, "module"): - state_dict = model.module.state_dict() - else: - state_dict = model.state_dict() - os.makedirs(os.path.dirname(checkpoint_path), exist_ok=True) - torch.save( - { - "model": state_dict, - "iteration": iteration, - "optimizer": optimizer.state_dict(), - "learning_rate": learning_rate, - }, - checkpoint_path, - ) - - -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: - print( - "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()) - 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) - - 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() - return model, optimizer, learning_rate, iteration \ No newline at end of file diff --git a/spaces/WZT/DigiProj/train.py b/spaces/WZT/DigiProj/train.py deleted file mode 100644 index 2c07e38f97cde2afc43a7f43e7ac8e44ba9c02ca..0000000000000000000000000000000000000000 --- a/spaces/WZT/DigiProj/train.py +++ /dev/null @@ -1,458 +0,0 @@ -import argparse -import math -import random -import os -from util import * -import numpy as np -import torch -torch.backends.cudnn.benchmark = True -from torch import nn, autograd -from torch import optim -from torch.nn import functional as F -from torch.utils import data -import torch.distributed as dist - -from torchvision import transforms, utils -from tqdm import tqdm -from torch.optim import lr_scheduler -import copy -import kornia.augmentation as K -import kornia -import lpips - -from model import * -from dataset import ImageFolder -from distributed import ( - get_rank, - synchronize, - reduce_loss_dict, - reduce_sum, - get_world_size, -) - -mse_criterion = nn.MSELoss() - - -def test(args, genA2B, genB2A, testA_loader, testB_loader, name, step): - testA_loader = iter(testA_loader) - testB_loader = iter(testB_loader) - with torch.no_grad(): - test_sample_num = 16 - - genA2B.eval(), genB2A.eval() - A2B = [] - B2A = [] - for i in range(test_sample_num): - real_A = testA_loader.next() - real_B = testB_loader.next() - - real_A, real_B = real_A.cuda(), real_B.cuda() - - A2B_content, A2B_style = genA2B.encode(real_A) - B2A_content, B2A_style = genB2A.encode(real_B) - - if i % 2 == 0: - A2B_mod1 = torch.randn([1, args.latent_dim]).cuda() - B2A_mod1 = torch.randn([1, args.latent_dim]).cuda() - A2B_mod2 = torch.randn([1, args.latent_dim]).cuda() - B2A_mod2 = torch.randn([1, args.latent_dim]).cuda() - - fake_B2B, _, _ = genA2B(real_B) - fake_A2A, _, _ = genB2A(real_A) - - colsA = [real_A, fake_A2A] - colsB = [real_B, fake_B2B] - - fake_A2B_1 = genA2B.decode(A2B_content, A2B_mod1) - fake_B2A_1 = genB2A.decode(B2A_content, B2A_mod1) - - fake_A2B_2 = genA2B.decode(A2B_content, A2B_mod2) - fake_B2A_2 = genB2A.decode(B2A_content, B2A_mod2) - - fake_A2B_3 = genA2B.decode(A2B_content, B2A_style) - fake_B2A_3 = genB2A.decode(B2A_content, A2B_style) - - colsA += [fake_A2B_3, fake_A2B_1, fake_A2B_2] - colsB += [fake_B2A_3, fake_B2A_1, fake_B2A_2] - - fake_A2B2A, _, _ = genB2A(fake_A2B_3, A2B_style) - fake_B2A2B, _, _ = genA2B(fake_B2A_3, B2A_style) - colsA.append(fake_A2B2A) - colsB.append(fake_B2A2B) - - fake_A2B2A, _, _ = genB2A(fake_A2B_1, A2B_style) - fake_B2A2B, _, _ = genA2B(fake_B2A_1, B2A_style) - colsA.append(fake_A2B2A) - colsB.append(fake_B2A2B) - - fake_A2B2A, _, _ = genB2A(fake_A2B_2, A2B_style) - fake_B2A2B, _, _ = genA2B(fake_B2A_2, B2A_style) - colsA.append(fake_A2B2A) - colsB.append(fake_B2A2B) - - fake_A2B2A, _, _ = genB2A(fake_A2B_1) - fake_B2A2B, _, _ = genA2B(fake_B2A_1) - colsA.append(fake_A2B2A) - colsB.append(fake_B2A2B) - - colsA = torch.cat(colsA, 2).detach().cpu() - colsB = torch.cat(colsB, 2).detach().cpu() - - A2B.append(colsA) - B2A.append(colsB) - A2B = torch.cat(A2B, 0) - B2A = torch.cat(B2A, 0) - - utils.save_image(A2B, f'{im_path}/{name}_A2B_{str(step).zfill(6)}.jpg', normalize=True, range=(-1, 1), nrow=16) - utils.save_image(B2A, f'{im_path}/{name}_B2A_{str(step).zfill(6)}.jpg', normalize=True, range=(-1, 1), nrow=16) - - genA2B.train(), genB2A.train() - - -def train(args, trainA_loader, trainB_loader, testA_loader, testB_loader, G_A2B, G_B2A, D_A, D_B, G_optim, D_optim, device): - G_A2B.train(), G_B2A.train(), D_A.train(), D_B.train() - trainA_loader = sample_data(trainA_loader) - trainB_loader = sample_data(trainB_loader) - G_scheduler = lr_scheduler.StepLR(G_optim, step_size=100000, gamma=0.5) - D_scheduler = lr_scheduler.StepLR(D_optim, step_size=100000, gamma=0.5) - - pbar = range(args.iter) - - if get_rank() == 0: - pbar = tqdm(pbar, initial=args.start_iter, dynamic_ncols=True, smoothing=0.1) - - loss_dict = {} - mean_path_length_A2B = 0 - mean_path_length_B2A = 0 - - if args.distributed: - G_A2B_module = G_A2B.module - G_B2A_module = G_B2A.module - D_A_module = D_A.module - D_B_module = D_B.module - D_L_module = D_L.module - - else: - G_A2B_module = G_A2B - G_B2A_module = G_B2A - D_A_module = D_A - D_B_module = D_B - D_L_module = D_L - - for idx in pbar: - i = idx + args.start_iter - - if i > args.iter: - print('Done!') - break - - ori_A = next(trainA_loader) - ori_B = next(trainB_loader) - if isinstance(ori_A, list): - ori_A = ori_A[0] - if isinstance(ori_B, list): - ori_B = ori_B[0] - - ori_A = ori_A.to(device) - ori_B = ori_B.to(device) - aug_A = aug(ori_A) - aug_B = aug(ori_B) - A = aug(ori_A[[np.random.randint(args.batch)]].expand_as(ori_A)) - B = aug(ori_B[[np.random.randint(args.batch)]].expand_as(ori_B)) - - if i % args.d_reg_every == 0: - aug_A.requires_grad = True - aug_B.requires_grad = True - - A2B_content, A2B_style = G_A2B.encode(A) - B2A_content, B2A_style = G_B2A.encode(B) - - # get new style - aug_A2B_style = G_B2A.style_encode(aug_B) - aug_B2A_style = G_A2B.style_encode(aug_A) - rand_A2B_style = torch.randn([args.batch, args.latent_dim]).to(device).requires_grad_() - rand_B2A_style = torch.randn([args.batch, args.latent_dim]).to(device).requires_grad_() - - # styles - idx = torch.randperm(2*args.batch) - input_A2B_style = torch.cat([rand_A2B_style, aug_A2B_style], 0)[idx][:args.batch] - - idx = torch.randperm(2*args.batch) - input_B2A_style = torch.cat([rand_B2A_style, aug_B2A_style], 0)[idx][:args.batch] - - fake_A2B = G_A2B.decode(A2B_content, input_A2B_style) - fake_B2A = G_B2A.decode(B2A_content, input_B2A_style) - - - # train disc - real_A_logit = D_A(aug_A) - real_B_logit = D_B(aug_B) - real_L_logit1 = D_L(rand_A2B_style) - real_L_logit2 = D_L(rand_B2A_style) - - fake_B_logit = D_B(fake_A2B.detach()) - fake_A_logit = D_A(fake_B2A.detach()) - fake_L_logit1 = D_L(aug_A2B_style.detach()) - fake_L_logit2 = D_L(aug_B2A_style.detach()) - - # global loss - D_loss = d_logistic_loss(real_A_logit, fake_A_logit) +\ - d_logistic_loss(real_B_logit, fake_B_logit) +\ - d_logistic_loss(real_L_logit1, fake_L_logit1) +\ - d_logistic_loss(real_L_logit2, fake_L_logit2) - - loss_dict['D_adv'] = D_loss - - if i % args.d_reg_every == 0: - r1_A_loss = d_r1_loss(real_A_logit, aug_A) - r1_B_loss = d_r1_loss(real_B_logit, aug_B) - r1_L_loss = d_r1_loss(real_L_logit1, rand_A2B_style) + d_r1_loss(real_L_logit2, rand_B2A_style) - r1_loss = r1_A_loss + r1_B_loss + r1_L_loss - D_r1_loss = (args.r1 / 2 * r1_loss * args.d_reg_every) - D_loss += D_r1_loss - - D_optim.zero_grad() - D_loss.backward() - D_optim.step() - - #Generator - # adv loss - fake_B_logit = D_B(fake_A2B) - fake_A_logit = D_A(fake_B2A) - fake_L_logit1 = D_L(aug_A2B_style) - fake_L_logit2 = D_L(aug_B2A_style) - - lambda_adv = (1, 1, 1) - G_adv_loss = 1 * (g_nonsaturating_loss(fake_A_logit, lambda_adv) +\ - g_nonsaturating_loss(fake_B_logit, lambda_adv) +\ - 2*g_nonsaturating_loss(fake_L_logit1, (1,)) +\ - 2*g_nonsaturating_loss(fake_L_logit2, (1,))) - - # style consis loss - G_con_loss = 50 * (A2B_style.var(0, unbiased=False).sum() + B2A_style.var(0, unbiased=False).sum()) - - # cycle recon - A2B2A_content, A2B2A_style = G_B2A.encode(fake_A2B) - B2A2B_content, B2A2B_style = G_A2B.encode(fake_B2A) - fake_A2B2A = G_B2A.decode(A2B2A_content, shuffle_batch(A2B_style)) - fake_B2A2B = G_A2B.decode(B2A2B_content, shuffle_batch(B2A_style)) - - G_cycle_loss = 20 * (F.mse_loss(fake_A2B2A, A) + F.mse_loss(fake_B2A2B, B)) - lpips_loss = 10 * (lpips_fn(fake_A2B2A, A).mean() + lpips_fn(fake_B2A2B, B).mean()) #10 for anime - - # style reconstruction - G_style_loss = 5 * (mse_criterion(A2B2A_style, input_A2B_style) +\ - mse_criterion(B2A2B_style, input_B2A_style)) - - - G_loss = G_adv_loss + G_cycle_loss + G_con_loss + lpips_loss + G_style_loss - - loss_dict['G_adv'] = G_adv_loss - loss_dict['G_con'] = G_con_loss - loss_dict['G_cycle'] = G_cycle_loss - loss_dict['lpips'] = lpips_loss - - G_optim.zero_grad() - G_loss.backward() - G_optim.step() - - G_scheduler.step() - D_scheduler.step() - - accumulate(G_A2B_ema, G_A2B_module) - accumulate(G_B2A_ema, G_B2A_module) - - loss_reduced = reduce_loss_dict(loss_dict) - D_adv_loss_val = loss_reduced['D_adv'].mean().item() - - G_adv_loss_val = loss_reduced['G_adv'].mean().item() - G_cycle_loss_val = loss_reduced['G_cycle'].mean().item() - G_con_loss_val = loss_reduced['G_con'].mean().item() - lpips_val = loss_reduced['lpips'].mean().item() - - if get_rank() == 0: - pbar.set_description( - ( - f'Dadv: {D_adv_loss_val:.2f}; lpips: {lpips_val:.2f} ' - f'Gadv: {G_adv_loss_val:.2f}; Gcycle: {G_cycle_loss_val:.2f}; GMS: {G_con_loss_val:.2f} {G_style_loss.item():.2f}' - ) - ) - - if i % 1000 == 0: - with torch.no_grad(): - test(args, G_A2B, G_B2A, testA_loader, testB_loader, 'normal', i) - test(args, G_A2B_ema, G_B2A_ema, testA_loader, testB_loader, 'ema', i) - - if (i+1) % 2000 == 0: - torch.save( - { - 'G_A2B': G_A2B_module.state_dict(), - 'G_B2A': G_B2A_module.state_dict(), - 'G_A2B_ema': G_A2B_ema.state_dict(), - 'G_B2A_ema': G_B2A_ema.state_dict(), - 'D_A': D_A_module.state_dict(), - 'D_B': D_B_module.state_dict(), - 'D_L': D_L_module.state_dict(), - 'G_optim': G_optim.state_dict(), - 'D_optim': D_optim.state_dict(), - 'iter': i, - }, - os.path.join(model_path, 'ck.pt'), - ) - - -if __name__ == '__main__': - device = 'cuda' - - parser = argparse.ArgumentParser() - - parser.add_argument('--iter', type=int, default=300000) - parser.add_argument('--batch', type=int, default=4) - parser.add_argument('--n_sample', type=int, default=64) - parser.add_argument('--size', type=int, default=256) - parser.add_argument('--r1', type=float, default=10) - parser.add_argument('--lambda_cycle', type=int, default=1) - parser.add_argument('--path_regularize', type=float, default=2) - parser.add_argument('--path_batch_shrink', type=int, default=2) - parser.add_argument('--d_reg_every', type=int, default=16) - parser.add_argument('--g_reg_every', type=int, default=4) - parser.add_argument('--mixing', type=float, default=0.9) - parser.add_argument('--ckpt', type=str, default=None) - parser.add_argument('--lr', type=float, default=2e-3) - parser.add_argument('--local_rank', type=int, default=0) - parser.add_argument('--num_down', type=int, default=3) - parser.add_argument('--name', type=str, required=True) - parser.add_argument('--d_path', type=str, required=True) - parser.add_argument('--latent_dim', type=int, default=8) - parser.add_argument('--lr_mlp', type=float, default=0.01) - parser.add_argument('--n_res', type=int, default=1) - - args = parser.parse_args() - - n_gpu = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 - args.distributed = False - - if args.distributed: - torch.cuda.set_device(args.local_rank) - torch.distributed.init_process_group(backend='nccl', init_method='env://') - synchronize() - - save_path = f'./{args.name}' - im_path = os.path.join(save_path, 'sample') - model_path = os.path.join(save_path, 'checkpoint') - os.makedirs(im_path, exist_ok=True) - os.makedirs(model_path, exist_ok=True) - - args.n_mlp = 5 - - args.start_iter = 0 - - G_A2B = Generator( args.size, args.num_down, args.latent_dim, args.n_mlp, lr_mlp=args.lr_mlp, n_res=args.n_res).to(device) - D_A = Discriminator(args.size).to(device) - G_B2A = Generator( args.size, args.num_down, args.latent_dim, args.n_mlp, lr_mlp=args.lr_mlp, n_res=args.n_res).to(device) - D_B = Discriminator(args.size).to(device) - D_L = LatDiscriminator(args.latent_dim).to(device) - lpips_fn = lpips.LPIPS(net='vgg').to(device) - - G_A2B_ema = copy.deepcopy(G_A2B).to(device).eval() - G_B2A_ema = copy.deepcopy(G_B2A).to(device).eval() - - g_reg_ratio = args.g_reg_every / (args.g_reg_every + 1) - d_reg_ratio = args.d_reg_every / (args.d_reg_every + 1) - - G_optim = optim.Adam( list(G_A2B.parameters()) + list(G_B2A.parameters()), lr=args.lr, betas=(0, 0.99)) - D_optim = optim.Adam( - list(D_L.parameters()) + list(D_A.parameters()) + list(D_B.parameters()), - lr=args.lr, betas=(0**d_reg_ratio, 0.99**d_reg_ratio)) - - if args.ckpt is not None: - ckpt = torch.load(args.ckpt, map_location=lambda storage, loc: storage) - - try: - ckpt_name = os.path.basename(args.ckpt) - args.start_iter = int(os.path.splitext(ckpt_name)[0]) - - except ValueError: - pass - - G_A2B.load_state_dict(ckpt['G_A2B']) - G_B2A.load_state_dict(ckpt['G_B2A']) - G_A2B_ema.load_state_dict(ckpt['G_A2B_ema']) - G_B2A_ema.load_state_dict(ckpt['G_B2A_ema']) - D_A.load_state_dict(ckpt['D_A']) - D_B.load_state_dict(ckpt['D_B']) - D_L.load_state_dict(ckpt['D_L']) - - G_optim.load_state_dict(ckpt['G_optim']) - D_optim.load_state_dict(ckpt['D_optim']) - args.start_iter = ckpt['iter'] - - if args.distributed: - G_A2B = nn.parallel.DistributedDataParallel( - G_A2B, - device_ids=[args.local_rank], - output_device=args.local_rank, - broadcast_buffers=False, - ) - - D_A = nn.parallel.DistributedDataParallel( - D_A, - device_ids=[args.local_rank], - output_device=args.local_rank, - broadcast_buffers=False, - ) - - G_B2A = nn.parallel.DistributedDataParallel( - G_B2A, - device_ids=[args.local_rank], - output_device=args.local_rank, - broadcast_buffers=False, - ) - - D_B = nn.parallel.DistributedDataParallel( - D_B, - device_ids=[args.local_rank], - output_device=args.local_rank, - broadcast_buffers=False, - ) - D_L = nn.parallel.DistributedDataParallel( - D_L, - device_ids=[args.local_rank], - output_device=args.local_rank, - broadcast_buffers=False, - ) - train_transform = transforms.Compose([ - transforms.ToTensor(), - transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), inplace=True) - ]) - - test_transform = transforms.Compose([ - transforms.Resize((args.size, args.size)), - transforms.ToTensor(), - transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), inplace=True) - ]) - - aug = nn.Sequential( - K.RandomAffine(degrees=(-20,20), scale=(0.8, 1.2), translate=(0.1, 0.1), shear=0.15), - kornia.geometry.transform.Resize(256+30), - K.RandomCrop((256,256)), - K.RandomHorizontalFlip(), - ) - - - d_path = args.d_path - trainA = ImageFolder(os.path.join(d_path, 'trainA'), train_transform) - trainB = ImageFolder(os.path.join(d_path, 'trainB'), train_transform) - testA = ImageFolder(os.path.join(d_path, 'testA'), test_transform) - testB = ImageFolder(os.path.join(d_path, 'testB'), test_transform) - - trainA_loader = data.DataLoader(trainA, batch_size=args.batch, - sampler=data_sampler(trainA, shuffle=True, distributed=args.distributed), drop_last=True, pin_memory=True, num_workers=5) - trainB_loader = data.DataLoader(trainB, batch_size=args.batch, - sampler=data_sampler(trainB, shuffle=True, distributed=args.distributed), drop_last=True, pin_memory=True, num_workers=5) - - testA_loader = data.DataLoader(testA, batch_size=1, shuffle=False) - testB_loader = data.DataLoader(testB, batch_size=1, shuffle=False) - - - train(args, trainA_loader, trainB_loader, testA_loader, testB_loader, G_A2B, G_B2A, D_A, D_B, G_optim, D_optim, device) diff --git a/spaces/Yan233th/so-vits-svc-models/inference/infer_tool.py b/spaces/Yan233th/so-vits-svc-models/inference/infer_tool.py deleted file mode 100644 index 3a2635b99b780483f8b1eec2f7c180ff095ede5e..0000000000000000000000000000000000000000 --- a/spaces/Yan233th/so-vits-svc-models/inference/infer_tool.py +++ /dev/null @@ -1,251 +0,0 @@ -import hashlib -import io -import json -import logging -import os -import time -from pathlib import Path -from inference import slicer - -import librosa -import numpy as np -# import onnxruntime -import parselmouth -import soundfile -import torch -import torchaudio - -import cluster -from hubert import hubert_model -import utils -from models import SynthesizerTrn - -logging.getLogger('matplotlib').setLevel(logging.WARNING) - - -def read_temp(file_name): - if not os.path.exists(file_name): - with open(file_name, "w") as f: - f.write(json.dumps({"info": "temp_dict"})) - return {} - else: - try: - with open(file_name, "r") as f: - data = f.read() - data_dict = json.loads(data) - if os.path.getsize(file_name) > 50 * 1024 * 1024: - f_name = file_name.replace("\\", "/").split("/")[-1] - print(f"clean {f_name}") - for wav_hash in list(data_dict.keys()): - if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600: - del data_dict[wav_hash] - except Exception as e: - print(e) - print(f"{file_name} error,auto rebuild file") - data_dict = {"info": "temp_dict"} - return data_dict - - -def write_temp(file_name, data): - with open(file_name, "w") as f: - f.write(json.dumps(data)) - - -def timeit(func): - def run(*args, **kwargs): - t = time.time() - res = func(*args, **kwargs) - print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t)) - return res - - return run - - -def format_wav(audio_path): - if Path(audio_path).suffix == '.wav': - return - raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None) - soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate) - - -def get_end_file(dir_path, end): - file_lists = [] - for root, dirs, files in os.walk(dir_path): - files = [f for f in files if f[0] != '.'] - dirs[:] = [d for d in dirs if d[0] != '.'] - for f_file in files: - if f_file.endswith(end): - file_lists.append(os.path.join(root, f_file).replace("\\", "/")) - return file_lists - - -def get_md5(content): - return hashlib.new("md5", content).hexdigest() - -def fill_a_to_b(a, b): - if len(a) < len(b): - for _ in range(0, len(b) - len(a)): - a.append(a[0]) - -def mkdir(paths: list): - for path in paths: - if not os.path.exists(path): - os.mkdir(path) - -def pad_array(arr, target_length): - current_length = arr.shape[0] - if current_length >= target_length: - return arr - else: - pad_width = target_length - current_length - pad_left = pad_width // 2 - pad_right = pad_width - pad_left - padded_arr = np.pad(arr, (pad_left, pad_right), 'constant', constant_values=(0, 0)) - return padded_arr - - -class Svc(object): - def __init__(self, net_g_path, config_path, - device=None, - cluster_model_path="logs/44k/kmeans_10000.pt"): - self.net_g_path = net_g_path - if device is None: - self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") - else: - self.dev = torch.device(device) - self.net_g_ms = None - self.hps_ms = utils.get_hparams_from_file(config_path) - self.target_sample = self.hps_ms.data.sampling_rate - self.hop_size = self.hps_ms.data.hop_length - self.spk2id = self.hps_ms.spk - # 加载hubert - self.hubert_model = utils.get_hubert_model().to(self.dev) - self.load_model() - if os.path.exists(cluster_model_path): - self.cluster_model = cluster.get_cluster_model(cluster_model_path) - - def load_model(self): - # 获取模型配置 - self.net_g_ms = SynthesizerTrn( - self.hps_ms.data.filter_length // 2 + 1, - self.hps_ms.train.segment_size // self.hps_ms.data.hop_length, - **self.hps_ms.model) - _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None) - if "half" in self.net_g_path and torch.cuda.is_available(): - _ = self.net_g_ms.half().eval().to(self.dev) - else: - _ = self.net_g_ms.eval().to(self.dev) - - - - def get_unit_f0(self, in_path, tran, cluster_infer_ratio, speaker): - - wav, sr = librosa.load(in_path, sr=self.target_sample) - - f0 = utils.compute_f0_parselmouth(wav, sampling_rate=self.target_sample, hop_length=self.hop_size) - f0, uv = utils.interpolate_f0(f0) - f0 = torch.FloatTensor(f0) - uv = torch.FloatTensor(uv) - f0 = f0 * 2 ** (tran / 12) - f0 = f0.unsqueeze(0).to(self.dev) - uv = uv.unsqueeze(0).to(self.dev) - - wav16k = librosa.resample(wav, orig_sr=self.target_sample, target_sr=16000) - wav16k = torch.from_numpy(wav16k).to(self.dev) - c = utils.get_hubert_content(self.hubert_model, wav_16k_tensor=wav16k) - c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1]) - - if cluster_infer_ratio !=0: - cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T - cluster_c = torch.FloatTensor(cluster_c).to(self.dev) - c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c - - c = c.unsqueeze(0) - return c, f0, uv - - def infer(self, speaker, tran, raw_path, - cluster_infer_ratio=0, - auto_predict_f0=False, - noice_scale=0.4): - speaker_id = self.spk2id.__dict__.get(speaker) - if not speaker_id and type(speaker) is int: - if len(self.spk2id.__dict__) >= speaker: - speaker_id = speaker - sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0) - c, f0, uv = self.get_unit_f0(raw_path, tran, cluster_infer_ratio, speaker) - if "half" in self.net_g_path and torch.cuda.is_available(): - c = c.half() - with torch.no_grad(): - start = time.time() - audio = self.net_g_ms.infer(c, f0=f0, g=sid, uv=uv, predict_f0=auto_predict_f0, noice_scale=noice_scale)[0,0].data.float() - use_time = time.time() - start - print("vits use time:{}".format(use_time)) - return audio, audio.shape[-1] - - def clear_empty(self): - # 清理显存 - torch.cuda.empty_cache() - - def slice_inference(self,raw_audio_path, spk, tran, slice_db,cluster_infer_ratio, auto_predict_f0,noice_scale, pad_seconds=0.5): - wav_path = raw_audio_path - chunks = slicer.cut(wav_path, db_thresh=slice_db) - audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks) - - audio = [] - for (slice_tag, data) in audio_data: - print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======') - # padd - pad_len = int(audio_sr * pad_seconds) - data = np.concatenate([np.zeros([pad_len]), data, np.zeros([pad_len])]) - length = int(np.ceil(len(data) / audio_sr * self.target_sample)) - raw_path = io.BytesIO() - soundfile.write(raw_path, data, audio_sr, format="wav") - raw_path.seek(0) - if slice_tag: - print('jump empty segment') - _audio = np.zeros(length) - else: - out_audio, out_sr = self.infer(spk, tran, raw_path, - cluster_infer_ratio=cluster_infer_ratio, - auto_predict_f0=auto_predict_f0, - noice_scale=noice_scale - ) - _audio = out_audio.cpu().numpy() - - pad_len = int(self.target_sample * pad_seconds) - _audio = _audio[pad_len:-pad_len] - audio.extend(list(_audio)) - return np.array(audio) - - -class RealTimeVC: - def __init__(self): - self.last_chunk = None - self.last_o = None - self.chunk_len = 16000 # 区块长度 - self.pre_len = 3840 # 交叉淡化长度,640的倍数 - - """输入输出都是1维numpy 音频波形数组""" - - def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path): - import maad - audio, sr = torchaudio.load(input_wav_path) - audio = audio.cpu().numpy()[0] - temp_wav = io.BytesIO() - if self.last_chunk is None: - input_wav_path.seek(0) - audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path) - audio = audio.cpu().numpy() - self.last_chunk = audio[-self.pre_len:] - self.last_o = audio - return audio[-self.chunk_len:] - else: - audio = np.concatenate([self.last_chunk, audio]) - soundfile.write(temp_wav, audio, sr, format="wav") - temp_wav.seek(0) - audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav) - audio = audio.cpu().numpy() - ret = maad.util.crossfade(self.last_o, audio, self.pre_len) - self.last_chunk = audio[-self.pre_len:] - self.last_o = audio - return ret[self.chunk_len:2 * self.chunk_len] diff --git a/spaces/YanzBotz/YanzBotz-Models/lib/infer_pack/modules/F0Predictor/__init__.py b/spaces/YanzBotz/YanzBotz-Models/lib/infer_pack/modules/F0Predictor/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Yiqin/ChatVID/model/vision/grit_src/third_party/CenterNet2/configs/common/train.py b/spaces/Yiqin/ChatVID/model/vision/grit_src/third_party/CenterNet2/configs/common/train.py deleted file mode 100644 index b6ed02bd59f540ca58df20bf72d462f195210a32..0000000000000000000000000000000000000000 --- a/spaces/Yiqin/ChatVID/model/vision/grit_src/third_party/CenterNet2/configs/common/train.py +++ /dev/null @@ -1,18 +0,0 @@ -# Common training-related configs that are designed for "tools/lazyconfig_train_net.py" -# You can use your own instead, together with your own train_net.py -train = dict( - output_dir="./output", - init_checkpoint="", - max_iter=90000, - amp=dict(enabled=False), # options for Automatic Mixed Precision - ddp=dict( # options for DistributedDataParallel - broadcast_buffers=False, - find_unused_parameters=False, - fp16_compression=False, - ), - checkpointer=dict(period=5000, max_to_keep=100), # options for PeriodicCheckpointer - eval_period=5000, - log_period=20, - device="cuda" - # ... -) diff --git a/spaces/Yuliang/ECON/lib/common/libmesh/inside_mesh.py b/spaces/Yuliang/ECON/lib/common/libmesh/inside_mesh.py deleted file mode 100644 index 379e2bb0bf048044016b1512e3e270996cb939c7..0000000000000000000000000000000000000000 --- a/spaces/Yuliang/ECON/lib/common/libmesh/inside_mesh.py +++ /dev/null @@ -1,152 +0,0 @@ -import numpy as np -from .triangle_hash import TriangleHash as _TriangleHash - - -def check_mesh_contains(mesh, points, hash_resolution=512): - intersector = MeshIntersector(mesh, hash_resolution) - contains, hole_points = intersector.query(points) - return contains, hole_points - - -class MeshIntersector: - def __init__(self, mesh, resolution=512): - triangles = mesh.vertices[mesh.faces].astype(np.float64) - n_tri = triangles.shape[0] - - self.resolution = resolution - self.bbox_min = triangles.reshape(3 * n_tri, 3).min(axis=0) - self.bbox_max = triangles.reshape(3 * n_tri, 3).max(axis=0) - # Tranlate and scale it to [0.5, self.resolution - 0.5]^3 - self.scale = (resolution - 1) / (self.bbox_max - self.bbox_min) - self.translate = 0.5 - self.scale * self.bbox_min - - self._triangles = triangles = self.rescale(triangles) - # assert(np.allclose(triangles.reshape(-1, 3).min(0), 0.5)) - # assert(np.allclose(triangles.reshape(-1, 3).max(0), resolution - 0.5)) - - triangles2d = triangles[:, :, :2] - self._tri_intersector2d = TriangleIntersector2d(triangles2d, resolution) - - def query(self, points): - # Rescale points - points = self.rescale(points) - - # placeholder result with no hits we'll fill in later - contains = np.zeros(len(points), dtype=np.bool) - hole_points = np.zeros(len(points), dtype=np.bool) - - # cull points outside of the axis aligned bounding box - # this avoids running ray tests unless points are close - inside_aabb = np.all((0 <= points) & (points <= self.resolution), axis=1) - if not inside_aabb.any(): - return contains, hole_points - - # Only consider points inside bounding box - mask = inside_aabb - points = points[mask] - - # Compute intersection depth and check order - points_indices, tri_indices = self._tri_intersector2d.query(points[:, :2]) - - triangles_intersect = self._triangles[tri_indices] - points_intersect = points[points_indices] - - depth_intersect, abs_n_2 = self.compute_intersection_depth( - points_intersect, triangles_intersect - ) - - # Count number of intersections in both directions - smaller_depth = depth_intersect >= points_intersect[:, 2] * abs_n_2 - bigger_depth = depth_intersect < points_intersect[:, 2] * abs_n_2 - points_indices_0 = points_indices[smaller_depth] - points_indices_1 = points_indices[bigger_depth] - - nintersect0 = np.bincount(points_indices_0, minlength=points.shape[0]) - nintersect1 = np.bincount(points_indices_1, minlength=points.shape[0]) - - # Check if point contained in mesh - contains1 = (np.mod(nintersect0, 2) == 1) - contains2 = (np.mod(nintersect1, 2) == 1) - # if (contains1 != contains2).any(): - # print('Warning: contains1 != contains2 for some points.') - contains[mask] = (contains1 & contains2) - hole_points[mask] = np.logical_xor(contains1, contains2) - return contains, hole_points - - def compute_intersection_depth(self, points, triangles): - t1 = triangles[:, 0, :] - t2 = triangles[:, 1, :] - t3 = triangles[:, 2, :] - - v1 = t3 - t1 - v2 = t2 - t1 - # v1 = v1 / np.linalg.norm(v1, axis=-1, keepdims=True) - # v2 = v2 / np.linalg.norm(v2, axis=-1, keepdims=True) - - normals = np.cross(v1, v2) - alpha = np.sum(normals[:, :2] * (t1[:, :2] - points[:, :2]), axis=1) - - n_2 = normals[:, 2] - t1_2 = t1[:, 2] - s_n_2 = np.sign(n_2) - abs_n_2 = np.abs(n_2) - - mask = (abs_n_2 != 0) - - depth_intersect = np.full(points.shape[0], np.nan) - depth_intersect[mask] = \ - t1_2[mask] * abs_n_2[mask] + alpha[mask] * s_n_2[mask] - - # Test the depth: - # TODO: remove and put into tests - # points_new = np.concatenate([points[:, :2], depth_intersect[:, None]], axis=1) - # alpha = (normals * t1).sum(-1) - # mask = (depth_intersect == depth_intersect) - # assert(np.allclose((points_new[mask] * normals[mask]).sum(-1), - # alpha[mask])) - return depth_intersect, abs_n_2 - - def rescale(self, array): - array = self.scale * array + self.translate - return array - - -class TriangleIntersector2d: - def __init__(self, triangles, resolution=128): - self.triangles = triangles - self.tri_hash = _TriangleHash(triangles, resolution) - - def query(self, points): - point_indices, tri_indices = self.tri_hash.query(points) - point_indices = np.array(point_indices, dtype=np.int64) - tri_indices = np.array(tri_indices, dtype=np.int64) - points = points[point_indices] - triangles = self.triangles[tri_indices] - mask = self.check_triangles(points, triangles) - point_indices = point_indices[mask] - tri_indices = tri_indices[mask] - return point_indices, tri_indices - - def check_triangles(self, points, triangles): - contains = np.zeros(points.shape[0], dtype=np.bool) - A = triangles[:, :2] - triangles[:, 2:] - A = A.transpose([0, 2, 1]) - y = points - triangles[:, 2] - - detA = A[:, 0, 0] * A[:, 1, 1] - A[:, 0, 1] * A[:, 1, 0] - - mask = (np.abs(detA) != 0.) - A = A[mask] - y = y[mask] - detA = detA[mask] - - s_detA = np.sign(detA) - abs_detA = np.abs(detA) - - u = (A[:, 1, 1] * y[:, 0] - A[:, 0, 1] * y[:, 1]) * s_detA - v = (-A[:, 1, 0] * y[:, 0] + A[:, 0, 0] * y[:, 1]) * s_detA - - sum_uv = u + v - contains[mask] = ((0 < u) & (u < abs_detA) & (0 < v) & (v < abs_detA) & (0 < sum_uv) & - (sum_uv < abs_detA)) - return contains diff --git a/spaces/Yunshansongbai/SVC-Nahida/inference/slicer.py b/spaces/Yunshansongbai/SVC-Nahida/inference/slicer.py deleted file mode 100644 index 61a323c53a0eb69323bdfdbe0155455bd195c850..0000000000000000000000000000000000000000 --- a/spaces/Yunshansongbai/SVC-Nahida/inference/slicer.py +++ /dev/null @@ -1,142 +0,0 @@ -import librosa -import paddle -import paddle.audio as paddleaudio - - -class Slicer: - def __init__(self, - sr: int, - threshold: float = -40., - 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.) - 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 = librosa.to_mono(waveform) - else: - samples = waveform - if samples.shape[0] <= self.min_length: - return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}} - rms_list = librosa.feature.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 {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}} - else: - chunks = [] - # 第一段静音并非从头开始,补上有声片段 - if sil_tags[0][0]: - chunks.append( - {"slice": False, "split_time": f"0,{min(waveform.shape[0], sil_tags[0][0] * self.hop_size)}"}) - for i in range(0, len(sil_tags)): - # 标识有声片段(跳过第一段) - if i: - chunks.append({"slice": False, - "split_time": f"{sil_tags[i - 1][1] * self.hop_size},{min(waveform.shape[0], sil_tags[i][0] * self.hop_size)}"}) - # 标识所有静音片段 - chunks.append({"slice": True, - "split_time": f"{sil_tags[i][0] * self.hop_size},{min(waveform.shape[0], sil_tags[i][1] * self.hop_size)}"}) - # 最后一段静音并非结尾,补上结尾片段 - if sil_tags[-1][1] * self.hop_size < len(waveform): - chunks.append({"slice": False, "split_time": f"{sil_tags[-1][1] * self.hop_size},{len(waveform)}"}) - chunk_dict = {} - for i in range(len(chunks)): - chunk_dict[str(i)] = chunks[i] - return chunk_dict - - -def cut(audio_path, db_thresh=-30, min_len=5000): - audio, sr = librosa.load(audio_path, sr=None) - slicer = Slicer( - sr=sr, - threshold=db_thresh, - min_length=min_len - ) - chunks = slicer.slice(audio) - return chunks - - -def chunks2audio(audio_path, chunks): - chunks = dict(chunks) - audio, sr = paddleaudio.load(audio_path) - if len(audio.shape) == 2 and audio.shape[1] >= 2: - audio = paddle.mean(audio, axis=0).unsqueeze(0) - audio = audio.cpu().numpy()[0] - result = [] - for k, v in chunks.items(): - tag = v["split_time"].split(",") - if tag[0] != tag[1]: - result.append((v["slice"], audio[int(tag[0]):int(tag[1])])) - return result, sr diff --git a/spaces/Zaixi/ICLR_FLAG/utils/chemutils.py b/spaces/Zaixi/ICLR_FLAG/utils/chemutils.py deleted file mode 100644 index d8196b8321737e855523781eb2b1af3eedc426cb..0000000000000000000000000000000000000000 --- a/spaces/Zaixi/ICLR_FLAG/utils/chemutils.py +++ /dev/null @@ -1,597 +0,0 @@ -import rdkit -import rdkit.Chem as Chem -from scipy.sparse import csr_matrix -from scipy.sparse.csgraph import minimum_spanning_tree -from collections import defaultdict -from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions -from rdkit.Chem.Descriptors import MolLogP, qed -from torch_geometric.data import Data, Batch -from random import sample -from rdkit.Chem.rdForceFieldHelpers import UFFOptimizeMolecule -import numpy as np -from math import sqrt -import torch -from copy import deepcopy -MST_MAX_WEIGHT = 100 -MAX_NCAND = 2000 - - -def vina_score(mol): - ligand_rdmol = Chem.AddHs(mol, addCoords=True) - if use_uff: - UFFOptimizeMolecule(ligand_rdmol) - -def lipinski(mol): - if qed(mol)<=5 and Chem.Lipinski.NumHDonors(mol)<=5 and Chem.Lipinski.NumHAcceptors(mol)<=10 and Chem.Descriptors.ExactMolWt(mol)<=500 and Chem.Lipinski.NumRotatableBonds(mol)<=5: - return True - else: - return False - - -def list_filter(a,b): - filter = [] - for i in a: - if i in b: - filter.append(i) - return filter - - -def rand_rotate(dir, ref, pos, alpha=None, device=None): - if device is None: - device = 'cpu' - dir = dir/torch.norm(dir) - if alpha is None: - alpha = torch.randn(1).to(device) - n_pos = pos.shape[0] - sin, cos = torch.sin(alpha).to(device), torch.cos(alpha).to(device) - K = 1 - cos - M = torch.dot(dir, ref) - nx, ny, nz = dir[0], dir[1], dir[2] - x0, y0, z0 = ref[0], ref[1], ref[2] - T = torch.tensor([nx ** 2 * K + cos, nx * ny * K - nz * sin, nx * nz * K + ny * sin, - (x0 - nx * M) * K + (nz * y0 - ny * z0) * sin, - nx * ny * K + nz * sin, ny ** 2 * K + cos, ny * nz * K - nx * sin, - (y0 - ny * M) * K + (nx * z0 - nz * x0) * sin, - nx * nz * K - ny * sin, ny * nz * K + nx * sin, nz ** 2 * K + cos, - (z0 - nz * M) * K + (ny * x0 - nx * y0) * sin, - 0, 0, 0, 1], device=device).reshape(4, 4) - pos = torch.cat([pos.t(), torch.ones(n_pos, device=device).unsqueeze(0)], dim=0) - rotated_pos = torch.mm(T, pos)[:3] - return rotated_pos.t() - - -def kabsch(A, B): - # Input: - # Nominal A Nx3 matrix of points - # Measured B Nx3 matrix of points - # Returns R,t - # R = 3x3 rotation matrix (B to A) - # t = 3x1 translation vector (B to A) - assert len(A) == len(B) - N = A.shape[0] # total points - centroid_A = np.mean(A, axis=0) - centroid_B = np.mean(B, axis=0) - # center the points - AA = A - np.tile(centroid_A, (N, 1)) - BB = B - np.tile(centroid_B, (N, 1)) - H = np.transpose(BB) * AA - U, S, Vt = np.linalg.svd(H) - R = Vt.T * U.T - # special reflection case - if np.linalg.det(R) < 0: - Vt[2, :] *= -1 - R = Vt.T * U.T - t = -R * centroid_B.T + centroid_A.T - return R, t - - -def kabsch_torch(A, B, C): - A=A.double() - B=B.double() - C=C.double() - a_mean = A.mean(dim=0, keepdims=True) - b_mean = B.mean(dim=0, keepdims=True) - A_c = A - a_mean - B_c = B - b_mean - # Covariance matrix - H = torch.matmul(A_c.transpose(0,1), B_c) # [B, 3, 3] - U, S, V = torch.svd(H) - # Rotation matrix - R = torch.matmul(V, U.transpose(0,1)) # [B, 3, 3] - # Translation vector - t = b_mean - torch.matmul(R, a_mean.transpose(0,1)).transpose(0,1) - C_aligned = torch.matmul(R, C.transpose(0,1)).transpose(0,1) + t - return C_aligned, R, t - - -def eig_coord_from_dist(D): - M = (D[:1, :] + D[:, :1] - D) / 2 - L, V = torch.linalg.eigh(M) - L = torch.diag_embed(torch.sort(L, descending=True)[0]) - X = torch.matmul(V, L.clamp(min=0).sqrt()) - return X[:, :3].detach() - - -def self_square_dist(X): - dX = X.unsqueeze(0) - X.unsqueeze(1) # [1, N, 3] - [N, 1, 3] - D = torch.sum(dX**2, dim=-1) - return D - - -def set_atommap(mol, num=0): - for atom in mol.GetAtoms(): - atom.SetAtomMapNum(num) - - -def get_mol(smiles): - mol = Chem.MolFromSmiles(smiles) - if mol is None: - return None - Chem.Kekulize(mol) - return mol - - -def get_smiles(mol): - return Chem.MolToSmiles(mol, kekuleSmiles=False) - - -def decode_stereo(smiles2D): - mol = Chem.MolFromSmiles(smiles2D) - dec_isomers = list(EnumerateStereoisomers(mol)) - - dec_isomers = [Chem.MolFromSmiles(Chem.MolToSmiles(mol, isomericSmiles=True)) for mol in dec_isomers] - smiles3D = [Chem.MolToSmiles(mol, isomericSmiles=True) for mol in dec_isomers] - - chiralN = [atom.GetIdx() for atom in dec_isomers[0].GetAtoms() if - int(atom.GetChiralTag()) > 0 and atom.GetSymbol() == "N"] - if len(chiralN) > 0: - for mol in dec_isomers: - for idx in chiralN: - mol.GetAtomWithIdx(idx).SetChiralTag(Chem.rdchem.ChiralType.CHI_UNSPECIFIED) - smiles3D.append(Chem.MolToSmiles(mol, isomericSmiles=True)) - - return smiles3D - - -def sanitize(mol): - try: - smiles = get_smiles(mol) - mol = get_mol(smiles) - except Exception as e: - return None - return mol - - -def copy_atom(atom): - new_atom = Chem.Atom(atom.GetSymbol()) - new_atom.SetFormalCharge(atom.GetFormalCharge()) - new_atom.SetAtomMapNum(atom.GetAtomMapNum()) - return new_atom - - -def copy_edit_mol(mol): - new_mol = Chem.RWMol(Chem.MolFromSmiles('')) - for atom in mol.GetAtoms(): - new_atom = copy_atom(atom) - new_mol.AddAtom(new_atom) - for bond in mol.GetBonds(): - a1 = bond.GetBeginAtom().GetIdx() - a2 = bond.GetEndAtom().GetIdx() - bt = bond.GetBondType() - new_mol.AddBond(a1, a2, bt) - return new_mol - - -def get_submol(mol, idxs, mark=[]): - new_mol = Chem.RWMol(Chem.MolFromSmiles('')) - map = {} - for atom in mol.GetAtoms(): - if atom.GetIdx() in idxs: - new_atom = copy_atom(atom) - if atom.GetIdx() in mark: - new_atom.SetAtomMapNum(1) - else: - new_atom.SetAtomMapNum(0) - map[atom.GetIdx()] = new_mol.AddAtom(new_atom) - for bond in mol.GetBonds(): - a1 = bond.GetBeginAtom().GetIdx() - a2 = bond.GetEndAtom().GetIdx() - if a1 in idxs and a2 in idxs: - bt = bond.GetBondType() - new_mol.AddBond(map[a1], map[a2], bt) - return new_mol.GetMol() - - -def get_clique_mol(mol, atoms): - smiles = Chem.MolFragmentToSmiles(mol, atoms, kekuleSmiles=True) - new_mol = Chem.MolFromSmiles(smiles, sanitize=False) - new_mol = copy_edit_mol(new_mol).GetMol() - new_mol = sanitize(new_mol) # We assume this is not None - return new_mol - - -def get_clique_mol_simple(mol, cluster): - smile_cluster = Chem.MolFragmentToSmiles(mol, cluster, canonical=True, kekuleSmiles=True) - mol_cluster = Chem.MolFromSmiles(smile_cluster, sanitize=False) - return mol_cluster - - -def tree_decomp(mol, reference_vocab=None): - edges = defaultdict(int) - n_atoms = mol.GetNumAtoms() - clusters = [] - for bond in mol.GetBonds(): - a1 = bond.GetBeginAtom().GetIdx() - a2 = bond.GetEndAtom().GetIdx() - if not bond.IsInRing(): - clusters.append({a1, a2}) - # extract rotatable bonds - - ssr = [set(x) for x in Chem.GetSymmSSSR(mol)] - # remove too large circles - ssr = [x for x in ssr if len(x) <= 8] - - # Merge Rings with intersection >= 2 atoms - # check the reference_vocab if it is not None - for i in range(len(ssr)-1): - if len(ssr[i]) <= 2: - continue - for j in range(i+1, len(ssr)): - if len(ssr[j]) <= 2: - continue - inter = ssr[i] & ssr[j] - if reference_vocab is not None: - if len(inter) >= 2: - merge = ssr[i] | ssr[j] - smile_merge = Chem.MolFragmentToSmiles(mol, merge, canonical=True, kekuleSmiles=True) - if reference_vocab[smile_merge] <= 100 and len(inter) == 2: - continue - ssr[i] = merge - ssr[j] = set() - else: - if len(inter) > 2: - merge = ssr[i] | ssr[j] - ssr[i] = merge - ssr[j] = set() - - ssr = [c for c in ssr if len(c) > 0] - clusters.extend(ssr) - nei_list = [[] for _ in range(n_atoms)] - for i in range(len(clusters)): - for atom in clusters[i]: - nei_list[atom].append(i) - - # Build edges - for atom in range(n_atoms): - if len(nei_list[atom]) <= 1: - continue - cnei = nei_list[atom] - for i in range(len(cnei)): - for j in range(i + 1, len(cnei)): - c1, c2 = cnei[i], cnei[j] - inter = set(clusters[c1]) & set(clusters[c2]) - if edges[(c1, c2)] < len(inter): - edges[(c1, c2)] = len(inter) # cnei[i] < cnei[j] by construction - - edges = [u + (MST_MAX_WEIGHT - v,) for u, v in edges.items()] - if len(edges) == 0: - return clusters, edges - - # Compute Maximum Spanning Tree - row, col, data = zip(*edges) - n_clique = len(clusters) - clique_graph = csr_matrix((data, (row, col)), shape=(n_clique, n_clique)) - junc_tree = minimum_spanning_tree(clique_graph) - row, col = junc_tree.nonzero() - edges = [(row[i], col[i]) for i in range(len(row))] - return clusters, edges - - -def atom_equal(a1, a2): - return a1.GetSymbol() == a2.GetSymbol() and a1.GetFormalCharge() == a2.GetFormalCharge() - - -# Bond type not considered because all aromatic (so SINGLE matches DOUBLE) -def ring_bond_equal(bond1, bond2, reverse=False): - b1 = (bond1.GetBeginAtom(), bond1.GetEndAtom()) - if reverse: - b2 = (bond2.GetEndAtom(), bond2.GetBeginAtom()) - else: - b2 = (bond2.GetBeginAtom(), bond2.GetEndAtom()) - return atom_equal(b1[0], b2[0]) and atom_equal(b1[1], b2[1]) and bond1.GetBondType() == bond2.GetBondType() - - -def attach(ctr_mol, nei_mol, amap): - ctr_mol = Chem.RWMol(ctr_mol) - for atom in nei_mol.GetAtoms(): - if atom.GetIdx() not in amap: - new_atom = copy_atom(atom) - new_atom.SetAtomMapNum(2) - amap[atom.GetIdx()] = ctr_mol.AddAtom(new_atom) - - for bond in nei_mol.GetBonds(): - a1 = amap[bond.GetBeginAtom().GetIdx()] - a2 = amap[bond.GetEndAtom().GetIdx()] - if ctr_mol.GetBondBetweenAtoms(a1, a2) is None: - ctr_mol.AddBond(a1, a2, bond.GetBondType()) - - return ctr_mol.GetMol(), amap - - -def attach_mols(ctr_mol, neighbors, prev_nodes, nei_amap): - prev_nids = [node.nid for node in prev_nodes] - for nei_node in prev_nodes + neighbors: - nei_id, nei_mol = nei_node.nid, nei_node.mol - amap = nei_amap[nei_id] - for atom in nei_mol.GetAtoms(): - if atom.GetIdx() not in amap: - new_atom = copy_atom(atom) - amap[atom.GetIdx()] = ctr_mol.AddAtom(new_atom) - - if nei_mol.GetNumBonds() == 0: - nei_atom = nei_mol.GetAtomWithIdx(0) - ctr_atom = ctr_mol.GetAtomWithIdx(amap[0]) - ctr_atom.SetAtomMapNum(nei_atom.GetAtomMapNum()) - else: - for bond in nei_mol.GetBonds(): - a1 = amap[bond.GetBeginAtom().GetIdx()] - a2 = amap[bond.GetEndAtom().GetIdx()] - if ctr_mol.GetBondBetweenAtoms(a1, a2) is None: - ctr_mol.AddBond(a1, a2, bond.GetBondType()) - elif nei_id in prev_nids: # father node overrides - ctr_mol.RemoveBond(a1, a2) - ctr_mol.AddBond(a1, a2, bond.GetBondType()) - return ctr_mol - - -def local_attach(ctr_mol, neighbors, prev_nodes, amap_list): - ctr_mol = copy_edit_mol(ctr_mol) - nei_amap = {nei.nid: {} for nei in prev_nodes + neighbors} - - for nei_id, ctr_atom, nei_atom in amap_list: - nei_amap[nei_id][nei_atom] = ctr_atom - - ctr_mol = attach_mols(ctr_mol, neighbors, prev_nodes, nei_amap) - return ctr_mol.GetMol() - - -# This version records idx mapping between ctr_mol and nei_mol -def enum_attach(ctr_mol, nei_mol): - try: - Chem.Kekulize(ctr_mol) - Chem.Kekulize(nei_mol) - except: - return [] - att_confs = [] - valence_ctr = {i: 0 for i in range(ctr_mol.GetNumAtoms())} - valence_nei = {i: 0 for i in range(nei_mol.GetNumAtoms())} - ctr_bonds = [bond for bond in ctr_mol.GetBonds() if bond.GetBeginAtom().GetAtomMapNum() == 1 and bond.GetEndAtom().GetAtomMapNum() == 1] - ctr_atoms = [atom for atom in ctr_mol.GetAtoms() if atom.GetAtomMapNum() == 1] - if nei_mol.GetNumBonds() == 1: # neighbor is a bond - bond = nei_mol.GetBondWithIdx(0) - #bond_val = int(bond.GetBondType()) - bond_val = int(bond.GetBondTypeAsDouble()) - b1, b2 = bond.GetBeginAtom(), bond.GetEndAtom() - - for atom in ctr_atoms: - # Optimize if atom is carbon (other atoms may change valence) - if atom.GetAtomicNum() == 6 and atom.GetTotalNumHs() < bond_val: - continue - if atom_equal(atom, b1): - new_amap = {b1.GetIdx(): atom.GetIdx()} - att_confs.append(new_amap) - elif atom_equal(atom, b2): - new_amap = {b2.GetIdx(): atom.GetIdx()} - att_confs.append(new_amap) - else: - # intersection is an atom - for a1 in ctr_atoms: - for a2 in nei_mol.GetAtoms(): - if atom_equal(a1, a2): - # Optimize if atom is carbon (other atoms may change valence) - if a1.GetAtomicNum() == 6 and a1.GetTotalNumHs() + a2.GetTotalNumHs() < 4: - continue - amap = {a2.GetIdx(): a1.GetIdx()} - att_confs.append(amap) - - # intersection is an bond - if ctr_mol.GetNumBonds() > 1: - for b1 in ctr_bonds: - for b2 in nei_mol.GetBonds(): - if ring_bond_equal(b1, b2): - amap = {b2.GetBeginAtom().GetIdx(): b1.GetBeginAtom().GetIdx(), - b2.GetEndAtom().GetIdx(): b1.GetEndAtom().GetIdx()} - att_confs.append(amap) - - if ring_bond_equal(b1, b2, reverse=True): - amap = {b2.GetEndAtom().GetIdx(): b1.GetBeginAtom().GetIdx(), - b2.GetBeginAtom().GetIdx(): b1.GetEndAtom().GetIdx()} - att_confs.append(amap) - return att_confs - - -def enumerate_assemble(mol, idxs, current, next): - ctr_mol = get_submol(mol, idxs, mark=current.clique) - ground_truth = get_submol(mol, list(set(idxs) | set(next.clique))) - # submol can also obtained with get_clique_mol, future exploration - ground_truth_smiles = get_smiles(ground_truth) - cand_smiles = [] - cand_mols = [] - cand_amap = enum_attach(ctr_mol, next.mol) - for amap in cand_amap: - try: - cand_mol, _ = attach(ctr_mol, next.mol, amap) - cand_mol = sanitize(cand_mol) - except: - continue - if cand_mol is None: - continue - smiles = get_smiles(cand_mol) - if smiles in cand_smiles or smiles == ground_truth_smiles: - continue - cand_smiles.append(smiles) - cand_mols.append(cand_mol) - if len(cand_mols) >= 1: - cand_mols = sample(cand_mols, 1) - cand_mols.append(ground_truth) - labels = torch.tensor([0, 1]) - else: - cand_mols = [ground_truth] - labels = torch.tensor([1]) - - return labels, cand_mols - - -# allowable node and edge features -allowable_features = { - 'possible_atomic_num_list' : list(range(1, 119)), - 'possible_formal_charge_list' : [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], - 'possible_chirality_list' : [ - Chem.rdchem.ChiralType.CHI_UNSPECIFIED, - Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CW, - Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CCW, - Chem.rdchem.ChiralType.CHI_OTHER - ], - 'possible_hybridization_list' : [ - Chem.rdchem.HybridizationType.S, - Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2, - Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.SP3D, - Chem.rdchem.HybridizationType.SP3D2, Chem.rdchem.HybridizationType.UNSPECIFIED - ], - 'possible_numH_list' : [0, 1, 2, 3, 4, 5, 6, 7, 8], - 'possible_implicit_valence_list' : [0, 1, 2, 3, 4, 5, 6], - 'possible_degree_list' : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - 'possible_bonds' : [ - Chem.rdchem.BondType.SINGLE, - Chem.rdchem.BondType.DOUBLE, - Chem.rdchem.BondType.TRIPLE, - Chem.rdchem.BondType.AROMATIC - ], - 'possible_bond_dirs' : [ # only for double bond stereo information - Chem.rdchem.BondDir.NONE, - Chem.rdchem.BondDir.ENDUPRIGHT, - Chem.rdchem.BondDir.ENDDOWNRIGHT - ] -} - -def mol_to_graph_data_obj_simple(mol): - """ - Converts rdkit mol object to graph Data object required by the pytorch - geometric package. NB: Uses simplified atom and bond features, and represent - as indices - :param mol: rdkit mol object - :return: graph data object with the attributes: x, edge_index, edge_attr - """ - # atoms - num_atom_features = 2 # atom type, chirality tag - atom_features_list = [] - for atom in mol.GetAtoms(): - atom_feature = [allowable_features['possible_atomic_num_list'].index( - atom.GetAtomicNum())] + [allowable_features[ - 'possible_chirality_list'].index(atom.GetChiralTag())] - atom_features_list.append(atom_feature) - x = torch.tensor(np.array(atom_features_list), dtype=torch.long) - - # bonds - num_bond_features = 2 # bond type, bond direction - if len(mol.GetBonds()) > 0: # mol has bonds - edges_list = [] - edge_features_list = [] - for bond in mol.GetBonds(): - i = bond.GetBeginAtomIdx() - j = bond.GetEndAtomIdx() - edge_feature = [allowable_features['possible_bonds'].index( - bond.GetBondType())] + [allowable_features[ - 'possible_bond_dirs'].index( - bond.GetBondDir())] - edges_list.append((i, j)) - edge_features_list.append(edge_feature) - edges_list.append((j, i)) - edge_features_list.append(edge_feature) - - # data.edge_index: Graph connectivity in COO format with shape [2, num_edges] - edge_index = torch.tensor(np.array(edges_list).T, dtype=torch.long) - - # data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features] - edge_attr = torch.tensor(np.array(edge_features_list), - dtype=torch.long) - else: # mol has no bonds - edge_index = torch.empty((2, 0), dtype=torch.long) - edge_attr = torch.empty((0, num_bond_features), dtype=torch.long) - - data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr) - - return data - - -# For inference -def assemble(mol_list, next_motif_smiles): - attach_fail = torch.zeros(len(mol_list)).bool() - cand_mols, cand_batch, new_atoms, cand_smiles, one_atom_attach, intersection = [], [], [], [], [], [] - for i in range(len(mol_list)): - next = Chem.MolFromSmiles(next_motif_smiles[i]) - cand_amap = enum_attach(mol_list[i], next) - if len(cand_amap) == 0: - attach_fail[i] = True - cand_mols.append(mol_list[i]) - cand_batch.append(i) - one_atom_attach.append(-1) - intersection.append([]) - new_atoms.append([]) - else: - valid_cand = 0 - for amap in cand_amap: - amap_len = len(amap) - iter_atoms = [v for v in amap.values()] - ctr_mol = deepcopy(mol_list[i]) - cand_mol, amap1 = attach(ctr_mol, next, amap) - if sanitize(deepcopy(cand_mol)) is None: - continue - smiles = get_smiles(cand_mol) - cand_smiles.append(smiles) - cand_mols.append(cand_mol) - cand_batch.append(i) - new_atoms.append([v for v in amap1.values()]) - one_atom_attach.append(amap_len) - intersection.append(iter_atoms) - valid_cand+=1 - if valid_cand==0: - attach_fail[i] = True - cand_mols.append(mol_list[i]) - cand_batch.append(i) - one_atom_attach.append(-1) - intersection.append([]) - new_atoms.append([]) - cand_batch = torch.tensor(cand_batch) - one_atom_attach = torch.tensor(one_atom_attach) == 1 - return cand_mols, cand_batch, new_atoms, one_atom_attach, intersection, attach_fail - - -if __name__ == "__main__": - import sys - from mol_tree import MolTree - - lg = rdkit.RDLogger.logger() - lg.setLevel(rdkit.RDLogger.CRITICAL) - - smiles = ["O=C1[C@@H]2C=C[C@@H](C=CC2)C1(c1ccccc1)c1ccccc1", "O=C([O-])CC[C@@]12CCCC[C@]1(O)OC(=O)CC2", - "ON=C1C[C@H]2CC3(C[C@@H](C1)c1ccccc12)OCCO3", - "C[C@H]1CC(=O)[C@H]2[C@@]3(O)C(=O)c4cccc(O)c4[C@@H]4O[C@@]43[C@@H](O)C[C@]2(O)C1", - 'Cc1cc(NC(=O)CSc2nnc3c4ccccc4n(C)c3n2)ccc1Br', 'CC(C)(C)c1ccc(C(=O)N[C@H]2CCN3CCCc4cccc2c43)cc1', - "O=c1c2ccc3c(=O)n(-c4nccs4)c(=O)c4ccc(c(=O)n1-c1nccs1)c2c34", "O=C(N1CCc2c(F)ccc(F)c2C1)C1(O)Cc2ccccc2C1"] - mol_tree = MolTree("C") - assert len(mol_tree.nodes) > 0 - - - def count(): - cnt, n = 0, 0 - for s in sys.stdin: - s = s.split()[0] - tree = MolTree(s) - tree.recover() - tree.assemble() - for node in tree.nodes: - cnt += len(node.cands) - n += len(tree.nodes) - # print cnt * 1.0 / n - count() diff --git a/spaces/ZeroTech/ChatGPT/README.md b/spaces/ZeroTech/ChatGPT/README.md deleted file mode 100644 index 22a1e3d7a10583001b93944d54469ad3c9dd9a9e..0000000000000000000000000000000000000000 --- a/spaces/ZeroTech/ChatGPT/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: ChatGPT -emoji: 📊 -colorFrom: blue -colorTo: blue -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/a-v-bely/russian-task-generator/utilities/utils.py b/spaces/a-v-bely/russian-task-generator/utilities/utils.py deleted file mode 100644 index 58fb296ef9f4e5bc343cf6f81e52784fc89cf375..0000000000000000000000000000000000000000 --- a/spaces/a-v-bely/russian-task-generator/utilities/utils.py +++ /dev/null @@ -1,29 +0,0 @@ -import uuid - - -def points_to_mark(good, total): - percents = good / total * 100 - if percents < 50: - return 2 - elif percents < 66: - return 3 - elif percents < 90: - return 4 - else: - return 5 - - -def answer_letter(answer, variants): - answer = answer.lower() - for var in variants: - letter, var = var.split(') ') - if var == answer: - return letter + ') ' + answer - - -def is_valid_uuid(value): - try: - uuid.UUID(str(value)) - return True - except ValueError: - return False diff --git a/spaces/aaronb/DragGAN/README.md b/spaces/aaronb/DragGAN/README.md deleted file mode 100644 index 5f5fc7e09ec9f39d1c03bef9cbac67692b0e7070..0000000000000000000000000000000000000000 --- a/spaces/aaronb/DragGAN/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: DragGAN -emoji: ⚡ -colorFrom: pink -colorTo: green -sdk: gradio -sdk_version: 3.29.0 -app_file: gradio_app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/sabl_retina_head.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/sabl_retina_head.py deleted file mode 100644 index 4211622cb8b4fe807230a89bcaab8f4f1681bfc0..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/sabl_retina_head.py +++ /dev/null @@ -1,621 +0,0 @@ -import numpy as np -import torch -import torch.nn as nn -from mmcv.cnn import ConvModule, bias_init_with_prob, normal_init -from mmcv.runner import force_fp32 - -from mmdet.core import (build_anchor_generator, build_assigner, - build_bbox_coder, build_sampler, images_to_levels, - multi_apply, multiclass_nms, unmap) -from ..builder import HEADS, build_loss -from .base_dense_head import BaseDenseHead -from .guided_anchor_head import GuidedAnchorHead - - -@HEADS.register_module() -class SABLRetinaHead(BaseDenseHead): - """Side-Aware Boundary Localization (SABL) for RetinaNet. - - The anchor generation, assigning and sampling in SABLRetinaHead - are the same as GuidedAnchorHead for guided anchoring. - - Please refer to https://arxiv.org/abs/1912.04260 for more details. - - Args: - num_classes (int): Number of classes. - in_channels (int): Number of channels in the input feature map. - stacked_convs (int): Number of Convs for classification \ - and regression branches. Defaults to 4. - feat_channels (int): Number of hidden channels. \ - Defaults to 256. - approx_anchor_generator (dict): Config dict for approx generator. - square_anchor_generator (dict): Config dict for square generator. - conv_cfg (dict): Config dict for ConvModule. Defaults to None. - norm_cfg (dict): Config dict for Norm Layer. Defaults to None. - bbox_coder (dict): Config dict for bbox coder. - reg_decoded_bbox (bool): If true, the regression loss would be - applied directly on decoded bounding boxes, converting both - the predicted boxes and regression targets to absolute - coordinates format. Default False. It should be `True` when - using `IoULoss`, `GIoULoss`, or `DIoULoss` in the bbox head. - train_cfg (dict): Training config of SABLRetinaHead. - test_cfg (dict): Testing config of SABLRetinaHead. - loss_cls (dict): Config of classification loss. - loss_bbox_cls (dict): Config of classification loss for bbox branch. - loss_bbox_reg (dict): Config of regression loss for bbox branch. - """ - - def __init__(self, - num_classes, - in_channels, - stacked_convs=4, - feat_channels=256, - approx_anchor_generator=dict( - type='AnchorGenerator', - octave_base_scale=4, - scales_per_octave=3, - ratios=[0.5, 1.0, 2.0], - strides=[8, 16, 32, 64, 128]), - square_anchor_generator=dict( - type='AnchorGenerator', - ratios=[1.0], - scales=[4], - strides=[8, 16, 32, 64, 128]), - conv_cfg=None, - norm_cfg=None, - bbox_coder=dict( - type='BucketingBBoxCoder', - num_buckets=14, - scale_factor=3.0), - reg_decoded_bbox=False, - train_cfg=None, - test_cfg=None, - loss_cls=dict( - type='FocalLoss', - use_sigmoid=True, - gamma=2.0, - alpha=0.25, - loss_weight=1.0), - loss_bbox_cls=dict( - type='CrossEntropyLoss', - use_sigmoid=True, - loss_weight=1.5), - loss_bbox_reg=dict( - type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.5)): - super(SABLRetinaHead, self).__init__() - self.in_channels = in_channels - self.num_classes = num_classes - self.feat_channels = feat_channels - self.num_buckets = bbox_coder['num_buckets'] - self.side_num = int(np.ceil(self.num_buckets / 2)) - - assert (approx_anchor_generator['octave_base_scale'] == - square_anchor_generator['scales'][0]) - assert (approx_anchor_generator['strides'] == - square_anchor_generator['strides']) - - self.approx_anchor_generator = build_anchor_generator( - approx_anchor_generator) - self.square_anchor_generator = build_anchor_generator( - square_anchor_generator) - self.approxs_per_octave = ( - self.approx_anchor_generator.num_base_anchors[0]) - - # one anchor per location - self.num_anchors = 1 - self.stacked_convs = stacked_convs - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - - self.reg_decoded_bbox = reg_decoded_bbox - - self.use_sigmoid_cls = loss_cls.get('use_sigmoid', False) - self.sampling = loss_cls['type'] not in [ - 'FocalLoss', 'GHMC', 'QualityFocalLoss' - ] - if self.use_sigmoid_cls: - self.cls_out_channels = num_classes - else: - self.cls_out_channels = num_classes + 1 - - self.bbox_coder = build_bbox_coder(bbox_coder) - self.loss_cls = build_loss(loss_cls) - self.loss_bbox_cls = build_loss(loss_bbox_cls) - self.loss_bbox_reg = build_loss(loss_bbox_reg) - - self.train_cfg = train_cfg - self.test_cfg = test_cfg - - if self.train_cfg: - self.assigner = build_assigner(self.train_cfg.assigner) - # use PseudoSampler when sampling is False - if self.sampling and hasattr(self.train_cfg, 'sampler'): - sampler_cfg = self.train_cfg.sampler - else: - sampler_cfg = dict(type='PseudoSampler') - self.sampler = build_sampler(sampler_cfg, context=self) - - self.fp16_enabled = False - self._init_layers() - - def _init_layers(self): - self.relu = nn.ReLU(inplace=True) - self.cls_convs = nn.ModuleList() - self.reg_convs = nn.ModuleList() - for i in range(self.stacked_convs): - chn = self.in_channels if i == 0 else self.feat_channels - self.cls_convs.append( - ConvModule( - chn, - self.feat_channels, - 3, - stride=1, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg)) - self.reg_convs.append( - ConvModule( - chn, - self.feat_channels, - 3, - stride=1, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg)) - self.retina_cls = nn.Conv2d( - self.feat_channels, self.cls_out_channels, 3, padding=1) - self.retina_bbox_reg = nn.Conv2d( - self.feat_channels, self.side_num * 4, 3, padding=1) - self.retina_bbox_cls = nn.Conv2d( - self.feat_channels, self.side_num * 4, 3, padding=1) - - def init_weights(self): - for m in self.cls_convs: - normal_init(m.conv, std=0.01) - for m in self.reg_convs: - normal_init(m.conv, std=0.01) - bias_cls = bias_init_with_prob(0.01) - normal_init(self.retina_cls, std=0.01, bias=bias_cls) - normal_init(self.retina_bbox_reg, std=0.01) - normal_init(self.retina_bbox_cls, std=0.01) - - def forward_single(self, x): - cls_feat = x - reg_feat = x - for cls_conv in self.cls_convs: - cls_feat = cls_conv(cls_feat) - for reg_conv in self.reg_convs: - reg_feat = reg_conv(reg_feat) - cls_score = self.retina_cls(cls_feat) - bbox_cls_pred = self.retina_bbox_cls(reg_feat) - bbox_reg_pred = self.retina_bbox_reg(reg_feat) - bbox_pred = (bbox_cls_pred, bbox_reg_pred) - return cls_score, bbox_pred - - def forward(self, feats): - return multi_apply(self.forward_single, feats) - - def get_anchors(self, featmap_sizes, img_metas, device='cuda'): - """Get squares according to feature map sizes and guided anchors. - - Args: - featmap_sizes (list[tuple]): Multi-level feature map sizes. - img_metas (list[dict]): Image meta info. - device (torch.device | str): device for returned tensors - - Returns: - tuple: square approxs of each image - """ - num_imgs = len(img_metas) - - # since feature map sizes of all images are the same, we only compute - # squares for one time - multi_level_squares = self.square_anchor_generator.grid_anchors( - featmap_sizes, device=device) - squares_list = [multi_level_squares for _ in range(num_imgs)] - - return squares_list - - def get_target(self, - approx_list, - inside_flag_list, - square_list, - gt_bboxes_list, - img_metas, - gt_bboxes_ignore_list=None, - gt_labels_list=None, - label_channels=None, - sampling=True, - unmap_outputs=True): - """Compute bucketing targets. - Args: - approx_list (list[list]): Multi level approxs of each image. - inside_flag_list (list[list]): Multi level inside flags of each - image. - square_list (list[list]): Multi level squares of each image. - gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image. - img_metas (list[dict]): Meta info of each image. - gt_bboxes_ignore_list (list[Tensor]): ignore list of gt bboxes. - gt_bboxes_list (list[Tensor]): Gt bboxes of each image. - label_channels (int): Channel of label. - sampling (bool): Sample Anchors or not. - unmap_outputs (bool): unmap outputs or not. - - Returns: - tuple: Returns a tuple containing learning targets. - - - labels_list (list[Tensor]): Labels of each level. - - label_weights_list (list[Tensor]): Label weights of each \ - level. - - bbox_cls_targets_list (list[Tensor]): BBox cls targets of \ - each level. - - bbox_cls_weights_list (list[Tensor]): BBox cls weights of \ - each level. - - bbox_reg_targets_list (list[Tensor]): BBox reg targets of \ - each level. - - bbox_reg_weights_list (list[Tensor]): BBox reg weights of \ - each level. - - num_total_pos (int): Number of positive samples in all \ - images. - - num_total_neg (int): Number of negative samples in all \ - images. - """ - num_imgs = len(img_metas) - assert len(approx_list) == len(inside_flag_list) == len( - square_list) == num_imgs - # anchor number of multi levels - num_level_squares = [squares.size(0) for squares in square_list[0]] - # concat all level anchors and flags to a single tensor - inside_flag_flat_list = [] - approx_flat_list = [] - square_flat_list = [] - for i in range(num_imgs): - assert len(square_list[i]) == len(inside_flag_list[i]) - inside_flag_flat_list.append(torch.cat(inside_flag_list[i])) - approx_flat_list.append(torch.cat(approx_list[i])) - square_flat_list.append(torch.cat(square_list[i])) - - # compute targets for each image - if gt_bboxes_ignore_list is None: - gt_bboxes_ignore_list = [None for _ in range(num_imgs)] - if gt_labels_list is None: - gt_labels_list = [None for _ in range(num_imgs)] - (all_labels, all_label_weights, all_bbox_cls_targets, - all_bbox_cls_weights, all_bbox_reg_targets, all_bbox_reg_weights, - pos_inds_list, neg_inds_list) = multi_apply( - self._get_target_single, - approx_flat_list, - inside_flag_flat_list, - square_flat_list, - gt_bboxes_list, - gt_bboxes_ignore_list, - gt_labels_list, - img_metas, - label_channels=label_channels, - sampling=sampling, - unmap_outputs=unmap_outputs) - # no valid anchors - if any([labels is None for labels in all_labels]): - return None - # sampled anchors of all images - num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list]) - num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list]) - # split targets to a list w.r.t. multiple levels - labels_list = images_to_levels(all_labels, num_level_squares) - label_weights_list = images_to_levels(all_label_weights, - num_level_squares) - bbox_cls_targets_list = images_to_levels(all_bbox_cls_targets, - num_level_squares) - bbox_cls_weights_list = images_to_levels(all_bbox_cls_weights, - num_level_squares) - bbox_reg_targets_list = images_to_levels(all_bbox_reg_targets, - num_level_squares) - bbox_reg_weights_list = images_to_levels(all_bbox_reg_weights, - num_level_squares) - return (labels_list, label_weights_list, bbox_cls_targets_list, - bbox_cls_weights_list, bbox_reg_targets_list, - bbox_reg_weights_list, num_total_pos, num_total_neg) - - def _get_target_single(self, - flat_approxs, - inside_flags, - flat_squares, - gt_bboxes, - gt_bboxes_ignore, - gt_labels, - img_meta, - label_channels=None, - sampling=True, - unmap_outputs=True): - """Compute regression and classification targets for anchors in a - single image. - - Args: - flat_approxs (Tensor): flat approxs of a single image, - shape (n, 4) - inside_flags (Tensor): inside flags of a single image, - shape (n, ). - flat_squares (Tensor): flat squares of a single image, - shape (approxs_per_octave * n, 4) - gt_bboxes (Tensor): Ground truth bboxes of a single image, \ - shape (num_gts, 4). - gt_bboxes_ignore (Tensor): Ground truth bboxes to be - ignored, shape (num_ignored_gts, 4). - gt_labels (Tensor): Ground truth labels of each box, - shape (num_gts,). - img_meta (dict): Meta info of the image. - label_channels (int): Channel of label. - sampling (bool): Sample Anchors or not. - unmap_outputs (bool): unmap outputs or not. - - Returns: - tuple: - - - labels_list (Tensor): Labels in a single image - - label_weights (Tensor): Label weights in a single image - - bbox_cls_targets (Tensor): BBox cls targets in a single image - - bbox_cls_weights (Tensor): BBox cls weights in a single image - - bbox_reg_targets (Tensor): BBox reg targets in a single image - - bbox_reg_weights (Tensor): BBox reg weights in a single image - - num_total_pos (int): Number of positive samples \ - in a single image - - num_total_neg (int): Number of negative samples \ - in a single image - """ - if not inside_flags.any(): - return (None, ) * 8 - # assign gt and sample anchors - expand_inside_flags = inside_flags[:, None].expand( - -1, self.approxs_per_octave).reshape(-1) - approxs = flat_approxs[expand_inside_flags, :] - squares = flat_squares[inside_flags, :] - - assign_result = self.assigner.assign(approxs, squares, - self.approxs_per_octave, - gt_bboxes, gt_bboxes_ignore) - sampling_result = self.sampler.sample(assign_result, squares, - gt_bboxes) - - num_valid_squares = squares.shape[0] - bbox_cls_targets = squares.new_zeros( - (num_valid_squares, self.side_num * 4)) - bbox_cls_weights = squares.new_zeros( - (num_valid_squares, self.side_num * 4)) - bbox_reg_targets = squares.new_zeros( - (num_valid_squares, self.side_num * 4)) - bbox_reg_weights = squares.new_zeros( - (num_valid_squares, self.side_num * 4)) - labels = squares.new_full((num_valid_squares, ), - self.num_classes, - dtype=torch.long) - label_weights = squares.new_zeros(num_valid_squares, dtype=torch.float) - - pos_inds = sampling_result.pos_inds - neg_inds = sampling_result.neg_inds - if len(pos_inds) > 0: - (pos_bbox_reg_targets, pos_bbox_reg_weights, pos_bbox_cls_targets, - pos_bbox_cls_weights) = self.bbox_coder.encode( - sampling_result.pos_bboxes, sampling_result.pos_gt_bboxes) - - bbox_cls_targets[pos_inds, :] = pos_bbox_cls_targets - bbox_reg_targets[pos_inds, :] = pos_bbox_reg_targets - bbox_cls_weights[pos_inds, :] = pos_bbox_cls_weights - bbox_reg_weights[pos_inds, :] = pos_bbox_reg_weights - if gt_labels is None: - # Only rpn gives gt_labels as None - # Foreground is the first class - labels[pos_inds] = 0 - else: - labels[pos_inds] = gt_labels[ - sampling_result.pos_assigned_gt_inds] - if self.train_cfg.pos_weight <= 0: - label_weights[pos_inds] = 1.0 - else: - label_weights[pos_inds] = self.train_cfg.pos_weight - if len(neg_inds) > 0: - label_weights[neg_inds] = 1.0 - - # map up to original set of anchors - if unmap_outputs: - num_total_anchors = flat_squares.size(0) - labels = unmap( - labels, num_total_anchors, inside_flags, fill=self.num_classes) - label_weights = unmap(label_weights, num_total_anchors, - inside_flags) - bbox_cls_targets = unmap(bbox_cls_targets, num_total_anchors, - inside_flags) - bbox_cls_weights = unmap(bbox_cls_weights, num_total_anchors, - inside_flags) - bbox_reg_targets = unmap(bbox_reg_targets, num_total_anchors, - inside_flags) - bbox_reg_weights = unmap(bbox_reg_weights, num_total_anchors, - inside_flags) - return (labels, label_weights, bbox_cls_targets, bbox_cls_weights, - bbox_reg_targets, bbox_reg_weights, pos_inds, neg_inds) - - def loss_single(self, cls_score, bbox_pred, labels, label_weights, - bbox_cls_targets, bbox_cls_weights, bbox_reg_targets, - bbox_reg_weights, num_total_samples): - # classification loss - labels = labels.reshape(-1) - label_weights = label_weights.reshape(-1) - cls_score = cls_score.permute(0, 2, 3, - 1).reshape(-1, self.cls_out_channels) - loss_cls = self.loss_cls( - cls_score, labels, label_weights, avg_factor=num_total_samples) - # regression loss - bbox_cls_targets = bbox_cls_targets.reshape(-1, self.side_num * 4) - bbox_cls_weights = bbox_cls_weights.reshape(-1, self.side_num * 4) - bbox_reg_targets = bbox_reg_targets.reshape(-1, self.side_num * 4) - bbox_reg_weights = bbox_reg_weights.reshape(-1, self.side_num * 4) - (bbox_cls_pred, bbox_reg_pred) = bbox_pred - bbox_cls_pred = bbox_cls_pred.permute(0, 2, 3, 1).reshape( - -1, self.side_num * 4) - bbox_reg_pred = bbox_reg_pred.permute(0, 2, 3, 1).reshape( - -1, self.side_num * 4) - loss_bbox_cls = self.loss_bbox_cls( - bbox_cls_pred, - bbox_cls_targets.long(), - bbox_cls_weights, - avg_factor=num_total_samples * 4 * self.side_num) - loss_bbox_reg = self.loss_bbox_reg( - bbox_reg_pred, - bbox_reg_targets, - bbox_reg_weights, - avg_factor=num_total_samples * 4 * self.bbox_coder.offset_topk) - return loss_cls, loss_bbox_cls, loss_bbox_reg - - @force_fp32(apply_to=('cls_scores', 'bbox_preds')) - def loss(self, - cls_scores, - bbox_preds, - gt_bboxes, - gt_labels, - img_metas, - gt_bboxes_ignore=None): - featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] - assert len(featmap_sizes) == self.approx_anchor_generator.num_levels - - device = cls_scores[0].device - - # get sampled approxes - approxs_list, inside_flag_list = GuidedAnchorHead.get_sampled_approxs( - self, featmap_sizes, img_metas, device=device) - - square_list = self.get_anchors(featmap_sizes, img_metas, device=device) - - label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1 - - cls_reg_targets = self.get_target( - approxs_list, - inside_flag_list, - square_list, - gt_bboxes, - img_metas, - gt_bboxes_ignore_list=gt_bboxes_ignore, - gt_labels_list=gt_labels, - label_channels=label_channels, - sampling=self.sampling) - if cls_reg_targets is None: - return None - (labels_list, label_weights_list, bbox_cls_targets_list, - bbox_cls_weights_list, bbox_reg_targets_list, bbox_reg_weights_list, - num_total_pos, num_total_neg) = cls_reg_targets - num_total_samples = ( - num_total_pos + num_total_neg if self.sampling else num_total_pos) - losses_cls, losses_bbox_cls, losses_bbox_reg = multi_apply( - self.loss_single, - cls_scores, - bbox_preds, - labels_list, - label_weights_list, - bbox_cls_targets_list, - bbox_cls_weights_list, - bbox_reg_targets_list, - bbox_reg_weights_list, - num_total_samples=num_total_samples) - return dict( - loss_cls=losses_cls, - loss_bbox_cls=losses_bbox_cls, - loss_bbox_reg=losses_bbox_reg) - - @force_fp32(apply_to=('cls_scores', 'bbox_preds')) - def get_bboxes(self, - cls_scores, - bbox_preds, - img_metas, - cfg=None, - rescale=False): - assert len(cls_scores) == len(bbox_preds) - num_levels = len(cls_scores) - featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] - - device = cls_scores[0].device - mlvl_anchors = self.get_anchors( - featmap_sizes, img_metas, device=device) - result_list = [] - for img_id in range(len(img_metas)): - cls_score_list = [ - cls_scores[i][img_id].detach() for i in range(num_levels) - ] - bbox_cls_pred_list = [ - bbox_preds[i][0][img_id].detach() for i in range(num_levels) - ] - bbox_reg_pred_list = [ - bbox_preds[i][1][img_id].detach() for i in range(num_levels) - ] - img_shape = img_metas[img_id]['img_shape'] - scale_factor = img_metas[img_id]['scale_factor'] - proposals = self.get_bboxes_single(cls_score_list, - bbox_cls_pred_list, - bbox_reg_pred_list, - mlvl_anchors[img_id], img_shape, - scale_factor, cfg, rescale) - result_list.append(proposals) - return result_list - - def get_bboxes_single(self, - cls_scores, - bbox_cls_preds, - bbox_reg_preds, - mlvl_anchors, - img_shape, - scale_factor, - cfg, - rescale=False): - cfg = self.test_cfg if cfg is None else cfg - mlvl_bboxes = [] - mlvl_scores = [] - mlvl_confids = [] - assert len(cls_scores) == len(bbox_cls_preds) == len( - bbox_reg_preds) == len(mlvl_anchors) - for cls_score, bbox_cls_pred, bbox_reg_pred, anchors in zip( - cls_scores, bbox_cls_preds, bbox_reg_preds, mlvl_anchors): - assert cls_score.size()[-2:] == bbox_cls_pred.size( - )[-2:] == bbox_reg_pred.size()[-2::] - cls_score = cls_score.permute(1, 2, - 0).reshape(-1, self.cls_out_channels) - if self.use_sigmoid_cls: - scores = cls_score.sigmoid() - else: - scores = cls_score.softmax(-1) - bbox_cls_pred = bbox_cls_pred.permute(1, 2, 0).reshape( - -1, self.side_num * 4) - bbox_reg_pred = bbox_reg_pred.permute(1, 2, 0).reshape( - -1, self.side_num * 4) - nms_pre = cfg.get('nms_pre', -1) - if nms_pre > 0 and scores.shape[0] > nms_pre: - if self.use_sigmoid_cls: - max_scores, _ = scores.max(dim=1) - else: - max_scores, _ = scores[:, :-1].max(dim=1) - _, topk_inds = max_scores.topk(nms_pre) - anchors = anchors[topk_inds, :] - bbox_cls_pred = bbox_cls_pred[topk_inds, :] - bbox_reg_pred = bbox_reg_pred[topk_inds, :] - scores = scores[topk_inds, :] - bbox_preds = [ - bbox_cls_pred.contiguous(), - bbox_reg_pred.contiguous() - ] - bboxes, confids = self.bbox_coder.decode( - anchors.contiguous(), bbox_preds, max_shape=img_shape) - mlvl_bboxes.append(bboxes) - mlvl_scores.append(scores) - mlvl_confids.append(confids) - mlvl_bboxes = torch.cat(mlvl_bboxes) - if rescale: - mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) - mlvl_scores = torch.cat(mlvl_scores) - mlvl_confids = torch.cat(mlvl_confids) - if self.use_sigmoid_cls: - padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) - mlvl_scores = torch.cat([mlvl_scores, padding], dim=1) - det_bboxes, det_labels = multiclass_nms( - mlvl_bboxes, - mlvl_scores, - cfg.score_thr, - cfg.nms, - cfg.max_per_img, - score_factors=mlvl_confids) - return det_bboxes, det_labels diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/losses/balanced_l1_loss.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/losses/balanced_l1_loss.py deleted file mode 100644 index 7bcd13ff26dbdc9f6eff8d7c7b5bde742a8d7d1d..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/losses/balanced_l1_loss.py +++ /dev/null @@ -1,120 +0,0 @@ -import mmcv -import numpy as np -import torch -import torch.nn as nn - -from ..builder import LOSSES -from .utils import weighted_loss - - -@mmcv.jit(derivate=True, coderize=True) -@weighted_loss -def balanced_l1_loss(pred, - target, - beta=1.0, - alpha=0.5, - gamma=1.5, - reduction='mean'): - """Calculate balanced L1 loss. - - Please see the `Libra R-CNN `_ - - Args: - pred (torch.Tensor): The prediction with shape (N, 4). - target (torch.Tensor): The learning target of the prediction with - shape (N, 4). - beta (float): The loss is a piecewise function of prediction and target - and ``beta`` serves as a threshold for the difference between the - prediction and target. Defaults to 1.0. - alpha (float): The denominator ``alpha`` in the balanced L1 loss. - Defaults to 0.5. - gamma (float): The ``gamma`` in the balanced L1 loss. - Defaults to 1.5. - reduction (str, optional): The method that reduces the loss to a - scalar. Options are "none", "mean" and "sum". - - Returns: - torch.Tensor: The calculated loss - """ - assert beta > 0 - assert pred.size() == target.size() and target.numel() > 0 - - diff = torch.abs(pred - target) - b = np.e**(gamma / alpha) - 1 - loss = torch.where( - diff < beta, alpha / b * - (b * diff + 1) * torch.log(b * diff / beta + 1) - alpha * diff, - gamma * diff + gamma / b - alpha * beta) - - return loss - - -@LOSSES.register_module() -class BalancedL1Loss(nn.Module): - """Balanced L1 Loss. - - arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019) - - Args: - alpha (float): The denominator ``alpha`` in the balanced L1 loss. - Defaults to 0.5. - gamma (float): The ``gamma`` in the balanced L1 loss. Defaults to 1.5. - beta (float, optional): The loss is a piecewise function of prediction - and target. ``beta`` serves as a threshold for the difference - between the prediction and target. Defaults to 1.0. - reduction (str, optional): The method that reduces the loss to a - scalar. Options are "none", "mean" and "sum". - loss_weight (float, optional): The weight of the loss. Defaults to 1.0 - """ - - def __init__(self, - alpha=0.5, - gamma=1.5, - beta=1.0, - reduction='mean', - loss_weight=1.0): - super(BalancedL1Loss, self).__init__() - self.alpha = alpha - self.gamma = gamma - self.beta = beta - self.reduction = reduction - self.loss_weight = loss_weight - - def forward(self, - pred, - target, - weight=None, - avg_factor=None, - reduction_override=None, - **kwargs): - """Forward function of loss. - - Args: - pred (torch.Tensor): The prediction with shape (N, 4). - target (torch.Tensor): The learning target of the prediction with - shape (N, 4). - weight (torch.Tensor, optional): Sample-wise loss weight with - shape (N, ). - avg_factor (int, optional): Average factor that is used to average - the loss. Defaults to None. - reduction_override (str, optional): The reduction method used to - override the original reduction method of the loss. - Options are "none", "mean" and "sum". - - Returns: - torch.Tensor: The calculated loss - """ - assert reduction_override in (None, 'none', 'mean', 'sum') - reduction = ( - reduction_override if reduction_override else self.reduction) - loss_bbox = self.loss_weight * balanced_l1_loss( - pred, - target, - weight, - alpha=self.alpha, - gamma=self.gamma, - beta=self.beta, - reduction=reduction, - avg_factor=avg_factor, - **kwargs) - return loss_bbox diff --git a/spaces/abionchito/rvc-models/infer_pack/transforms.py b/spaces/abionchito/rvc-models/infer_pack/transforms.py deleted file mode 100644 index a11f799e023864ff7082c1f49c0cc18351a13b47..0000000000000000000000000000000000000000 --- a/spaces/abionchito/rvc-models/infer_pack/transforms.py +++ /dev/null @@ -1,209 +0,0 @@ -import torch -from torch.nn import functional as F - -import numpy as np - - -DEFAULT_MIN_BIN_WIDTH = 1e-3 -DEFAULT_MIN_BIN_HEIGHT = 1e-3 -DEFAULT_MIN_DERIVATIVE = 1e-3 - - -def piecewise_rational_quadratic_transform( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails=None, - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if tails is None: - spline_fn = rational_quadratic_spline - spline_kwargs = {} - else: - spline_fn = unconstrained_rational_quadratic_spline - spline_kwargs = {"tails": tails, "tail_bound": tail_bound} - - outputs, logabsdet = spline_fn( - inputs=inputs, - unnormalized_widths=unnormalized_widths, - unnormalized_heights=unnormalized_heights, - unnormalized_derivatives=unnormalized_derivatives, - inverse=inverse, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - **spline_kwargs - ) - return outputs, logabsdet - - -def searchsorted(bin_locations, inputs, eps=1e-6): - bin_locations[..., -1] += eps - return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1 - - -def unconstrained_rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails="linear", - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) - - if tails == "linear": - unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) - constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives[..., 0] = constant - unnormalized_derivatives[..., -1] = constant - - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 - else: - raise RuntimeError("{} tails are not implemented.".format(tails)) - - ( - outputs[inside_interval_mask], - logabsdet[inside_interval_mask], - ) = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :], - inverse=inverse, - left=-tail_bound, - right=tail_bound, - bottom=-tail_bound, - top=tail_bound, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - ) - - return outputs, logabsdet - - -def rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - left=0.0, - right=1.0, - bottom=0.0, - top=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if torch.min(inputs) < left or torch.max(inputs) > right: - raise ValueError("Input to a transform is not within its domain") - - num_bins = unnormalized_widths.shape[-1] - - if min_bin_width * num_bins > 1.0: - raise ValueError("Minimal bin width too large for the number of bins") - if min_bin_height * num_bins > 1.0: - raise ValueError("Minimal bin height too large for the number of bins") - - widths = F.softmax(unnormalized_widths, dim=-1) - widths = min_bin_width + (1 - min_bin_width * num_bins) * widths - cumwidths = torch.cumsum(widths, dim=-1) - cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0) - cumwidths = (right - left) * cumwidths + left - cumwidths[..., 0] = left - cumwidths[..., -1] = right - widths = cumwidths[..., 1:] - cumwidths[..., :-1] - - derivatives = min_derivative + F.softplus(unnormalized_derivatives) - - heights = F.softmax(unnormalized_heights, dim=-1) - heights = min_bin_height + (1 - min_bin_height * num_bins) * heights - cumheights = torch.cumsum(heights, dim=-1) - cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0) - cumheights = (top - bottom) * cumheights + bottom - cumheights[..., 0] = bottom - cumheights[..., -1] = top - heights = cumheights[..., 1:] - cumheights[..., :-1] - - if inverse: - bin_idx = searchsorted(cumheights, inputs)[..., None] - else: - bin_idx = searchsorted(cumwidths, inputs)[..., None] - - input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0] - input_bin_widths = widths.gather(-1, bin_idx)[..., 0] - - input_cumheights = cumheights.gather(-1, bin_idx)[..., 0] - delta = heights / widths - input_delta = delta.gather(-1, bin_idx)[..., 0] - - input_derivatives = derivatives.gather(-1, bin_idx)[..., 0] - input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0] - - input_heights = heights.gather(-1, bin_idx)[..., 0] - - if inverse: - a = (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) + input_heights * (input_delta - input_derivatives) - b = input_heights * input_derivatives - (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) - c = -input_delta * (inputs - input_cumheights) - - discriminant = b.pow(2) - 4 * a * c - assert (discriminant >= 0).all() - - root = (2 * c) / (-b - torch.sqrt(discriminant)) - outputs = root * input_bin_widths + input_cumwidths - - theta_one_minus_theta = root * (1 - root) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * root.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - root).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, -logabsdet - else: - theta = (inputs - input_cumwidths) / input_bin_widths - theta_one_minus_theta = theta * (1 - theta) - - numerator = input_heights * ( - input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta - ) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - outputs = input_cumheights + numerator / denominator - - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * theta.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - theta).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, logabsdet diff --git a/spaces/abrar-adnan/vehicle-recognizer/app.py b/spaces/abrar-adnan/vehicle-recognizer/app.py deleted file mode 100644 index 3f642cb859b6ee22a72c5a0222aecebbe6fa9a5e..0000000000000000000000000000000000000000 --- a/spaces/abrar-adnan/vehicle-recognizer/app.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastai.vision.all import * -import gradio as gr - -# import pathlib -# temp = pathlib.PosixPath -# pathlib.PosixPath = pathlib.WindowsPath - -vehicle_labels = ( - 'ATV', - 'Airplane', - 'Ambulance', - 'Armored Tank', - 'Autorickshaw', - 'Bicycle', - 'Boat', - 'Buggy', - 'Bulldozer', - 'Cargo Ship', - 'Cargo Truck', - 'Crane', - 'Excavator', - 'Ferry', - 'Helicopter', - 'Hot Air Baloon', - 'Microbus', - 'Monster Truck', - 'Motorcycle', - 'Multi Purpose Vehicle', - 'Ocean Liner', - 'Police Car', - 'Private Car', - 'Rickshaw', - 'SUV', - 'Sail Boat', - 'Semi Truck', - 'Sports Car', - 'Steam Roller', - 'Train', - 'Transport Bus', - 'Truck', - 'Yacht' -) - -model = load_learner('vehicle-recognizer-v2.pkl') - -def recognize_image(image): - pred, idx, probs = model.predict(image) - return dict(zip(vehicle_labels, map(float, probs))) - -image = gr.inputs.Image(shape=(192,192)) -label = gr.outputs.Label(num_top_classes=5) -examples = [ - 'image1.jpg', - 'image2.jpg', - 'image3.jpg', - 'image4.jpg' - ] - -iface = gr.Interface(fn=recognize_image, inputs=image, outputs=label, examples=examples) -iface.launch(inline=False) \ No newline at end of file diff --git a/spaces/akhaliq/SummerTime/model/third_party/HMNet/Utils/HMNet/InfinibatchLoader.py b/spaces/akhaliq/SummerTime/model/third_party/HMNet/Utils/HMNet/InfinibatchLoader.py deleted file mode 100644 index 0200f5cb30d49571bc19d2ee970a8197a597e20d..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/SummerTime/model/third_party/HMNet/Utils/HMNet/InfinibatchLoader.py +++ /dev/null @@ -1,688 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -import os -import gzip -import numpy as np -from random import Random, shuffle, random -import torch -import math -from model.third_party.HMNet.DataLoader import iterators -import json -import struct -from timeit import default_timer as timer - -""" -Define different types of task here -""" - -MONO_TASKS = ["meeting"] # tasks that takes a singe sentence and reconstruct -TRANS_TASKS = ["sum"] # tasks that transfer a source sentence to a target sentence -ALL_TASKS = MONO_TASKS + TRANS_TASKS # all valid tasks - - -def _bump_seed(seed): - """ - Helper to bump a random seed if not None. - """ - return None if seed is None else seed + 1 - - -def HMNetBatchGen( - task_args, - dataset_label, - model_config=None, - tokenizer=None, - world_size=None, - rank=None, - seed=None, -): - """ - This example batch generater creates simple MLM training batches - It take paths to the dataset directories, and produce final iterator that yields tensors of a batch - It performs file reading, shuffling, tokenization, masking, batching, collating by nesting the iterators in the DataLoader infinibatch library - arguments: - task_args: a dict containing parameters for the task - dataset_label: train, dev, or test - model_config: model architecture config - tokenizer: a list of tokenizers - world_size, rank: GPU world size and rank for distributed training - Note: this batch generator does not move the batches to the GPU. The caller must do that as desired. - """ - - role_dict_file = os.path.join(task_args["datadir"], task_args["ROLE_DICT_FILE"]) - role_dict = json.load(open(role_dict_file)) - inv_role_dict = {v: k for k, v in role_dict.items()} - anon_roles = task_args.get( - "ANONYMOUS_ROLES", False - ) # whether to convert all speakers to speaker-0, speaker-1, ... - - dataset_file = os.path.join( - task_args["datadir"], task_args["{}_FILE".format(dataset_label.upper())] - ) - is_train = dataset_label == "train" - tokens_per_batch = task_args["MINI_BATCH"] * task_args["MAX_TRANSCRIPT_WORD"] - batch_read_ahead = task_args["BATCH_READ_AHEAD"] - doc_shuffle_buffer_size = task_args["DOC_SHUFFLE_BUF_SIZE"] - sample_shuffle_buffer_size = task_args["SAMPLE_SHUFFLE_BUFFER_SIZE"] - batch_shuffle_buffer_size = task_args["BATCH_SHUFFLE_BUFFER_SIZE"] - - max_padding_ratio = task_args.get("MAX_PADDING_RATIO", 1.0) - - max_gen_length = task_args.get("MAX_GEN_LENGTH", 200) - max_transcript_len = task_args.get("MAX_TRANSCRIPT_WORD", 8300) - max_sentence_len = task_args.get("MAX_SENT_LEN", 30) - max_sentence_num = task_args.get("MAX_SENT_NUM", 400) - - merge_summary_buffer_size = task_args.get("MERGE_SUMMARY_BUFFER_SIZE", 24) - merge_summary_num = task_args.get("MERGE_SUMMARY_NUM", 1) - merge_summary_shuffle = task_args.get("MERGE_SUMMARY_SHUFFLE", False) - - ############################### - # set up rank-aware chunk file path iterator - # this part can be used as is in all tasks - ############################### - # dataset_file is the path to a json file containing dataset information - data_sets = json.load(open(dataset_file, encoding="utf-8")) - - # get paths to all the chunk files in the source and target dataset dirs - datasets_chunks = [] - for i, data_set in enumerate(data_sets): - task = data_set["task"] - dataset_name = data_set["name"] - source = data_set["source"] - # to determine if use relative path to load dataset - if "USE_REL_DATA_PATH" in task_args: - source["dataset"] = os.path.join(task_args["datadir"], source["dataset"]) - source_chunk_files = [ - x for x in os.scandir(source["dataset"]) if x.name.endswith(".gz") - ] # enumerate all .gz files in the given paths - source_chunk_files.sort(key=lambda x: x.name) - if "target" in data_set: - target = data_set["target"] - if "USE_REL_DATA_PATH" in task_args: - target["dataset"] = os.path.join( - task_args["datadir"], target["dataset"] - ) - - target_chunk_files = [ - x for x in os.scandir(target["dataset"]) if x.name.endswith(".gz") - ] # enumerate all .gz files in the given paths - target_chunk_files.sort(key=lambda x: x.name) - assert len(source_chunk_files) == len( - target_chunk_files - ), f"Number of chunk files should be the same in source ({len(source_chunk_files)}) and target ({len(target_chunk_files)}) datasets." - assert all( - [ - s.name == t.name - for s, t in zip(source_chunk_files, target_chunk_files) - ] - ) - - datasets_chunks.append( - [ - { - "source": {"dataset": os.path.join(source["dataset"], s.name)}, - "target": { - "dataset": os.path.join(target["dataset"], t.name) - if target["dataset"] - else None - }, - "task": task, - "cid": i, # corpus id for corpus based metric computation during evaluation - "name": dataset_name, - } - for s, t in zip(source_chunk_files, target_chunk_files) - ] - ) - else: - datasets_chunks.append( - [ - { - "source": {"dataset": os.path.join(source["dataset"], s.name)}, - "task": task, - "cid": i, # corpus id for corpus based metric computation during evaluation - "name": dataset_name, - } - for s in source_chunk_files - ] - ) - - # create an iterator to iterate the chunk file paths in each dataset - if is_train: - for dataset_chunks in datasets_chunks: - dataset_chunks.sort( - key=lambda x: x["source"]["dataset"] - ) # make sure file order is always the same, independent of OS - datasets_chunks.sort( - key=lambda x: x[0]["source"]["dataset"] - ) # make sure file order is always the same, independent of OS - - for i, dataset_chunks in enumerate(datasets_chunks): - datasets_chunks[i] = iterators.InfinitePermutationSourceIterator( - dataset_chunks, - seed, - shuffle=True, - num_instances=world_size, - instance_rank=rank, - ) - else: - datasets_chunks = [ - [chunk for dataset_chunks in datasets_chunks for chunk in dataset_chunks] - ] # flatten the datasets - datasets_chunks[0].sort( - key=lambda x: x["source"]["dataset"] - ) # make sure file order is always the same, independent of OS - datasets_chunks[0] = iterators.ChunkedSourceIterator( - datasets_chunks[0], num_instances=world_size, instance_rank=rank - ) # in evaluation mode, the files are iterated once without shuffling, but still with parallelization - ############################### - - dataset_batch_read_ahead = max(1, batch_read_ahead // len(datasets_chunks)) - dataset_doc_shuffle_buffer_size = max( - 1, doc_shuffle_buffer_size // len(datasets_chunks) - ) - dataset_sample_shuffle_buffer_size = max( - 1, sample_shuffle_buffer_size // len(datasets_chunks) - ) - dataset_batch_shuffle_buffer_size = max( - 1, batch_shuffle_buffer_size // len(datasets_chunks) - ) - - ############################### - # set up document iterator from chunk file iterator - ############################### - # use SelectManyIterator to split each chunk file into multiple documents - def read_docs_from_chunk(chunk): - # this function is provided to the SelectManyIterator constructor as a callback - # it takes one item from the source iterator as input (one chunk in this case), and return an iterable (a list of documents), each item in the returned iterable will be yielded by the SelectManyIterator - docs = [] - doc = [] - cid = chunk["cid"] - task = chunk["task"] - source = chunk["source"] - name = chunk["name"] - with gzip.open(source["dataset"], "rt", encoding="utf-8") as fs: - if "target" in chunk: - target = chunk["target"] - if target["dataset"]: - with gzip.open(target["dataset"], "rt", encoding="utf-8") as ft: - for line_s, line_t in zip(fs, ft): - line_s, line_t = line_s.strip(), line_t.strip() - if line_s != "": - # take care of multiple reference, assume line_t is splitted by " ||| " - if is_train: - # for train, split references to multiple pairs - line_t_list = line_t.split(" ||| ") - else: - # for valid and test, not split - line_t_list = [line_t] - - for sub_line_t in line_t_list: - if ( - task == "sum" - and len(doc) >= merge_summary_buffer_size - ): - docs.append(doc) - doc = [] - elif (not task == "sum") and len(doc) > 0: - docs.append(doc) - doc = [] - doc.append( - { - "source": {"sequence": line_s}, - "target": {"sequence": sub_line_t}, - "task": task, - "cid": cid, - "name": name, - } - ) - - else: - for line in fs: - line = line.strip() - if len(doc) > 0: - docs.append(doc) - doc = [] - if line != "": - doc.append( - { - "source": {"sequence": line}, - "task": task, - "cid": cid, - "name": name, - } - ) - - if len(doc) > 0: - docs.append(doc) - return ( - docs # each doc in the docs list will be yielded by the SelectManyIterator - ) - - datasets_doc_samples = [] - for dataset_chunks in datasets_chunks: - datasets_doc_samples.append( - iterators.SelectManyIterator(dataset_chunks, read_docs_from_chunk) - ) - ############################### - - ############################### - # set up the doc randomizer - ############################### - # use BufferedShuffleIterator to shuffle the items from the source iterator - # We shuffle before the next steps since at startup, shuffling needs to fill a large buffers. Doing expensive operations afterwards will reduce startup time. - # the principle that determines a proper shuffle_buffer_size is: shuffle_buffer_size >> chunk_size - if is_train: - for i, doc_samples in enumerate(datasets_doc_samples): - seed = _bump_seed(seed) - datasets_doc_samples[i] = iterators.BufferedShuffleIterator( - doc_samples, dataset_doc_shuffle_buffer_size, seed - ) - ############################### - - def _parse_tags(parsed_text): - output = {"word": [], "pos_id": [], "ent_id": []} - - for token in parsed_text: - # [(token.text,token.idx) for token in parsed_sentence] - output["word"].append(_str(token.text)) - pos = token.tag_ - output["pos_id"].append(POS[pos] if pos in POS else 0) - - ent = ( - "O" - if token.ent_iob_ == "O" - else (token.ent_iob_ + "-" + token.ent_type_) - ) - output["ent_id"].append(ENT[ent] if ent in ENT else 0) - - word_idx = 0 - for sent in parsed_text.sents: - # output['sentences'].append((word_idx, word_idx + len(sent))) - word_idx += len(sent) - - assert word_idx == len(output["word"]) - assert len(output["word"]) > 0 - - return output - - def _str(s): - """Convert PTB tokens to normal tokens""" - if s.lower() == "-lrb-": - s = "(" - elif s.lower() == "-rrb-": - s = ")" - elif s.lower() == "-lsb-": - s = "[" - elif s.lower() == "-rsb-": - s = "]" - elif s.lower() == "-lcb-": - s = "{" - elif s.lower() == "-rcb-": - s = "}" - return s - - ############################### - # tokenize all sentences in a doc - ############################### - # use SamplingRandomMapIterator because it applies one-to-one mapping (new iterator take one document from source iterator, apply transform, and output it) with checkpointed random state - def tokenize(rand: Random, doc): - # this function is provided to the SamplingRandomMapIterator constructor as a callback - # it takes one item from the source iterator as input, and returns one processed item - # use the provided Random object for all random operations in the transform, because that random object is checkpointed. - start = timer() - for sample in doc: - if anon_roles: - sample_role_dict = {} - - source = sample["source"] - if sample["task"] == "sum": - # make pseduo meetings - turns = json.loads(source["sequence"]) - source["sequence"] = [] - sample["meeting"] = [] - for turn in turns: - turn["role"] = role_dict.get(sample["name"], 0) - sample["meeting"].append(turn) - source["sequence"].extend(turn["utt"]["word"]) - - target = sample["target"] - target["sequence"] = tokenizer.tokenize(target["sequence"]) - - elif sample["task"] == "meeting": - data = json.loads(source["sequence"]) - sample["meeting"] = [] - source["sequence"] = [] - - for turn in data["meeting"]: - if anon_roles: - if turn["role"] not in sample_role_dict: - sample_role_dict[turn["role"]] = len(sample_role_dict) - turn["role"] = role_dict.get( - "".format(sample_role_dict[turn["role"]]), 0 - ) - else: - turn["role"] = role_dict.get(turn["role"], 0) - sample["meeting"].append(turn) - assert isinstance(turn["utt"], dict), turn["utt"] - source["sequence"].extend(turn["utt"]["word"]) - - sample["target"] = {} - summary_str = " ".join(data["summary"]) - if anon_roles: - for role in sample_role_dict: - summary_str = summary_str.replace( - role, "".format(sample_role_dict[role]) - ) - sample["target"]["sequence"] = tokenizer.tokenize(summary_str) - - else: - assert False, f"Undefined Task {sample['task']}" - - doc = [ - sample - for sample in doc - if len(sample["source"]["sequence"]) > 0 - and ( - "target" not in sample - or sample["target"]["sequence"] is None - or len(sample["target"]["sequence"]) > 0 - ) - ] - end = timer() - # print('Tokenize takes {:06.2f} seconds'.format(end-start)) - return doc - - for i, doc_samples in enumerate(datasets_doc_samples): - seed = _bump_seed(seed) - datasets_doc_samples[i] = iterators.SamplingRandomMapIterator( - doc_samples, transform=tokenize, seed=seed - ) - ############################### - - ############################### - # shuffle samples from documents again - ############################### - if is_train: - for i, samples in enumerate(datasets_doc_samples): - seed = _bump_seed(seed) - datasets_doc_samples[i] = iterators.BufferedShuffleIterator( - samples, dataset_sample_shuffle_buffer_size, seed - ) - ############################### - - def concat_samples_in_doc(doc): - if len(doc) == 1: - # return for all meeting dataset and article dataset with one article per sample - return doc - - concat_sample = {} - concat_sample["source"] = {"sequence": []} - concat_sample["target"] = {"sequence": []} - concat_sample["meeting"] = [] - - ret_sample_list = [] - - count = 0 - for sample in doc: - for turn in sample["meeting"]: - # take the role add append '-n' for the n-th document - turn["role"] = role_dict.get( - inv_role_dict[turn["role"]] + "-{}".format(count), 0 - ) - concat_sample["meeting"].append(turn) - - concat_sample["source"]["sequence"].extend(sample["source"]["sequence"]) - concat_sample["target"]["sequence"].extend(sample["target"]["sequence"]) - - count += 1 - - if count >= merge_summary_num: - if merge_summary_shuffle and count > 1 and is_train: - shuffle(concat_sample["meeting"]) - ret_sample_list.append(concat_sample) - concat_sample = {} - concat_sample["source"] = {"sequence": []} - concat_sample["target"] = {"sequence": []} - concat_sample["meeting"] = [] - count = 0 - - return ret_sample_list - - datasets_samples = [] - for doc_samples in datasets_doc_samples: - datasets_samples.append( - iterators.SelectManyIterator(doc_samples, concat_samples_in_doc) - ) - - ############################### - # batching with dynamic batch size depending on the task - ############################### - def dynamic_batch_size(sample): - if is_train: - batch_size = tokens_per_batch // ( - len(sample["source"]["sequence"]) - + len(sample["target"]["sequence"]) - + 1 - ) - else: - batch_size = tokens_per_batch // ( - len(sample["source"]["sequence"]) + max_gen_length + 1 - ) - return max(1, batch_size) - - datasets_batches = [] - for i, samples in enumerate(datasets_samples): - seed = _bump_seed(seed) - datasets_batches.append( - iterators.BucketedReadaheadBatchIterator( - samples, - read_ahead=dataset_batch_read_ahead, - key=lambda x: len(x["source"]["sequence"]), - batch_size=dynamic_batch_size, - shuffle=is_train, - seed=seed, - ) - ) - ############################### - - ############################### - # create a zip iterator on all datasets - ############################### - # Use ZipIterator to zip datasets from different datasets. This is to make dataset-dependent tasks distributed evenly - datasets_batches_zip = iterators.ZipIterator(*tuple(datasets_batches)) - ############################### - - ############################### - # unzip batches from all datasets - ############################### - def unzip(datasets_batche): - return [batche for batche in datasets_batche] - - batches = iterators.SelectManyIterator(datasets_batches_zip, unzip) - ############################### - - ############################### - # set up the batch randomizer - ############################### - seed = _bump_seed(seed) - batches = iterators.BufferedShuffleIterator( - batches, batch_shuffle_buffer_size, seed - ) - ############################### - - def _pad_batch(batch): - # padding and generate final batch - x_sent_batch = [] - x_role_batch = [] - x_pos_batch = [] - x_ent_batch = [] - y_sent_batch = [] - - encoder_tokens, decoder_tokens = [], [] - - for datum in batch: - x_sent = [] - x_role = [] - x_pos = [] - x_ent = [] - - sample_input_tokens = [] - - total_word_len = 0 - total_sent_len = 0 - - assert len(datum["meeting"]) > 0 - for m in datum["meeting"]: # each m is actually a turn - words = m["utt"]["word"] - pos = m["utt"]["pos_id"] - ent = m["utt"]["ent_id"] - L = len(words) - # assert L < max_transcript_len, "a turn {} is longer than max_transcript_len".format(' '.join(words)) - if L > max_transcript_len: - # this is rarely happpened when a turn is super long - # in this case we just skip it to save memory - continue - if ( - total_word_len + L > max_transcript_len - or total_sent_len + 1 > max_sentence_num - ): - break - - sample_input_tokens.extend(words) - - for i in range(math.ceil(L / max_sentence_len)): - x_role.append(m["role"]) - sub_words = words[ - i * max_sentence_len : min((i + 1) * max_sentence_len, L) - ] - x_sent.append( - [tokenizer.bos_token] + sub_words + [tokenizer.eos_token] - ) - x_pos.append( - [0] - + pos[i * max_sentence_len : min((i + 1) * max_sentence_len, L)] - + [0] - ) - x_ent.append( - [0] - + ent[i * max_sentence_len : min((i + 1) * max_sentence_len, L)] - + [0] - ) - - total_sent_len += 1 - - total_word_len += L - - if is_train: # training - y_sent = ( - [tokenizer.bos_token] - + datum["target"]["sequence"][:max_gen_length] - + [tokenizer.eos_token] - ) - else: - y_sent = ( - [tokenizer.bos_token] - + datum["target"]["sequence"] - + [tokenizer.eos_token] - ) - - if len(x_sent) > 0: - # this could be false when there is a single but very long turn - x_sent_batch.append(x_sent) - x_role_batch.append(x_role) - x_pos_batch.append(x_pos) - x_ent_batch.append(x_ent) - y_sent_batch.append(y_sent) - - encoder_tokens.append(sample_input_tokens) - decoder_tokens.append(y_sent) - - if len(x_sent_batch) == 0: - # this could happen when there is a single but very long turn - # leading the whole batch with all instances filtered - return None - - # count max length - x_max_doc_len = max([len(s) for s in x_sent_batch]) - x_max_sent_len = max([max([len(t) for t in s]) for s in x_sent_batch]) - y_max_len = max([len(s) for s in y_sent_batch]) - x_role_max_len = max([len(s) for s in x_role_batch]) - actual_size = len(x_sent_batch) - - actual_tokens_per_batch = actual_size * ( - x_max_doc_len * x_max_sent_len + y_max_len - ) - - # if the actual batch size is too larger than expected because of skewed length - if (actual_tokens_per_batch / tokens_per_batch) > ( - max_padding_ratio + 1 - ) and is_train: - return None - - # create tensors - x_tensor = torch.LongTensor(actual_size, x_max_doc_len, x_max_sent_len).fill_( - tokenizer.pad_token_id - ) - x_pos_tensor = torch.LongTensor( - actual_size, x_max_doc_len, x_max_sent_len - ).fill_(0) - x_ent_tensor = torch.LongTensor( - actual_size, x_max_doc_len, x_max_sent_len - ).fill_(0) - x_role_tensor = torch.LongTensor(actual_size, x_role_max_len).fill_(0) - y_tensor = torch.LongTensor(actual_size, y_max_len).fill_( - tokenizer.pad_token_id - ) - - for i in range(len(x_sent_batch)): - for j in range(len(x_sent_batch[i])): - x_tensor[i, j, : len(x_sent_batch[i][j])] = torch.LongTensor( - tokenizer.convert_tokens_to_ids(x_sent_batch[i][j]) - ) - y_tensor[i, : len(y_sent_batch[i])] = torch.LongTensor( - tokenizer.convert_tokens_to_ids(y_sent_batch[i]) - ) - - for j in range(len(x_pos_batch[i])): - x_pos_tensor[i, j, : len(x_pos_batch[i][j])] = torch.LongTensor( - x_pos_batch[i][j] - ) - for j in range(len(x_ent_batch[i])): - x_ent_tensor[i, j, : len(x_ent_batch[i][j])] = torch.LongTensor( - x_ent_batch[i][j] - ) - - x_role_tensor[i, : len(x_role_batch[i])] = torch.LongTensor(x_role_batch[i]) - - return { - "encoder_input_ids": x_tensor, - "encoder_input_roles": x_role_tensor, - "encoder_input_pos": x_pos_tensor, - "encoder_input_ent": x_ent_tensor, - "decoder_input_ids": y_tensor, - "encoder_tokens": encoder_tokens, - "decoder_tokens": decoder_tokens, - } - - ############################### - # collate samples into padded rectangular tensors - ############################### - def collate(batch): - batch = _pad_batch(batch) - - if batch is None: - ret_batches = [] - else: - ret_batches = [batch] - - return ret_batches - - ############################### - # collate samples into padded rectangular tensors - ############################### - batches = iterators.SelectManyIterator(batches, collate) - ############################### - - return batches diff --git a/spaces/akhaliq/basil_mix/README.md b/spaces/akhaliq/basil_mix/README.md deleted file mode 100644 index a042210238578ef9af58692f9cd99c54d7185b53..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/basil_mix/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Basil Mix -emoji: 🏃 -colorFrom: gray -colorTo: indigo -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/akhaliq/yolov7/utils/aws/userdata.sh b/spaces/akhaliq/yolov7/utils/aws/userdata.sh deleted file mode 100644 index 5762ae575f5b64df9b438180840fce0a2bafec42..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/yolov7/utils/aws/userdata.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html -# This script will run only once on first instance start (for a re-start script see mime.sh) -# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir -# Use >300 GB SSD - -cd home/ubuntu -if [ ! -d yolor ]; then - echo "Running first-time script." # install dependencies, download COCO, pull Docker - git clone -b paper https://github.com/WongKinYiu/yolor && sudo chmod -R 777 yolor - cd yolor - bash data/scripts/get_coco.sh && echo "Data done." & - sudo docker pull nvcr.io/nvidia/pytorch:21.08-py3 && echo "Docker done." & - python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & - wait && echo "All tasks done." # finish background tasks -else - echo "Running re-start script." # resume interrupted runs - i=0 - list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' - while IFS= read -r id; do - ((i++)) - echo "restarting container $i: $id" - sudo docker start $id - # sudo docker exec -it $id python train.py --resume # single-GPU - sudo docker exec -d $id python utils/aws/resume.py # multi-scenario - done <<<"$list" -fi diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/cli/cmdoptions.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/cli/cmdoptions.py deleted file mode 100644 index b7e54f7c63c3355b5e2da338034f249b2e1c9e38..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/cli/cmdoptions.py +++ /dev/null @@ -1,1018 +0,0 @@ -""" -shared options and groups - -The principle here is to define options once, but *not* instantiate them -globally. One reason being that options with action='append' can carry state -between parses. pip parses general options twice internally, and shouldn't -pass on state. To be consistent, all options will follow this design. -""" - -# The following comment should be removed at some point in the future. -# mypy: strict-optional=False - -import logging -import os -import textwrap -from functools import partial -from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values -from textwrap import dedent -from typing import Any, Callable, Dict, Optional, Tuple - -from pip._vendor.packaging.utils import canonicalize_name - -from pip._internal.cli.parser import ConfigOptionParser -from pip._internal.cli.progress_bars import BAR_TYPES -from pip._internal.exceptions import CommandError -from pip._internal.locations import USER_CACHE_DIR, get_src_prefix -from pip._internal.models.format_control import FormatControl -from pip._internal.models.index import PyPI -from pip._internal.models.target_python import TargetPython -from pip._internal.utils.hashes import STRONG_HASHES -from pip._internal.utils.misc import strtobool - -logger = logging.getLogger(__name__) - - -def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None: - """ - Raise an option parsing error using parser.error(). - - Args: - parser: an OptionParser instance. - option: an Option instance. - msg: the error text. - """ - msg = f"{option} error: {msg}" - msg = textwrap.fill(" ".join(msg.split())) - parser.error(msg) - - -def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup: - """ - Return an OptionGroup object - group -- assumed to be dict with 'name' and 'options' keys - parser -- an optparse Parser - """ - option_group = OptionGroup(parser, group["name"]) - for option in group["options"]: - option_group.add_option(option()) - return option_group - - -def check_install_build_global( - options: Values, check_options: Optional[Values] = None -) -> None: - """Disable wheels if per-setup.py call options are set. - - :param options: The OptionParser options to update. - :param check_options: The options to check, if not supplied defaults to - options. - """ - if check_options is None: - check_options = options - - def getname(n: str) -> Optional[Any]: - return getattr(check_options, n, None) - - names = ["build_options", "global_options", "install_options"] - if any(map(getname, names)): - control = options.format_control - control.disallow_binaries() - logger.warning( - "Disabling all use of wheels due to the use of --build-option " - "/ --global-option / --install-option.", - ) - - -def check_dist_restriction(options: Values, check_target: bool = False) -> None: - """Function for determining if custom platform options are allowed. - - :param options: The OptionParser options. - :param check_target: Whether or not to check if --target is being used. - """ - dist_restriction_set = any( - [ - options.python_version, - options.platforms, - options.abis, - options.implementation, - ] - ) - - binary_only = FormatControl(set(), {":all:"}) - sdist_dependencies_allowed = ( - options.format_control != binary_only and not options.ignore_dependencies - ) - - # Installations or downloads using dist restrictions must not combine - # source distributions and dist-specific wheels, as they are not - # guaranteed to be locally compatible. - if dist_restriction_set and sdist_dependencies_allowed: - raise CommandError( - "When restricting platform and interpreter constraints using " - "--python-version, --platform, --abi, or --implementation, " - "either --no-deps must be set, or --only-binary=:all: must be " - "set and --no-binary must not be set (or must be set to " - ":none:)." - ) - - if check_target: - if dist_restriction_set and not options.target_dir: - raise CommandError( - "Can not use any platform or abi specific options unless " - "installing via '--target'" - ) - - -def _path_option_check(option: Option, opt: str, value: str) -> str: - return os.path.expanduser(value) - - -def _package_name_option_check(option: Option, opt: str, value: str) -> str: - return canonicalize_name(value) - - -class PipOption(Option): - TYPES = Option.TYPES + ("path", "package_name") - TYPE_CHECKER = Option.TYPE_CHECKER.copy() - TYPE_CHECKER["package_name"] = _package_name_option_check - TYPE_CHECKER["path"] = _path_option_check - - -########### -# options # -########### - -help_: Callable[..., Option] = partial( - Option, - "-h", - "--help", - dest="help", - action="help", - help="Show help.", -) - -debug_mode: Callable[..., Option] = partial( - Option, - "--debug", - dest="debug_mode", - action="store_true", - default=False, - help=( - "Let unhandled exceptions propagate outside the main subroutine, " - "instead of logging them to stderr." - ), -) - -isolated_mode: Callable[..., Option] = partial( - Option, - "--isolated", - dest="isolated_mode", - action="store_true", - default=False, - help=( - "Run pip in an isolated mode, ignoring environment variables and user " - "configuration." - ), -) - -require_virtualenv: Callable[..., Option] = partial( - Option, - "--require-virtualenv", - "--require-venv", - dest="require_venv", - action="store_true", - default=False, - help=( - "Allow pip to only run in a virtual environment; " - "exit with an error otherwise." - ), -) - -verbose: Callable[..., Option] = partial( - Option, - "-v", - "--verbose", - dest="verbose", - action="count", - default=0, - help="Give more output. Option is additive, and can be used up to 3 times.", -) - -no_color: Callable[..., Option] = partial( - Option, - "--no-color", - dest="no_color", - action="store_true", - default=False, - help="Suppress colored output.", -) - -version: Callable[..., Option] = partial( - Option, - "-V", - "--version", - dest="version", - action="store_true", - help="Show version and exit.", -) - -quiet: Callable[..., Option] = partial( - Option, - "-q", - "--quiet", - dest="quiet", - action="count", - default=0, - help=( - "Give less output. Option is additive, and can be used up to 3" - " times (corresponding to WARNING, ERROR, and CRITICAL logging" - " levels)." - ), -) - -progress_bar: Callable[..., Option] = partial( - Option, - "--progress-bar", - dest="progress_bar", - type="choice", - choices=list(BAR_TYPES.keys()), - default="on", - help=( - "Specify type of progress to be displayed [" - + "|".join(BAR_TYPES.keys()) - + "] (default: %default)" - ), -) - -log: Callable[..., Option] = partial( - PipOption, - "--log", - "--log-file", - "--local-log", - dest="log", - metavar="path", - type="path", - help="Path to a verbose appending log.", -) - -no_input: Callable[..., Option] = partial( - Option, - # Don't ask for input - "--no-input", - dest="no_input", - action="store_true", - default=False, - help="Disable prompting for input.", -) - -proxy: Callable[..., Option] = partial( - Option, - "--proxy", - dest="proxy", - type="str", - default="", - help="Specify a proxy in the form [user:passwd@]proxy.server:port.", -) - -retries: Callable[..., Option] = partial( - Option, - "--retries", - dest="retries", - type="int", - default=5, - help="Maximum number of retries each connection should attempt " - "(default %default times).", -) - -timeout: Callable[..., Option] = partial( - Option, - "--timeout", - "--default-timeout", - metavar="sec", - dest="timeout", - type="float", - default=15, - help="Set the socket timeout (default %default seconds).", -) - - -def exists_action() -> Option: - return Option( - # Option when path already exist - "--exists-action", - dest="exists_action", - type="choice", - choices=["s", "i", "w", "b", "a"], - default=[], - action="append", - metavar="action", - help="Default action when a path already exists: " - "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", - ) - - -cert: Callable[..., Option] = partial( - PipOption, - "--cert", - dest="cert", - type="path", - metavar="path", - help=( - "Path to PEM-encoded CA certificate bundle. " - "If provided, overrides the default. " - "See 'SSL Certificate Verification' in pip documentation " - "for more information." - ), -) - -client_cert: Callable[..., Option] = partial( - PipOption, - "--client-cert", - dest="client_cert", - type="path", - default=None, - metavar="path", - help="Path to SSL client certificate, a single file containing the " - "private key and the certificate in PEM format.", -) - -index_url: Callable[..., Option] = partial( - Option, - "-i", - "--index-url", - "--pypi-url", - dest="index_url", - metavar="URL", - default=PyPI.simple_url, - help="Base URL of the Python Package Index (default %default). " - "This should point to a repository compliant with PEP 503 " - "(the simple repository API) or a local directory laid out " - "in the same format.", -) - - -def extra_index_url() -> Option: - return Option( - "--extra-index-url", - dest="extra_index_urls", - metavar="URL", - action="append", - default=[], - help="Extra URLs of package indexes to use in addition to " - "--index-url. Should follow the same rules as " - "--index-url.", - ) - - -no_index: Callable[..., Option] = partial( - Option, - "--no-index", - dest="no_index", - action="store_true", - default=False, - help="Ignore package index (only looking at --find-links URLs instead).", -) - - -def find_links() -> Option: - return Option( - "-f", - "--find-links", - dest="find_links", - action="append", - default=[], - metavar="url", - help="If a URL or path to an html file, then parse for links to " - "archives such as sdist (.tar.gz) or wheel (.whl) files. " - "If a local path or file:// URL that's a directory, " - "then look for archives in the directory listing. " - "Links to VCS project URLs are not supported.", - ) - - -def trusted_host() -> Option: - return Option( - "--trusted-host", - dest="trusted_hosts", - action="append", - metavar="HOSTNAME", - default=[], - help="Mark this host or host:port pair as trusted, even though it " - "does not have valid or any HTTPS.", - ) - - -def constraints() -> Option: - return Option( - "-c", - "--constraint", - dest="constraints", - action="append", - default=[], - metavar="file", - help="Constrain versions using the given constraints file. " - "This option can be used multiple times.", - ) - - -def requirements() -> Option: - return Option( - "-r", - "--requirement", - dest="requirements", - action="append", - default=[], - metavar="file", - help="Install from the given requirements file. " - "This option can be used multiple times.", - ) - - -def editable() -> Option: - return Option( - "-e", - "--editable", - dest="editables", - action="append", - default=[], - metavar="path/url", - help=( - "Install a project in editable mode (i.e. setuptools " - '"develop mode") from a local project path or a VCS url.' - ), - ) - - -def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None: - value = os.path.abspath(value) - setattr(parser.values, option.dest, value) - - -src: Callable[..., Option] = partial( - PipOption, - "--src", - "--source", - "--source-dir", - "--source-directory", - dest="src_dir", - type="path", - metavar="dir", - default=get_src_prefix(), - action="callback", - callback=_handle_src, - help="Directory to check out editable projects into. " - 'The default in a virtualenv is "/src". ' - 'The default for global installs is "/src".', -) - - -def _get_format_control(values: Values, option: Option) -> Any: - """Get a format_control object.""" - return getattr(values, option.dest) - - -def _handle_no_binary( - option: Option, opt_str: str, value: str, parser: OptionParser -) -> None: - existing = _get_format_control(parser.values, option) - FormatControl.handle_mutual_excludes( - value, - existing.no_binary, - existing.only_binary, - ) - - -def _handle_only_binary( - option: Option, opt_str: str, value: str, parser: OptionParser -) -> None: - existing = _get_format_control(parser.values, option) - FormatControl.handle_mutual_excludes( - value, - existing.only_binary, - existing.no_binary, - ) - - -def no_binary() -> Option: - format_control = FormatControl(set(), set()) - return Option( - "--no-binary", - dest="format_control", - action="callback", - callback=_handle_no_binary, - type="str", - default=format_control, - help="Do not use binary packages. Can be supplied multiple times, and " - 'each time adds to the existing value. Accepts either ":all:" to ' - 'disable all binary packages, ":none:" to empty the set (notice ' - "the colons), or one or more package names with commas between " - "them (no colons). Note that some packages are tricky to compile " - "and may fail to install when this option is used on them.", - ) - - -def only_binary() -> Option: - format_control = FormatControl(set(), set()) - return Option( - "--only-binary", - dest="format_control", - action="callback", - callback=_handle_only_binary, - type="str", - default=format_control, - help="Do not use source packages. Can be supplied multiple times, and " - 'each time adds to the existing value. Accepts either ":all:" to ' - 'disable all source packages, ":none:" to empty the set, or one ' - "or more package names with commas between them. Packages " - "without binary distributions will fail to install when this " - "option is used on them.", - ) - - -platforms: Callable[..., Option] = partial( - Option, - "--platform", - dest="platforms", - metavar="platform", - action="append", - default=None, - help=( - "Only use wheels compatible with . Defaults to the " - "platform of the running system. Use this option multiple times to " - "specify multiple platforms supported by the target interpreter." - ), -) - - -# This was made a separate function for unit-testing purposes. -def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]: - """ - Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. - - :return: A 2-tuple (version_info, error_msg), where `error_msg` is - non-None if and only if there was a parsing error. - """ - if not value: - # The empty string is the same as not providing a value. - return (None, None) - - parts = value.split(".") - if len(parts) > 3: - return ((), "at most three version parts are allowed") - - if len(parts) == 1: - # Then we are in the case of "3" or "37". - value = parts[0] - if len(value) > 1: - parts = [value[0], value[1:]] - - try: - version_info = tuple(int(part) for part in parts) - except ValueError: - return ((), "each version part must be an integer") - - return (version_info, None) - - -def _handle_python_version( - option: Option, opt_str: str, value: str, parser: OptionParser -) -> None: - """ - Handle a provided --python-version value. - """ - version_info, error_msg = _convert_python_version(value) - if error_msg is not None: - msg = "invalid --python-version value: {!r}: {}".format( - value, - error_msg, - ) - raise_option_error(parser, option=option, msg=msg) - - parser.values.python_version = version_info - - -python_version: Callable[..., Option] = partial( - Option, - "--python-version", - dest="python_version", - metavar="python_version", - action="callback", - callback=_handle_python_version, - type="str", - default=None, - help=dedent( - """\ - The Python interpreter version to use for wheel and "Requires-Python" - compatibility checks. Defaults to a version derived from the running - interpreter. The version can be specified using up to three dot-separated - integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor - version can also be given as a string without dots (e.g. "37" for 3.7.0). - """ - ), -) - - -implementation: Callable[..., Option] = partial( - Option, - "--implementation", - dest="implementation", - metavar="implementation", - default=None, - help=( - "Only use wheels compatible with Python " - "implementation , e.g. 'pp', 'jy', 'cp', " - " or 'ip'. If not specified, then the current " - "interpreter implementation is used. Use 'py' to force " - "implementation-agnostic wheels." - ), -) - - -abis: Callable[..., Option] = partial( - Option, - "--abi", - dest="abis", - metavar="abi", - action="append", - default=None, - help=( - "Only use wheels compatible with Python abi , e.g. 'pypy_41'. " - "If not specified, then the current interpreter abi tag is used. " - "Use this option multiple times to specify multiple abis supported " - "by the target interpreter. Generally you will need to specify " - "--implementation, --platform, and --python-version when using this " - "option." - ), -) - - -def add_target_python_options(cmd_opts: OptionGroup) -> None: - cmd_opts.add_option(platforms()) - cmd_opts.add_option(python_version()) - cmd_opts.add_option(implementation()) - cmd_opts.add_option(abis()) - - -def make_target_python(options: Values) -> TargetPython: - target_python = TargetPython( - platforms=options.platforms, - py_version_info=options.python_version, - abis=options.abis, - implementation=options.implementation, - ) - - return target_python - - -def prefer_binary() -> Option: - return Option( - "--prefer-binary", - dest="prefer_binary", - action="store_true", - default=False, - help="Prefer older binary packages over newer source packages.", - ) - - -cache_dir: Callable[..., Option] = partial( - PipOption, - "--cache-dir", - dest="cache_dir", - default=USER_CACHE_DIR, - metavar="dir", - type="path", - help="Store the cache data in

.", -) - - -def _handle_no_cache_dir( - option: Option, opt: str, value: str, parser: OptionParser -) -> None: - """ - Process a value provided for the --no-cache-dir option. - - This is an optparse.Option callback for the --no-cache-dir option. - """ - # The value argument will be None if --no-cache-dir is passed via the - # command-line, since the option doesn't accept arguments. However, - # the value can be non-None if the option is triggered e.g. by an - # environment variable, like PIP_NO_CACHE_DIR=true. - if value is not None: - # Then parse the string value to get argument error-checking. - try: - strtobool(value) - except ValueError as exc: - raise_option_error(parser, option=option, msg=str(exc)) - - # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() - # converted to 0 (like "false" or "no") caused cache_dir to be disabled - # rather than enabled (logic would say the latter). Thus, we disable - # the cache directory not just on values that parse to True, but (for - # backwards compatibility reasons) also on values that parse to False. - # In other words, always set it to False if the option is provided in - # some (valid) form. - parser.values.cache_dir = False - - -no_cache: Callable[..., Option] = partial( - Option, - "--no-cache-dir", - dest="cache_dir", - action="callback", - callback=_handle_no_cache_dir, - help="Disable the cache.", -) - -no_deps: Callable[..., Option] = partial( - Option, - "--no-deps", - "--no-dependencies", - dest="ignore_dependencies", - action="store_true", - default=False, - help="Don't install package dependencies.", -) - -ignore_requires_python: Callable[..., Option] = partial( - Option, - "--ignore-requires-python", - dest="ignore_requires_python", - action="store_true", - help="Ignore the Requires-Python information.", -) - -no_build_isolation: Callable[..., Option] = partial( - Option, - "--no-build-isolation", - dest="build_isolation", - action="store_false", - default=True, - help="Disable isolation when building a modern source distribution. " - "Build dependencies specified by PEP 518 must be already installed " - "if this option is used.", -) - - -def _handle_no_use_pep517( - option: Option, opt: str, value: str, parser: OptionParser -) -> None: - """ - Process a value provided for the --no-use-pep517 option. - - This is an optparse.Option callback for the no_use_pep517 option. - """ - # Since --no-use-pep517 doesn't accept arguments, the value argument - # will be None if --no-use-pep517 is passed via the command-line. - # However, the value can be non-None if the option is triggered e.g. - # by an environment variable, for example "PIP_NO_USE_PEP517=true". - if value is not None: - msg = """A value was passed for --no-use-pep517, - probably using either the PIP_NO_USE_PEP517 environment variable - or the "no-use-pep517" config file option. Use an appropriate value - of the PIP_USE_PEP517 environment variable or the "use-pep517" - config file option instead. - """ - raise_option_error(parser, option=option, msg=msg) - - # Otherwise, --no-use-pep517 was passed via the command-line. - parser.values.use_pep517 = False - - -use_pep517: Any = partial( - Option, - "--use-pep517", - dest="use_pep517", - action="store_true", - default=None, - help="Use PEP 517 for building source distributions " - "(use --no-use-pep517 to force legacy behaviour).", -) - -no_use_pep517: Any = partial( - Option, - "--no-use-pep517", - dest="use_pep517", - action="callback", - callback=_handle_no_use_pep517, - default=None, - help=SUPPRESS_HELP, -) - -install_options: Callable[..., Option] = partial( - Option, - "--install-option", - dest="install_options", - action="append", - metavar="options", - help="Extra arguments to be supplied to the setup.py install " - 'command (use like --install-option="--install-scripts=/usr/local/' - 'bin"). Use multiple --install-option options to pass multiple ' - "options to setup.py install. If you are using an option with a " - "directory path, be sure to use absolute path.", -) - -build_options: Callable[..., Option] = partial( - Option, - "--build-option", - dest="build_options", - metavar="options", - action="append", - help="Extra arguments to be supplied to 'setup.py bdist_wheel'.", -) - -global_options: Callable[..., Option] = partial( - Option, - "--global-option", - dest="global_options", - action="append", - metavar="options", - help="Extra global options to be supplied to the setup.py " - "call before the install or bdist_wheel command.", -) - -no_clean: Callable[..., Option] = partial( - Option, - "--no-clean", - action="store_true", - default=False, - help="Don't clean up build directories.", -) - -pre: Callable[..., Option] = partial( - Option, - "--pre", - action="store_true", - default=False, - help="Include pre-release and development versions. By default, " - "pip only finds stable versions.", -) - -disable_pip_version_check: Callable[..., Option] = partial( - Option, - "--disable-pip-version-check", - dest="disable_pip_version_check", - action="store_true", - default=True, - help="Don't periodically check PyPI to determine whether a new version " - "of pip is available for download. Implied with --no-index.", -) - - -def _handle_merge_hash( - option: Option, opt_str: str, value: str, parser: OptionParser -) -> None: - """Given a value spelled "algo:digest", append the digest to a list - pointed to in a dict by the algo name.""" - if not parser.values.hashes: - parser.values.hashes = {} - try: - algo, digest = value.split(":", 1) - except ValueError: - parser.error( - "Arguments to {} must be a hash name " # noqa - "followed by a value, like --hash=sha256:" - "abcde...".format(opt_str) - ) - if algo not in STRONG_HASHES: - parser.error( - "Allowed hash algorithms for {} are {}.".format( # noqa - opt_str, ", ".join(STRONG_HASHES) - ) - ) - parser.values.hashes.setdefault(algo, []).append(digest) - - -hash: Callable[..., Option] = partial( - Option, - "--hash", - # Hash values eventually end up in InstallRequirement.hashes due to - # __dict__ copying in process_line(). - dest="hashes", - action="callback", - callback=_handle_merge_hash, - type="string", - help="Verify that the package's archive matches this " - "hash before installing. Example: --hash=sha256:abcdef...", -) - - -require_hashes: Callable[..., Option] = partial( - Option, - "--require-hashes", - dest="require_hashes", - action="store_true", - default=False, - help="Require a hash to check each requirement against, for " - "repeatable installs. This option is implied when any package in a " - "requirements file has a --hash option.", -) - - -list_path: Callable[..., Option] = partial( - PipOption, - "--path", - dest="path", - type="path", - action="append", - help="Restrict to the specified installation path for listing " - "packages (can be used multiple times).", -) - - -def check_list_path_option(options: Values) -> None: - if options.path and (options.user or options.local): - raise CommandError("Cannot combine '--path' with '--user' or '--local'") - - -list_exclude: Callable[..., Option] = partial( - PipOption, - "--exclude", - dest="excludes", - action="append", - metavar="package", - type="package_name", - help="Exclude specified package from the output", -) - - -no_python_version_warning: Callable[..., Option] = partial( - Option, - "--no-python-version-warning", - dest="no_python_version_warning", - action="store_true", - default=False, - help="Silence deprecation warnings for upcoming unsupported Pythons.", -) - - -use_new_feature: Callable[..., Option] = partial( - Option, - "--use-feature", - dest="features_enabled", - metavar="feature", - action="append", - default=[], - choices=["2020-resolver", "fast-deps", "in-tree-build"], - help="Enable new functionality, that may be backward incompatible.", -) - -use_deprecated_feature: Callable[..., Option] = partial( - Option, - "--use-deprecated", - dest="deprecated_features_enabled", - metavar="feature", - action="append", - default=[], - choices=[ - "legacy-resolver", - "out-of-tree-build", - "backtrack-on-build-failures", - "html5lib", - ], - help=("Enable deprecated functionality, that will be removed in the future."), -) - - -########## -# groups # -########## - -general_group: Dict[str, Any] = { - "name": "General Options", - "options": [ - help_, - debug_mode, - isolated_mode, - require_virtualenv, - verbose, - version, - quiet, - log, - no_input, - proxy, - retries, - timeout, - exists_action, - trusted_host, - cert, - client_cert, - cache_dir, - no_cache, - disable_pip_version_check, - no_color, - no_python_version_warning, - use_new_feature, - use_deprecated_feature, - ], -} - -index_group: Dict[str, Any] = { - "name": "Package Index Options", - "options": [ - index_url, - extra_index_url, - no_index, - find_links, - ], -} diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/commands/check.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/commands/check.py deleted file mode 100644 index 3864220b2b4a2fd3803bdff0ab9e4c3941c1f313..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/commands/check.py +++ /dev/null @@ -1,53 +0,0 @@ -import logging -from optparse import Values -from typing import List - -from pip._internal.cli.base_command import Command -from pip._internal.cli.status_codes import ERROR, SUCCESS -from pip._internal.operations.check import ( - check_package_set, - create_package_set_from_installed, -) -from pip._internal.utils.misc import write_output - -logger = logging.getLogger(__name__) - - -class CheckCommand(Command): - """Verify installed packages have compatible dependencies.""" - - usage = """ - %prog [options]""" - - def run(self, options: Values, args: List[str]) -> int: - - package_set, parsing_probs = create_package_set_from_installed() - missing, conflicting = check_package_set(package_set) - - for project_name in missing: - version = package_set[project_name].version - for dependency in missing[project_name]: - write_output( - "%s %s requires %s, which is not installed.", - project_name, - version, - dependency[0], - ) - - for project_name in conflicting: - version = package_set[project_name].version - for dep_name, dep_version, req in conflicting[project_name]: - write_output( - "%s %s has requirement %s, but you have %s %s.", - project_name, - version, - req, - dep_name, - dep_version, - ) - - if missing or conflicting or parsing_probs: - return ERROR - else: - write_output("No broken requirements found.") - return SUCCESS diff --git a/spaces/ali-ghamdan/realesrgan-models/realesrgan/__init__.py b/spaces/ali-ghamdan/realesrgan-models/realesrgan/__init__.py deleted file mode 100644 index 544045c0f36e03e8b253eb41dfaa12d390f60544..0000000000000000000000000000000000000000 --- a/spaces/ali-ghamdan/realesrgan-models/realesrgan/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# flake8: noqa -from .archs import * -from .data import * -from .models import * -from .utils import * -# from .version import * diff --git a/spaces/amish1729/LFUNet/utils/__init__.py b/spaces/amish1729/LFUNet/utils/__init__.py deleted file mode 100644 index 4d39236dacfed2f2125fd41156de2fa3755f3cd9..0000000000000000000000000000000000000000 --- a/spaces/amish1729/LFUNet/utils/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -import numpy as np -from PIL import Image -import requests -import functools -from tqdm.notebook import tqdm -import shutil - -def image_to_array(image: Image) -> np.ndarray: - """Convert Image to array""" - return np.asarray(image).astype('uint8') - - -def load_image(img_path: str) -> Image: - """Load image to array""" - return Image.open(img_path) - - -def download_data(url, save_path, file_size=None): - """Downloads data from `url` to `save_path`""" - r = requests.get(url, stream=True, allow_redirects=True) - if r.status_code != 200: - r.raise_for_status() - raise RuntimeError(f'Request to {url} returned status code {r.status_code}') - - if file_size is None: - file_size = int(r.headers.get('content-length', 0)) - - r.raw.read = functools.partial(r.raw.read, decode_content=True) # Decompress if needed - with tqdm.wrapattr(r.raw, 'read', total=file_size, desc='') as r_raw: - with open(save_path, 'wb') as f: - shutil.copyfileobj(r_raw, f) - -def plot_image_triple(): - pass \ No newline at end of file diff --git a/spaces/andryMLOPS/ASTA-GPT-3.8_web_ui/client/css/message.css b/spaces/andryMLOPS/ASTA-GPT-3.8_web_ui/client/css/message.css deleted file mode 100644 index 64e04147ee4d1e76dda4f39c4f756c9da63e3874..0000000000000000000000000000000000000000 --- a/spaces/andryMLOPS/ASTA-GPT-3.8_web_ui/client/css/message.css +++ /dev/null @@ -1,65 +0,0 @@ -.message { - width: 100%; - overflow-wrap: break-word; - display: flex; - gap: var(--section-gap); - padding: var(--section-gap); - padding-bottom: 0; -} - -.message:last-child { - animation: 0.6s show_message; -} - -@keyframes show_message { - from { - transform: translateY(10px); - opacity: 0; - } -} - -.message .avatar-container img { - max-width: 48px; - max-height: 48px; - box-shadow: 0.4px 0.5px 0.7px -2px rgba(0, 0, 0, 0.08), 1.1px 1.3px 2px -2px rgba(0, 0, 0, 0.041), - 2.7px 3px 4.8px -2px rgba(0, 0, 0, 0.029), 9px 10px 16px -2px rgba(0, 0, 0, 0.022); -} - -.message .content { - display: flex; - flex-direction: column; - width: 90%; - gap: 18px; -} - -.message .content p, -.message .content li, -.message .content code { - font-size: 1rem; - line-height: 1.3; -} - -@media screen and (max-height: 720px) { - .message { - padding: 12px; - gap: 0; - } - - .message .content { - margin-left: 8px; - width: 80%; - } - - .message .avatar-container img { - max-width: 32px; - max-height: 32px; - } - - .message .content, - .message .content p, - .message .content li, - .message .content code { - font-size: 0.875rem; - line-height: 1.3; - } -} diff --git a/spaces/antonovmaxim/text-generation-webui-space/docs/Chat-mode.md b/spaces/antonovmaxim/text-generation-webui-space/docs/Chat-mode.md deleted file mode 100644 index 08dd290dadbd8a590ace65d557b8916a2707fc26..0000000000000000000000000000000000000000 --- a/spaces/antonovmaxim/text-generation-webui-space/docs/Chat-mode.md +++ /dev/null @@ -1,45 +0,0 @@ -## Chat characters - -Custom chat mode characters are defined by `.yaml` files inside the `characters` folder. An example is included: [Example.yaml](https://github.com/oobabooga/text-generation-webui/blob/main/characters/Example.yaml) - -The following fields may be defined: - -| Field | Description | -|-------|-------------| -| `name` or `bot` | The character's name. | -| `your_name` or `user` (optional) | Your name. This overwrites what you had previously written in the `Your name` field in the interface. | -| `context` | A string that appears at the top of the prompt. It usually contains a description of the character's personality. | -| `greeting` (optional) | The character's opening message when a new conversation is started. | -| `example_dialogue` (optional) | A few example messages to guide the model. | -| `turn_template` (optional) | Used to define where the spaces and new line characters should be in Instruct mode. See the characters in `characters/instruction-following` for examples. | - -#### Special tokens - -* `{{char}}` or ``: are replaced with the character's name -* `{{user}}` or ``: are replaced with your name - -These replacements happen when the character is loaded, and they apply to the `context`, `greeting`, and `example_dialogue` fields. - -#### How do I add a profile picture for my character? - -Put an image with the same name as your character's yaml file into the `characters` folder. For example, if your bot is `Character.yaml`, add `Character.jpg` or `Character.png` to the folder. - -#### Is the chat history truncated in the prompt? - -Once your prompt reaches the 2048 token limit, old messages will be removed one at a time. The context string will always stay at the top of the prompt and will never get truncated. - -#### Pygmalion format characters - -These are also supported out of the box. Simply put the JSON file in the `characters` folder, or upload it directly from the web UI by clicking on the "Upload character" tab at the bottom. - -## Chat styles - -Custom chat styles can be defined in the `text-generation-webui/css` folder. Simply create a new file with name starting in `chat_style-` and ending in `.css` and it will automatically appear in the "Chat style" dropdown menu in the interface. Examples: - -``` -chat_style-cai-chat.css -chat_style-TheEncrypted777.css -chat_style-wpp.css -``` - -You should use the same class names as in `chat_style-cai-chat.css` in your custom style. \ No newline at end of file diff --git a/spaces/antonovmaxim/text-generation-webui-space/extensions/gallery/script.py b/spaces/antonovmaxim/text-generation-webui-space/extensions/gallery/script.py deleted file mode 100644 index 993ef273839e7cfbf9e80f2d7f9d4a71d208b446..0000000000000000000000000000000000000000 --- a/spaces/antonovmaxim/text-generation-webui-space/extensions/gallery/script.py +++ /dev/null @@ -1,96 +0,0 @@ -from pathlib import Path - -import gradio as gr - -from modules.html_generator import get_image_cache -from modules.shared import gradio - - -def generate_css(): - css = """ - .character-gallery > .gallery { - margin: 1rem 0; - display: grid !important; - grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); - grid-column-gap: 0.4rem; - grid-row-gap: 1.2rem; - } - - .character-gallery > .label { - display: none !important; - } - - .character-gallery button.gallery-item { - display: contents; - } - - .character-container { - cursor: pointer; - text-align: center; - position: relative; - opacity: 0.85; - } - - .character-container:hover { - opacity: 1; - } - - .character-container .placeholder, .character-container img { - width: 150px; - height: 200px; - background-color: gray; - object-fit: cover; - margin: 0 auto; - border-radius: 1rem; - border: 3px solid white; - box-shadow: 3px 3px 6px 0px rgb(0 0 0 / 50%); - } - - .character-name { - margin-top: 0.3rem; - display: block; - font-size: 1.2rem; - font-weight: 600; - overflow-wrap: anywhere; - } - """ - return css - - -def generate_html(): - cards = [] - # Iterate through files in image folder - for file in sorted(Path("characters").glob("*")): - if file.suffix in [".json", ".yml", ".yaml"]: - character = file.stem - container_html = '
' - image_html = "
" - - for path in [Path(f"characters/{character}.{extension}") for extension in ['png', 'jpg', 'jpeg']]: - if path.exists(): - image_html = f'' - break - - container_html += f'{image_html} {character}' - container_html += "
" - cards.append([container_html, character]) - - return cards - - -def select_character(evt: gr.SelectData): - return (evt.value[1]) - - -def ui(): - with gr.Accordion("Character gallery", open=False): - update = gr.Button("Refresh") - gr.HTML(value="") - gallery = gr.Dataset(components=[gr.HTML(visible=False)], - label="", - samples=generate_html(), - elem_classes=["character-gallery"], - samples_per_page=50 - ) - update.click(generate_html, [], gallery) - gallery.select(select_character, None, gradio['character_menu']) diff --git a/spaces/anzorq/point-e_demo/app.py b/spaces/anzorq/point-e_demo/app.py deleted file mode 100644 index c47ba2183d689064240e8e2b5b05f6aedff97ec8..0000000000000000000000000000000000000000 --- a/spaces/anzorq/point-e_demo/app.py +++ /dev/null @@ -1,287 +0,0 @@ -import os -from PIL import Image -import torch - -from point_e.diffusion.configs import DIFFUSION_CONFIGS, diffusion_from_config -from point_e.diffusion.sampler import PointCloudSampler -from point_e.models.download import load_checkpoint -from point_e.models.configs import MODEL_CONFIGS, model_from_config -from point_e.util.plotting import plot_point_cloud -from point_e.util.pc_to_mesh import marching_cubes_mesh - -import skimage.measure - -from pyntcloud import PyntCloud -import matplotlib.colors -import plotly.graph_objs as go - -import trimesh - -import gradio as gr - - -state = "" -device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') - -def set_state(s): - print(s) - global state - state = s - -def get_state(): - return state - -set_state('Creating txt2mesh model...') -t2m_name = 'base40M-textvec' -t2m_model = model_from_config(MODEL_CONFIGS[t2m_name], device) -t2m_model.eval() -base_diffusion_t2m = diffusion_from_config(DIFFUSION_CONFIGS[t2m_name]) - -set_state('Downloading txt2mesh checkpoint...') -t2m_model.load_state_dict(load_checkpoint(t2m_name, device)) - - -def load_img2mesh_model(model_name): - set_state(f'Creating img2mesh model {model_name}...') - i2m_name = model_name - i2m_model = model_from_config(MODEL_CONFIGS[i2m_name], device) - i2m_model.eval() - base_diffusion_i2m = diffusion_from_config(DIFFUSION_CONFIGS[i2m_name]) - - set_state(f'Downloading img2mesh checkpoint {model_name}...') - i2m_model.load_state_dict(load_checkpoint(i2m_name, device)) - - return i2m_model, base_diffusion_i2m - -img2mesh_model_name = 'base40M' #'base300M' #'base1B' -i2m_model, base_diffusion_i2m = load_img2mesh_model(img2mesh_model_name) - - -set_state('Creating upsample model...') -upsampler_model = model_from_config(MODEL_CONFIGS['upsample'], device) -upsampler_model.eval() -upsampler_diffusion = diffusion_from_config(DIFFUSION_CONFIGS['upsample']) - -set_state('Downloading upsampler checkpoint...') -upsampler_model.load_state_dict(load_checkpoint('upsample', device)) - -set_state('Creating SDF model...') -sdf_name = 'sdf' -sdf_model = model_from_config(MODEL_CONFIGS[sdf_name], device) -sdf_model.eval() - -set_state('Loading SDF model...') -sdf_model.load_state_dict(load_checkpoint(sdf_name, device)) - -stable_diffusion = gr.Blocks.load(name="spaces/runwayml/stable-diffusion-v1-5") - - -set_state('') - -def get_sampler(model_name, txt2obj, guidance_scale): - - global img2mesh_model_name - global base_diffusion_i2m - global i2m_model - if model_name != img2mesh_model_name: - img2mesh_model_name = model_name - i2m_model, base_diffusion_i2m = load_img2mesh_model(model_name) - - return PointCloudSampler( - device=device, - models=[t2m_model if txt2obj else i2m_model, upsampler_model], - diffusions=[base_diffusion_t2m if txt2obj else base_diffusion_i2m, upsampler_diffusion], - num_points=[1024, 4096 - 1024], - aux_channels=['R', 'G', 'B'], - guidance_scale=[guidance_scale, 0.0 if txt2obj else guidance_scale], - model_kwargs_key_filter=('texts', '') if txt2obj else ("*",) - ) - -def generate_txt2img(prompt): - - prompt = f"“a 3d rendering of {prompt}, full view, white background" - gallery_dir = stable_diffusion(prompt, fn_index=2) - imgs = [os.path.join(gallery_dir, img) for img in os.listdir(gallery_dir) if os.path.splitext(img)[1] == '.jpg'] - - return imgs[0], gr.update(visible=True) - -def generate_3D(input, model_name='base40M', guidance_scale=3.0, grid_size=32): - - set_state('Entered generate function...') - - if isinstance(input, Image.Image): - input = prepare_img(input) - - # if input is a string, it's a text prompt - sampler = get_sampler(model_name, txt2obj=True if isinstance(input, str) else False, guidance_scale=guidance_scale) - - # Produce a sample from the model. - set_state('Sampling...') - samples = None - kw_args = dict(texts=[input]) if isinstance(input, str) else dict(images=[input]) - for x in sampler.sample_batch_progressive(batch_size=1, model_kwargs=kw_args): - samples = x - - set_state('Converting to point cloud...') - pc = sampler.output_to_point_clouds(samples)[0] - - set_state('Saving point cloud...') - with open("point_cloud.ply", "wb") as f: - pc.write_ply(f) - - set_state('Converting to mesh...') - save_ply(pc, 'mesh.ply', grid_size) - - set_state('') - - return pc_to_plot(pc), ply_to_obj('mesh.ply', '3d_model.obj'), gr.update(value=['3d_model.obj', 'mesh.ply', 'point_cloud.ply'], visible=True) - -def prepare_img(img): - - w, h = img.size - if w > h: - img = img.crop((w - h) / 2, 0, w - (w - h) / 2, h) - else: - img = img.crop((0, (h - w) / 2, w, h - (h - w) / 2)) - - # resize to 256x256 - img = img.resize((256, 256)) - - return img - -def pc_to_plot(pc): - - return go.Figure( - data=[ - go.Scatter3d( - x=pc.coords[:,0], y=pc.coords[:,1], z=pc.coords[:,2], - mode='markers', - marker=dict( - size=2, - color=['rgb({},{},{})'.format(r,g,b) for r,g,b in zip(pc.channels["R"], pc.channels["G"], pc.channels["B"])], - ) - ) - ], - layout=dict( - scene=dict(xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False)) - ), - ) - -def ply_to_obj(ply_file, obj_file): - mesh = trimesh.load(ply_file) - mesh.export(obj_file) - - return obj_file - -def save_ply(pc, file_name, grid_size): - - # Produce a mesh (with vertex colors) - mesh = marching_cubes_mesh( - pc=pc, - model=sdf_model, - batch_size=4096, - grid_size=grid_size, # increase to 128 for resolution used in evals - fill_vertex_channels=True, - progress=True, - ) - - # Write the mesh to a PLY file to import into some other program. - with open(file_name, 'wb') as f: - mesh.write_ply(f) - - -with gr.Blocks() as app: - gr.Markdown("## Point-E text-to-3D Demo") - gr.Markdown("This is a demo for [Point-E: A System for Generating 3D Point Clouds from Complex Prompts](https://arxiv.org/abs/2212.08751) by OpenAI. Check out the [GitHub repo](https://github.com/openai/point-e) for more information.") - gr.HTML("""To skip the queue you can duplicate this space: -
Duplicate Space -
Don't forget to change space hardware to GPU after duplicating it.""") - - with gr.Row(): - with gr.Column(): - with gr.Tab("Text to 3D"): - prompt = gr.Textbox(label="Prompt", placeholder="A cactus in a pot") - btn_generate_txt2obj = gr.Button(value="Generate") - - with gr.Tab("Image to 3D"): - img = gr.Image(label="Image") - gr.Markdown("Best results with images of 3D objects with no shadows on a white background.") - btn_generate_img2obj = gr.Button(value="Generate") - - with gr.Tab("Text to Image to 3D"): - gr.Markdown("Generate an image with Stable Diffusion, then convert it to 3D. Just enter the object you want to generate.") - prompt_sd = gr.Textbox(label="Prompt", placeholder="a 3d rendering of [your prompt], full view, white background") - btn_generate_txt2sd = gr.Button(value="Generate image") - img_sd = gr.Image(label="Image") - btn_generate_sd2obj = gr.Button(value="Convert to 3D", visible=False) - - with gr.Accordion("Advanced settings", open=False): - dropdown_models = gr.Dropdown(label="Model", value="base40M", choices=["base40M", "base300M"]) #, "base1B"]) - guidance_scale = gr.Slider(label="Guidance scale", value=3.0, minimum=3.0, maximum=10.0, step=0.1) - grid_size = gr.Slider(label="Grid size (for .obj 3D model)", value=32, minimum=16, maximum=128, step=16) - - with gr.Column(): - plot = gr.Plot(label="Point cloud") - # btn_pc_to_obj = gr.Button(value="Convert to OBJ", visible=False) - model_3d = gr.Model3D(value=None) - file_out = gr.File(label="Files", visible=False) - - # state_info = state_info = gr.Textbox(label="State", show_label=False).style(container=False) - - - # inputs = [dropdown_models, prompt, img, guidance_scale, grid_size] - outputs = [plot, model_3d, file_out] - - prompt.submit(generate_3D, inputs=[prompt, dropdown_models, guidance_scale, grid_size], outputs=outputs) - btn_generate_txt2obj.click(generate_3D, inputs=[prompt, dropdown_models, guidance_scale, grid_size], outputs=outputs, api_name="generate_txt2obj") - - btn_generate_img2obj.click(generate_3D, inputs=[img, dropdown_models, guidance_scale, grid_size], outputs=outputs, api_name="generate_img2obj") - - prompt_sd.submit(generate_txt2img, inputs=prompt_sd, outputs=[img_sd, btn_generate_sd2obj]) - btn_generate_txt2sd.click(generate_txt2img, inputs=prompt_sd, outputs=[img_sd, btn_generate_sd2obj], queue=False) - btn_generate_sd2obj.click(generate_3D, inputs=[img, dropdown_models, guidance_scale, grid_size], outputs=outputs) - - # btn_pc_to_obj.click(ply_to_obj, inputs=plot, outputs=[model_3d, file_out]) - - gr.Examples( - examples=[ - ["a cactus in a pot"], - ["a round table with floral tablecloth"], - ["a red kettle"], - ["a vase with flowers"], - ["a sports car"], - ["a man"], - ], - inputs=[prompt], - outputs=outputs, - fn=generate_3D, - cache_examples=True - ) - - gr.Examples( - examples=[ - ["images/corgi.png"], - ["images/cube_stack.jpg"], - ["images/chair.png"], - ], - inputs=[img], - outputs=outputs, - fn=generate_3D, - cache_examples=True - ) - - # app.load(get_state, inputs=[], outputs=state_info, every=0.5, show_progress=False) - - gr.HTML(""" -

-
-
-

Space by:
- Twitter Follow
- GitHub followers


- Buy Me A Coffee

-

visitors

-
- """) - -app.queue(max_size=250, concurrency_count=6).launch() diff --git a/spaces/aodianyun/stable-diffusion-webui/modules/face_restoration.py b/spaces/aodianyun/stable-diffusion-webui/modules/face_restoration.py deleted file mode 100644 index 2c86c6ccce338a1411f4367a0bc6e4046ad67cae..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/stable-diffusion-webui/modules/face_restoration.py +++ /dev/null @@ -1,19 +0,0 @@ -from modules import shared - - -class FaceRestoration: - def name(self): - return "None" - - def restore(self, np_image): - return np_image - - -def restore_faces(np_image): - face_restorers = [x for x in shared.face_restorers if x.name() == shared.opts.face_restoration_model or shared.opts.face_restoration_model is None] - if len(face_restorers) == 0: - return np_image - - face_restorer = face_restorers[0] - - return face_restorer.restore(np_image) diff --git a/spaces/argilla/argilla-streamlit-customs/my_app/pages/autotrain-project.py b/spaces/argilla/argilla-streamlit-customs/my_app/pages/autotrain-project.py deleted file mode 100644 index 1a4998ce4c52ff39227b041c3ff227867dedc931..0000000000000000000000000000000000000000 --- a/spaces/argilla/argilla-streamlit-customs/my_app/pages/autotrain-project.py +++ /dev/null @@ -1,139 +0,0 @@ - -import argilla as rg -import streamlit as st -from huggingface_hub import ModelFilter -from utils.autotrain import get_projects, schedule_retrain, task_id_mapping -from utils.commons import ( - argilla_login_flow, - get_data_snapshot, - get_dataset_list, - hf_login_flow, -) - -st.set_page_config( - page_title="Argilla - 🦾 - AutoTrain Project", - page_icon="🦾", - layout="wide", -) - - -api_url, api_key = argilla_login_flow("🦾 AutoTrain Project") - -st.write( - """ - This page allows you to train a model using [AutoTrain](https://ui.autotrain.huggingface.co) wihout using any code based on you Argilla datasets! - In the background it uses `argilla.load().prepare_for_training()`, `datasets.push_to_hub()` and the [AutoTrain API](https://api.autotrain.huggingface.co/docs). - """ -) - -hf_auth_token, api = hf_login_flow() - -user_info = api.whoami() -organizations = [user_info["name"]] + [org["name"] for org in user_info["orgs"]] - -projects = get_projects(hf_auth_token) -project_ids = [proj["proj_name"] for proj in projects] - -target_organization = st.selectbox( - "Hugging Face organization", - options=organizations, - help="the organization where the trained model should end up", -) - -datasets_list = [ - f"{ds['owner']}/{ds['name']}" for ds in get_dataset_list(api_url, api_key) -] -dataset_argilla = st.selectbox( - "Argilla dataset name", - options=datasets_list, -) -dataset_argilla_name = dataset_argilla.split("/")[-1] -dataset_argilla_workspace = dataset_argilla.split("/")[0] -get_data_snapshot( - dataset_argilla_name, dataset_argilla_workspace, query="status: Validated" -) - -input_model = st.text_input( - "Input Model [from the hub](https://huggingface.co/models)", - value="olm/olm-roberta-base-latest", - help="the base model to re-train", -) - -potential_models = api.list_models(filter=ModelFilter(model_name=input_model)) -if not len(potential_models) == 1: - if not any([(input_model == model.modelId) for model in list(potential_models)]): - st.warning("Please select a model from the list below:") - st.write(potential_models) - st.stop() - -for dataset in get_dataset_list(api_url, api_key): - if ( - dataset["name"] == dataset_argilla_name - and dataset["owner"] == dataset_argilla_workspace - ): - dataset_type = dataset["task"] - break - -if dataset_type == "TextClassification": - task_options = ["text-classification-multi-class", "text-classification-binary"] -elif dataset_type == "TokenClassification": - task_options = ["token-classification"] -elif dataset_type == "Text2Text": - task_options = ["summarization"] - -task = st.selectbox("Task", task_options) -task_id = task_id_mapping[task] - -if task_id in [1, 2]: - mapping = { - "text": "text", - "label": "target", - } -elif task_id in [4]: - mapping = { - "tokens": "tokens", - "ner_tags": "tags", - } -elif task_id in [8]: - mapping = { - "text": "text", - "target": "target", - } - - -directly_train = False -free_training = st.checkbox("Train for free (max. 3000 samples)", value=True) -st.warning("AutoTrain@HF is currently in beta and only allows public datasets, hence your data will published publically.") -start = st.button("Schedule AutoTrain") - -if start: - with st.spinner(text="Export in progress..."): - rg.set_workspace(dataset_argilla_workspace) - if free_training: - ds = rg.load(dataset_argilla_name, limit=3000) - else: - ds = rg.load(dataset_argilla_name) - ds_ds = ds.prepare_for_training(framework="transformers", train_size=0.8) - - input_dataset = f"{target_organization}/{dataset_argilla_name}" - ds_ds.push_to_hub( - input_dataset, - token=hf_auth_token, - private=False, - ) - autotrain_project_name = ( - f"{dataset_argilla_name}-{api.dataset_info(input_dataset).sha[:7]}" - ) - - schedule_retrain( - hf_auth_token=hf_auth_token, - target_organization=target_organization, - input_dataset=input_dataset, - input_model=input_model, - autotrain_project_prefix=autotrain_project_name, - task_id=task_id, - directly_train=directly_train, - mapping=mapping, - ) - - diff --git a/spaces/arxify/RVC-beta-v2-0618/infer/trans_weights.py b/spaces/arxify/RVC-beta-v2-0618/infer/trans_weights.py deleted file mode 100644 index da0759627d3fee175a2311a5ac50ccb7f8db8ded..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/infer/trans_weights.py +++ /dev/null @@ -1,16 +0,0 @@ -import torch, pdb - -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-suc\G_1000.pth")["model"]#sim_nsf# -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-freeze-vocoder-flow-enc_q\G_1000.pth")["model"]#sim_nsf# -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-freeze-vocoder\G_1000.pth")["model"]#sim_nsf# -# a=torch.load(r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-test\G_1000.pth")["model"]#sim_nsf# -a = torch.load( - r"E:\codes\py39\vits_vc_gpu_train\logs\ft-mi-no_opt-no_dropout\G_1000.pth" -)[ - "model" -] # sim_nsf# -for key in a.keys(): - a[key] = a[key].half() -# torch.save(a,"ft-mi-freeze-vocoder_true_1k.pt")# -# torch.save(a,"ft-mi-sim1k.pt")# -torch.save(a, "ft-mi-no_opt-no_dropout.pt") # diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Debugger/__init__.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Debugger/__init__.py deleted file mode 100644 index fa81adaff68e06d8e915a6afa375f62f7e5a8fad..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Debugger/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# empty file diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/horizon_graph.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/horizon_graph.py deleted file mode 100644 index 8335957897674be96afd0fd817ee2dd88bf00978..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/horizon_graph.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -Horizon Graph -------------- -This example shows how to make a Horizon Graph with 2 layers. (See https://idl.cs.washington.edu/papers/horizon/ for more details on Horizon Graphs.) -""" -# category: area charts -import altair as alt -import pandas as pd - -source = pd.DataFrame([ - {"x": 1, "y": 28}, {"x": 2, "y": 55}, - {"x": 3, "y": 43}, {"x": 4, "y": 91}, - {"x": 5, "y": 81}, {"x": 6, "y": 53}, - {"x": 7, "y": 19}, {"x": 8, "y": 87}, - {"x": 9, "y": 52}, {"x": 10, "y": 48}, - {"x": 11, "y": 24}, {"x": 12, "y": 49}, - {"x": 13, "y": 87}, {"x": 14, "y": 66}, - {"x": 15, "y": 17}, {"x": 16, "y": 27}, - {"x": 17, "y": 68}, {"x": 18, "y": 16}, - {"x": 19, "y": 49}, {"x": 20, "y": 15} -]) - -area1 = alt.Chart(source).mark_area( - clip=True, - interpolate='monotone' -).encode( - alt.X('x', scale=alt.Scale(zero=False, nice=False)), - alt.Y('y', scale=alt.Scale(domain=[0, 50]), title='y'), - opacity=alt.value(0.6) -).properties( - width=500, - height=75 -) - -area2 = area1.encode( - alt.Y('ny:Q', scale=alt.Scale(domain=[0, 50])) -).transform_calculate( - "ny", alt.datum.y - 50 -) - -area1 + area2 diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/utils/deprecation.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/utils/deprecation.py deleted file mode 100644 index 9deca223b1f6952e03d8e82a17baca5dee8a4751..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/utils/deprecation.py +++ /dev/null @@ -1,70 +0,0 @@ -import warnings -import functools - - -class AltairDeprecationWarning(UserWarning): - pass - - -def deprecated(message=None): - """Decorator to deprecate a function or class. - - Parameters - ---------- - message : string (optional) - The deprecation message - """ - - def wrapper(obj): - return _deprecate(obj, message=message) - - return wrapper - - -def _deprecate(obj, name=None, message=None): - """Return a version of a class or function that raises a deprecation warning. - - Parameters - ---------- - obj : class or function - The object to create a deprecated version of. - name : string (optional) - The name of the deprecated object - message : string (optional) - The deprecation message - - Returns - ------- - deprecated_obj : - The deprecated version of obj - - Examples - -------- - >>> class Foo(object): pass - >>> OldFoo = _deprecate(Foo, "OldFoo") - >>> f = OldFoo() # doctest: +SKIP - AltairDeprecationWarning: alt.OldFoo is deprecated. Use alt.Foo instead. - """ - if message is None: - message = "alt.{} is deprecated. Use alt.{} instead." "".format( - name, obj.__name__ - ) - if isinstance(obj, type): - return type( - name, - (obj,), - { - "__doc__": obj.__doc__, - "__init__": _deprecate(obj.__init__, "__init__", message), - }, - ) - elif callable(obj): - - @functools.wraps(obj) - def new_obj(*args, **kwargs): - warnings.warn(message, AltairDeprecationWarning) - return obj(*args, **kwargs) - - return new_obj - else: - raise ValueError("Cannot deprecate object of type {}".format(type(obj))) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/antlr4/__init__.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/antlr4/__init__.py deleted file mode 100644 index 42027289e7af293a297b538f07f43ca4a566ef62..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/antlr4/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -from antlr4.Token import Token -from antlr4.InputStream import InputStream -from antlr4.FileStream import FileStream -from antlr4.StdinStream import StdinStream -from antlr4.BufferedTokenStream import TokenStream -from antlr4.CommonTokenStream import CommonTokenStream -from antlr4.Lexer import Lexer -from antlr4.Parser import Parser -from antlr4.dfa.DFA import DFA -from antlr4.atn.ATN import ATN -from antlr4.atn.ATNDeserializer import ATNDeserializer -from antlr4.atn.LexerATNSimulator import LexerATNSimulator -from antlr4.atn.ParserATNSimulator import ParserATNSimulator -from antlr4.atn.PredictionMode import PredictionMode -from antlr4.PredictionContext import PredictionContextCache -from antlr4.ParserRuleContext import RuleContext, ParserRuleContext -from antlr4.tree.Tree import ParseTreeListener, ParseTreeVisitor, ParseTreeWalker, TerminalNode, ErrorNode, RuleNode -from antlr4.error.Errors import RecognitionException, IllegalStateException, NoViableAltException -from antlr4.error.ErrorStrategy import BailErrorStrategy -from antlr4.error.DiagnosticErrorListener import DiagnosticErrorListener -from antlr4.Utils import str_list diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/click/_compat.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/click/_compat.py deleted file mode 100644 index 766d286bee8e6186341c9e4d5b783fb3390bc16e..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/click/_compat.py +++ /dev/null @@ -1,626 +0,0 @@ -import codecs -import io -import os -import re -import sys -import typing as t -from weakref import WeakKeyDictionary - -CYGWIN = sys.platform.startswith("cygwin") -MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version) -# Determine local App Engine environment, per Google's own suggestion -APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get( - "SERVER_SOFTWARE", "" -) -WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS2 -auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None -_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") - - -def get_filesystem_encoding() -> str: - return sys.getfilesystemencoding() or sys.getdefaultencoding() - - -def _make_text_stream( - stream: t.BinaryIO, - encoding: t.Optional[str], - errors: t.Optional[str], - force_readable: bool = False, - force_writable: bool = False, -) -> t.TextIO: - if encoding is None: - encoding = get_best_encoding(stream) - if errors is None: - errors = "replace" - return _NonClosingTextIOWrapper( - stream, - encoding, - errors, - line_buffering=True, - force_readable=force_readable, - force_writable=force_writable, - ) - - -def is_ascii_encoding(encoding: str) -> bool: - """Checks if a given encoding is ascii.""" - try: - return codecs.lookup(encoding).name == "ascii" - except LookupError: - return False - - -def get_best_encoding(stream: t.IO) -> str: - """Returns the default stream encoding if not found.""" - rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() - if is_ascii_encoding(rv): - return "utf-8" - return rv - - -class _NonClosingTextIOWrapper(io.TextIOWrapper): - def __init__( - self, - stream: t.BinaryIO, - encoding: t.Optional[str], - errors: t.Optional[str], - force_readable: bool = False, - force_writable: bool = False, - **extra: t.Any, - ) -> None: - self._stream = stream = t.cast( - t.BinaryIO, _FixupStream(stream, force_readable, force_writable) - ) - super().__init__(stream, encoding, errors, **extra) - - def __del__(self) -> None: - try: - self.detach() - except Exception: - pass - - def isatty(self) -> bool: - # https://bitbucket.org/pypy/pypy/issue/1803 - return self._stream.isatty() - - -class _FixupStream: - """The new io interface needs more from streams than streams - traditionally implement. As such, this fix-up code is necessary in - some circumstances. - - The forcing of readable and writable flags are there because some tools - put badly patched objects on sys (one such offender are certain version - of jupyter notebook). - """ - - def __init__( - self, - stream: t.BinaryIO, - force_readable: bool = False, - force_writable: bool = False, - ): - self._stream = stream - self._force_readable = force_readable - self._force_writable = force_writable - - def __getattr__(self, name: str) -> t.Any: - return getattr(self._stream, name) - - def read1(self, size: int) -> bytes: - f = getattr(self._stream, "read1", None) - - if f is not None: - return t.cast(bytes, f(size)) - - return self._stream.read(size) - - def readable(self) -> bool: - if self._force_readable: - return True - x = getattr(self._stream, "readable", None) - if x is not None: - return t.cast(bool, x()) - try: - self._stream.read(0) - except Exception: - return False - return True - - def writable(self) -> bool: - if self._force_writable: - return True - x = getattr(self._stream, "writable", None) - if x is not None: - return t.cast(bool, x()) - try: - self._stream.write("") # type: ignore - except Exception: - try: - self._stream.write(b"") - except Exception: - return False - return True - - def seekable(self) -> bool: - x = getattr(self._stream, "seekable", None) - if x is not None: - return t.cast(bool, x()) - try: - self._stream.seek(self._stream.tell()) - except Exception: - return False - return True - - -def _is_binary_reader(stream: t.IO, default: bool = False) -> bool: - try: - return isinstance(stream.read(0), bytes) - except Exception: - return default - # This happens in some cases where the stream was already - # closed. In this case, we assume the default. - - -def _is_binary_writer(stream: t.IO, default: bool = False) -> bool: - try: - stream.write(b"") - except Exception: - try: - stream.write("") - return False - except Exception: - pass - return default - return True - - -def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]: - # We need to figure out if the given stream is already binary. - # This can happen because the official docs recommend detaching - # the streams to get binary streams. Some code might do this, so - # we need to deal with this case explicitly. - if _is_binary_reader(stream, False): - return t.cast(t.BinaryIO, stream) - - buf = getattr(stream, "buffer", None) - - # Same situation here; this time we assume that the buffer is - # actually binary in case it's closed. - if buf is not None and _is_binary_reader(buf, True): - return t.cast(t.BinaryIO, buf) - - return None - - -def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]: - # We need to figure out if the given stream is already binary. - # This can happen because the official docs recommend detaching - # the streams to get binary streams. Some code might do this, so - # we need to deal with this case explicitly. - if _is_binary_writer(stream, False): - return t.cast(t.BinaryIO, stream) - - buf = getattr(stream, "buffer", None) - - # Same situation here; this time we assume that the buffer is - # actually binary in case it's closed. - if buf is not None and _is_binary_writer(buf, True): - return t.cast(t.BinaryIO, buf) - - return None - - -def _stream_is_misconfigured(stream: t.TextIO) -> bool: - """A stream is misconfigured if its encoding is ASCII.""" - # If the stream does not have an encoding set, we assume it's set - # to ASCII. This appears to happen in certain unittest - # environments. It's not quite clear what the correct behavior is - # but this at least will force Click to recover somehow. - return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii") - - -def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool: - """A stream attribute is compatible if it is equal to the - desired value or the desired value is unset and the attribute - has a value. - """ - stream_value = getattr(stream, attr, None) - return stream_value == value or (value is None and stream_value is not None) - - -def _is_compatible_text_stream( - stream: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str] -) -> bool: - """Check if a stream's encoding and errors attributes are - compatible with the desired values. - """ - return _is_compat_stream_attr( - stream, "encoding", encoding - ) and _is_compat_stream_attr(stream, "errors", errors) - - -def _force_correct_text_stream( - text_stream: t.IO, - encoding: t.Optional[str], - errors: t.Optional[str], - is_binary: t.Callable[[t.IO, bool], bool], - find_binary: t.Callable[[t.IO], t.Optional[t.BinaryIO]], - force_readable: bool = False, - force_writable: bool = False, -) -> t.TextIO: - if is_binary(text_stream, False): - binary_reader = t.cast(t.BinaryIO, text_stream) - else: - text_stream = t.cast(t.TextIO, text_stream) - # If the stream looks compatible, and won't default to a - # misconfigured ascii encoding, return it as-is. - if _is_compatible_text_stream(text_stream, encoding, errors) and not ( - encoding is None and _stream_is_misconfigured(text_stream) - ): - return text_stream - - # Otherwise, get the underlying binary reader. - possible_binary_reader = find_binary(text_stream) - - # If that's not possible, silently use the original reader - # and get mojibake instead of exceptions. - if possible_binary_reader is None: - return text_stream - - binary_reader = possible_binary_reader - - # Default errors to replace instead of strict in order to get - # something that works. - if errors is None: - errors = "replace" - - # Wrap the binary stream in a text stream with the correct - # encoding parameters. - return _make_text_stream( - binary_reader, - encoding, - errors, - force_readable=force_readable, - force_writable=force_writable, - ) - - -def _force_correct_text_reader( - text_reader: t.IO, - encoding: t.Optional[str], - errors: t.Optional[str], - force_readable: bool = False, -) -> t.TextIO: - return _force_correct_text_stream( - text_reader, - encoding, - errors, - _is_binary_reader, - _find_binary_reader, - force_readable=force_readable, - ) - - -def _force_correct_text_writer( - text_writer: t.IO, - encoding: t.Optional[str], - errors: t.Optional[str], - force_writable: bool = False, -) -> t.TextIO: - return _force_correct_text_stream( - text_writer, - encoding, - errors, - _is_binary_writer, - _find_binary_writer, - force_writable=force_writable, - ) - - -def get_binary_stdin() -> t.BinaryIO: - reader = _find_binary_reader(sys.stdin) - if reader is None: - raise RuntimeError("Was not able to determine binary stream for sys.stdin.") - return reader - - -def get_binary_stdout() -> t.BinaryIO: - writer = _find_binary_writer(sys.stdout) - if writer is None: - raise RuntimeError("Was not able to determine binary stream for sys.stdout.") - return writer - - -def get_binary_stderr() -> t.BinaryIO: - writer = _find_binary_writer(sys.stderr) - if writer is None: - raise RuntimeError("Was not able to determine binary stream for sys.stderr.") - return writer - - -def get_text_stdin( - encoding: t.Optional[str] = None, errors: t.Optional[str] = None -) -> t.TextIO: - rv = _get_windows_console_stream(sys.stdin, encoding, errors) - if rv is not None: - return rv - return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True) - - -def get_text_stdout( - encoding: t.Optional[str] = None, errors: t.Optional[str] = None -) -> t.TextIO: - rv = _get_windows_console_stream(sys.stdout, encoding, errors) - if rv is not None: - return rv - return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True) - - -def get_text_stderr( - encoding: t.Optional[str] = None, errors: t.Optional[str] = None -) -> t.TextIO: - rv = _get_windows_console_stream(sys.stderr, encoding, errors) - if rv is not None: - return rv - return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) - - -def _wrap_io_open( - file: t.Union[str, os.PathLike, int], - mode: str, - encoding: t.Optional[str], - errors: t.Optional[str], -) -> t.IO: - """Handles not passing ``encoding`` and ``errors`` in binary mode.""" - if "b" in mode: - return open(file, mode) - - return open(file, mode, encoding=encoding, errors=errors) - - -def open_stream( - filename: str, - mode: str = "r", - encoding: t.Optional[str] = None, - errors: t.Optional[str] = "strict", - atomic: bool = False, -) -> t.Tuple[t.IO, bool]: - binary = "b" in mode - - # Standard streams first. These are simple because they ignore the - # atomic flag. Use fsdecode to handle Path("-"). - if os.fsdecode(filename) == "-": - if any(m in mode for m in ["w", "a", "x"]): - if binary: - return get_binary_stdout(), False - return get_text_stdout(encoding=encoding, errors=errors), False - if binary: - return get_binary_stdin(), False - return get_text_stdin(encoding=encoding, errors=errors), False - - # Non-atomic writes directly go out through the regular open functions. - if not atomic: - return _wrap_io_open(filename, mode, encoding, errors), True - - # Some usability stuff for atomic writes - if "a" in mode: - raise ValueError( - "Appending to an existing file is not supported, because that" - " would involve an expensive `copy`-operation to a temporary" - " file. Open the file in normal `w`-mode and copy explicitly" - " if that's what you're after." - ) - if "x" in mode: - raise ValueError("Use the `overwrite`-parameter instead.") - if "w" not in mode: - raise ValueError("Atomic writes only make sense with `w`-mode.") - - # Atomic writes are more complicated. They work by opening a file - # as a proxy in the same folder and then using the fdopen - # functionality to wrap it in a Python file. Then we wrap it in an - # atomic file that moves the file over on close. - import errno - import random - - try: - perm: t.Optional[int] = os.stat(filename).st_mode - except OSError: - perm = None - - flags = os.O_RDWR | os.O_CREAT | os.O_EXCL - - if binary: - flags |= getattr(os, "O_BINARY", 0) - - while True: - tmp_filename = os.path.join( - os.path.dirname(filename), - f".__atomic-write{random.randrange(1 << 32):08x}", - ) - try: - fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) - break - except OSError as e: - if e.errno == errno.EEXIST or ( - os.name == "nt" - and e.errno == errno.EACCES - and os.path.isdir(e.filename) - and os.access(e.filename, os.W_OK) - ): - continue - raise - - if perm is not None: - os.chmod(tmp_filename, perm) # in case perm includes bits in umask - - f = _wrap_io_open(fd, mode, encoding, errors) - af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) - return t.cast(t.IO, af), True - - -class _AtomicFile: - def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None: - self._f = f - self._tmp_filename = tmp_filename - self._real_filename = real_filename - self.closed = False - - @property - def name(self) -> str: - return self._real_filename - - def close(self, delete: bool = False) -> None: - if self.closed: - return - self._f.close() - os.replace(self._tmp_filename, self._real_filename) - self.closed = True - - def __getattr__(self, name: str) -> t.Any: - return getattr(self._f, name) - - def __enter__(self) -> "_AtomicFile": - return self - - def __exit__(self, exc_type, exc_value, tb): # type: ignore - self.close(delete=exc_type is not None) - - def __repr__(self) -> str: - return repr(self._f) - - -def strip_ansi(value: str) -> str: - return _ansi_re.sub("", value) - - -def _is_jupyter_kernel_output(stream: t.IO) -> bool: - while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): - stream = stream._stream - - return stream.__class__.__module__.startswith("ipykernel.") - - -def should_strip_ansi( - stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None -) -> bool: - if color is None: - if stream is None: - stream = sys.stdin - return not isatty(stream) and not _is_jupyter_kernel_output(stream) - return not color - - -# On Windows, wrap the output streams with colorama to support ANSI -# color codes. -# NOTE: double check is needed so mypy does not analyze this on Linux -if sys.platform.startswith("win") and WIN: - from ._winconsole import _get_windows_console_stream - - def _get_argv_encoding() -> str: - import locale - - return locale.getpreferredencoding() - - _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() - - def auto_wrap_for_ansi( - stream: t.TextIO, color: t.Optional[bool] = None - ) -> t.TextIO: - """Support ANSI color and style codes on Windows by wrapping a - stream with colorama. - """ - try: - cached = _ansi_stream_wrappers.get(stream) - except Exception: - cached = None - - if cached is not None: - return cached - - import colorama - - strip = should_strip_ansi(stream, color) - ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) - rv = t.cast(t.TextIO, ansi_wrapper.stream) - _write = rv.write - - def _safe_write(s): - try: - return _write(s) - except BaseException: - ansi_wrapper.reset_all() - raise - - rv.write = _safe_write - - try: - _ansi_stream_wrappers[stream] = rv - except Exception: - pass - - return rv - -else: - - def _get_argv_encoding() -> str: - return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding() - - def _get_windows_console_stream( - f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str] - ) -> t.Optional[t.TextIO]: - return None - - -def term_len(x: str) -> int: - return len(strip_ansi(x)) - - -def isatty(stream: t.IO) -> bool: - try: - return stream.isatty() - except Exception: - return False - - -def _make_cached_stream_func( - src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO] -) -> t.Callable[[], t.TextIO]: - cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() - - def func() -> t.TextIO: - stream = src_func() - try: - rv = cache.get(stream) - except Exception: - rv = None - if rv is not None: - return rv - rv = wrapper_func() - try: - cache[stream] = rv - except Exception: - pass - return rv - - return func - - -_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin) -_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout) -_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr) - - -binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = { - "stdin": get_binary_stdin, - "stdout": get_binary_stdout, - "stderr": get_binary_stderr, -} - -text_streams: t.Mapping[ - str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO] -] = { - "stdin": get_text_stdin, - "stdout": get_text_stdout, - "stderr": get_text_stderr, -} diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/examples/MMPT/mmpt/datasets/__init__.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/examples/MMPT/mmpt/datasets/__init__.py deleted file mode 100644 index 2578235e1771fdc7e6fcfb66a519cbe891d7e254..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/examples/MMPT/mmpt/datasets/__init__.py +++ /dev/null @@ -1,10 +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 .mmdataset import * - -try: - from .fairseqmmdataset import * -except ImportError: - pass diff --git a/spaces/aseifert/ExplaiNER/src/model.py b/spaces/aseifert/ExplaiNER/src/model.py deleted file mode 100644 index 06e149f3156b0b0e9ec2d848afd4fc561630d6e8..0000000000000000000000000000000000000000 --- a/spaces/aseifert/ExplaiNER/src/model.py +++ /dev/null @@ -1,33 +0,0 @@ -import streamlit as st -from sentence_transformers import SentenceTransformer -from transformers import AutoModelForTokenClassification # type: ignore -from transformers import AutoTokenizer # type: ignore - - -@st.experimental_singleton() -def get_model(model_name: str, labels=None): - if labels is None: - return AutoModelForTokenClassification.from_pretrained( - model_name, - output_attentions=True, - ) # type: ignore - else: - id2label = {idx: tag for idx, tag in enumerate(labels)} - label2id = {tag: idx for idx, tag in enumerate(labels)} - return AutoModelForTokenClassification.from_pretrained( - model_name, - output_attentions=True, - num_labels=len(labels), - id2label=id2label, - label2id=label2id, - ) # type: ignore - - -@st.experimental_singleton() -def get_encoder(model_name: str, device: str = "cpu"): - return SentenceTransformer(model_name, device=device) - - -@st.experimental_singleton() -def get_tokenizer(tokenizer_name: str): - return AutoTokenizer.from_pretrained(tokenizer_name) diff --git a/spaces/awaawawawa/iurf7irfuyytruyyugb/webui.py b/spaces/awaawawawa/iurf7irfuyytruyyugb/webui.py deleted file mode 100644 index d4941511f94ca0c493ebd1f2d257e0f332ee2aa5..0000000000000000000000000000000000000000 --- a/spaces/awaawawawa/iurf7irfuyytruyyugb/webui.py +++ /dev/null @@ -1,137 +0,0 @@ -import os -import threading -import time -import importlib -import signal -import threading - -from fastapi.middleware.gzip import GZipMiddleware - -from modules.paths import script_path - -from modules import devices, sd_samplers -import modules.codeformer_model as codeformer -import modules.extras -import modules.face_restoration -import modules.gfpgan_model as gfpgan -import modules.img2img - -import modules.lowvram -import modules.paths -import modules.scripts -import modules.sd_hijack -import modules.sd_models -import modules.shared as shared -import modules.txt2img - -import modules.ui -from modules import devices -from modules import modelloader -from modules.paths import script_path -from modules.shared import cmd_opts -import modules.hypernetworks.hypernetwork - - -queue_lock = threading.Lock() - - -def wrap_queued_call(func): - def f(*args, **kwargs): - with queue_lock: - res = func(*args, **kwargs) - - return res - - return f - - -def wrap_gradio_gpu_call(func, extra_outputs=None): - def f(*args, **kwargs): - devices.torch_gc() - - shared.state.sampling_step = 0 - shared.state.job_count = -1 - shared.state.job_no = 0 - shared.state.job_timestamp = shared.state.get_job_timestamp() - shared.state.current_latent = None - shared.state.current_image = None - shared.state.current_image_sampling_step = 0 - shared.state.skipped = False - shared.state.interrupted = False - shared.state.textinfo = None - - with queue_lock: - res = func(*args, **kwargs) - - shared.state.job = "" - shared.state.job_count = 0 - - devices.torch_gc() - - return res - - return modules.ui.wrap_gradio_call(f, extra_outputs=extra_outputs) - -def initialize(): - modelloader.cleanup_models() - modules.sd_models.setup_model() - codeformer.setup_model(cmd_opts.codeformer_models_path) - gfpgan.setup_model(cmd_opts.gfpgan_models_path) - shared.face_restorers.append(modules.face_restoration.FaceRestoration()) - modelloader.load_upscalers() - - modules.scripts.load_scripts(os.path.join(script_path, "scripts")) - - shared.sd_model = modules.sd_models.load_model() - shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights(shared.sd_model))) - shared.opts.onchange("sd_hypernetwork", wrap_queued_call(lambda: modules.hypernetworks.hypernetwork.load_hypernetwork(shared.opts.sd_hypernetwork))) - shared.opts.onchange("sd_hypernetwork_strength", modules.hypernetworks.hypernetwork.apply_strength) - - -def webui(): - initialize() - - # make the program just exit at ctrl+c without waiting for anything - def sigint_handler(sig, frame): - print(f'Interrupted with signal {sig} in {frame}') - os._exit(0) - - signal.signal(signal.SIGINT, sigint_handler) - - while 1: - - demo = modules.ui.create_ui(wrap_gradio_gpu_call=wrap_gradio_gpu_call) - - app, local_url, share_url = demo.launch( - share=cmd_opts.share, - server_name="0.0.0.0" if cmd_opts.listen else None, - server_port=cmd_opts.port, - debug=cmd_opts.gradio_debug, - auth=[tuple(cred.split(':')) for cred in cmd_opts.gradio_auth.strip('"').split(',')] if cmd_opts.gradio_auth else None, - inbrowser=cmd_opts.autolaunch, - prevent_thread_lock=True - ) - - app.add_middleware(GZipMiddleware, minimum_size=1000) - - while 1: - time.sleep(0.5) - if getattr(demo, 'do_restart', False): - time.sleep(0.5) - demo.close() - time.sleep(0.5) - break - - sd_samplers.set_samplers() - - print('Reloading Custom Scripts') - modules.scripts.reload_scripts(os.path.join(script_path, "scripts")) - print('Reloading modules: modules.ui') - importlib.reload(modules.ui) - print('Refreshing Model List') - modules.sd_models.list_models() - print('Restarting Gradio') - - -if __name__ == "__main__": - webui() diff --git a/spaces/awacke1/File-Memory-Human-Feedback-Streamlit/README.md b/spaces/awacke1/File-Memory-Human-Feedback-Streamlit/README.md deleted file mode 100644 index 4175ad3ebbe6ad61a5efe1dca41a43882bd759ec..0000000000000000000000000000000000000000 --- a/spaces/awacke1/File-Memory-Human-Feedback-Streamlit/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: File Memory Human Feedback Streamlit -emoji: 🏢 -colorFrom: gray -colorTo: yellow -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/awacke1/GradioTranslation/README.md b/spaces/awacke1/GradioTranslation/README.md deleted file mode 100644 index a473e0cd65a7bda2c2a21ec01d67debd697053ee..0000000000000000000000000000000000000000 --- a/spaces/awacke1/GradioTranslation/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: GradioTranslation -emoji: 🦀 -colorFrom: pink -colorTo: green -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/awacke1/Markdown-Analyzer/app.py b/spaces/awacke1/Markdown-Analyzer/app.py deleted file mode 100644 index 062bc44301804dc22b514e8982633bea73bbc490..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Markdown-Analyzer/app.py +++ /dev/null @@ -1,63 +0,0 @@ -import streamlit as st -import requests -from transformers import pipeline -import plotly.express as px -import pandas as pd -from collections import Counter -import re - -def get_markdown_from_github(url): - response = requests.get(url) - markdown = response.text - return markdown - -def preprocess_text(text): - text = text.lower() - text = re.sub('[^A-Za-z0-9]+', ' ', text) - return text - -def get_most_frequent_words(text, n): - words = re.findall(r'\b\w{5,}\b', text) - word_count = Counter(words) - most_common_words = word_count.most_common(n) - return most_common_words - -def get_sentences_with_common_words(text, common_words): - sentences = re.split('[.?!]', text) - selected_sentences = [] - for sentence in sentences: - for word in common_words: - if word in sentence: - selected_sentences.append(sentence.strip()) - break - return selected_sentences - -def render_heatmap(words, sentences): - df = pd.DataFrame(words, columns=['word', 'frequency']) - fig = px.treemap(df, path=['word'], values='frequency', color='frequency', hover_data=['frequency'], color_continuous_scale='reds') - st.plotly_chart(fig, use_container_width=True) - -def main(): - st.title('Markdown Analyzer') - - # Get markdown from GitHub - default_markdown_url = 'https://github.com/AaronCWacker/Yggdrasil/blob/main/README.md' - markdown_url = st.sidebar.text_input("Enter a URL to analyze (default is provided):", default_markdown_url) - markdown = get_markdown_from_github(markdown_url) - - # Preprocess text - text = preprocess_text(markdown) - - # Get most frequent words - n_most_frequent_words = st.sidebar.slider('Number of most frequent words to display', 1, 20, 10) - most_frequent_words = get_most_frequent_words(text, n_most_frequent_words) - - # Get sentences containing common words - common_words = [word for word, _ in most_frequent_words] - sentences = get_sentences_with_common_words(text, common_words) - - # Render heatmap - render_heatmap(most_frequent_words, sentences) - -if __name__ == '__main__': - main() diff --git a/spaces/awacke1/PerceiverEmotionClassifier/README.md b/spaces/awacke1/PerceiverEmotionClassifier/README.md deleted file mode 100644 index ead763e0c800789e57732ede98e44e8f1c4b277e..0000000000000000000000000000000000000000 --- a/spaces/awacke1/PerceiverEmotionClassifier/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: PerceiverEmotionClassifier -emoji: 🚀 -colorFrom: blue -colorTo: gray -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/awaiss/vits-models/text/symbols.py b/spaces/awaiss/vits-models/text/symbols.py deleted file mode 100644 index edfbd24247be8c757275ce80b9ec27a0ffa808f3..0000000000000000000000000000000000000000 --- a/spaces/awaiss/vits-models/text/symbols.py +++ /dev/null @@ -1,39 +0,0 @@ -''' -Defines the set of symbols used in text input to the model. -''' - -'''# japanese_cleaners -_pad = '_' -_punctuation = ',.!?-' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧ↓↑ ' -''' - -'''# japanese_cleaners2 -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧʦ↓↑ ' -''' - -'''# korean_cleaners -_pad = '_' -_punctuation = ',.!?…~' -_letters = 'ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㄲㄸㅃㅆㅉㅏㅓㅗㅜㅡㅣㅐㅔ ' -''' - -'''# chinese_cleaners -_pad = '_' -_punctuation = ',。!?—…' -_letters = 'ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩˉˊˇˋ˙ ' -''' - -# zh_ja_mixture_cleaners -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijklmnoprstuvwyzʃʧʦɯɹəɥ⁼ʰ`→↓↑ ' - - -# Export all symbols: -symbols = [_pad] + list(_punctuation) + list(_letters) - -# Special symbol ids -SPACE_ID = symbols.index(" ") \ No newline at end of file diff --git a/spaces/ayushnoori/program-synthesis/synthesis.py b/spaces/ayushnoori/program-synthesis/synthesis.py deleted file mode 100644 index f094ac5d147a1acc1ef4809231359403e4c2a1ac..0000000000000000000000000000000000000000 --- a/spaces/ayushnoori/program-synthesis/synthesis.py +++ /dev/null @@ -1,216 +0,0 @@ -''' -BOTTOM UP ENUMERATIVE SYNTHESIS -Ayush Noori -CS252R, Fall 2020 - -Example of usage: -python synthesis.py --domain arithmetic --examples addition -''' - -# load libraries -import numpy as np -import argparse -import itertools -import time - -# import examples -from arithmetic import * -from strings import * -from abstract_syntax_tree import * -from examples import example_set, check_examples -import config - - -# PARSE ARGUMENTS -def parse_args(): - ''' - Parse command line arguments. - ''' - - parser = argparse.ArgumentParser(description="Bottom-up enumerative synthesis in Python.") - - # define valid choices for the 'domain' argument - valid_domain_choices = ["arithmetic", "strings"] - - # add examples - parser.add_argument('--domain', type=str, required=True, # default="arithmetic", - choices=valid_domain_choices, - help='Domain of synthesis (either "arithmetic" or "string").') - - parser.add_argument('--examples', dest='examples_key', type=str, required=True, # default="addition", - choices=example_set.keys(), - help='Examples to synthesize program from. Must be a valid key in the "example_set" dictionary.') - - parser.add_argument('--max-weight', type=int, required=False, default=3, - help='Maximum weight of programs to consider before terminating search.') - - args = parser.parse_args() - return args - - -# EXTRACT CONSTANTS AND VARIABLES -def extract_constants(examples): - ''' - Extracts the constants from the input-output examples. Also constructs variables as needed - based on the input-output examples, and adds them to the list of constants. - ''' - - # check validity of provided examples - # if valid, extract arity and argument types - arity, arg_types = check_examples(examples) - - # initialize list of constants - constants = [] - - # get unique set of inputs - inputs = [input for example in examples for input in example[0]] - inputs = set(inputs) - - # add 1 to the set of inputs - inputs.add(1) - - # extract constants in input - for input in inputs: - - if type(input) == int: - constants.append(IntegerConstant(input)) - elif type(input) == str: - constants.append(StringConstant(input)) - pass - else: - raise Exception("Input of unknown type.") - - # initialize list of variables - variables = [] - - # extract variables in input - for position, arg in enumerate(arg_types): - if arg == int: - variables.append(IntegerVariable(position)) - elif arg == str: - variables.append(StringVariable(position)) - else: - raise Exception("Input of unknown type.") - - return constants + variables - - -# CHECK OBSERVATIONAL EQUIVALENCE -def observationally_equivalent(program_a, program_b, examples): - """ - Returns True if Program A and Program B are observationally equivalent, False otherwise. - """ - - inputs = [example[0] for example in examples] - a_output = [program_a.evaluate(input) for input in inputs] - b_output = [program_b.evaluate(input) for input in inputs] - - return a_output == b_output - - -# CHECK CORRECTNESS -def check_program(program, examples): - ''' - Check whether the program satisfies the input-output examples. - ''' - - inputs = [example[0] for example in examples] - outputs = [example[1] for example in examples] - program_output = [program.evaluate(input) for input in inputs] - - return program_output == outputs - - -# RUN SYNTHESIZER -def run_synthesizer(args): - ''' - Run bottom-up enumerative synthesis. - ''' - - # retrieve selected input-output examples - examples = example_set[args.examples_key] - - # extract constants from examples - program_bank = extract_constants(examples) - program_bank_str = [p.str() for p in program_bank] - print("\nSynthesis Log:") - print(f"- Extracted {len(program_bank)} constants from examples.") - - # define operators - if args.domain == "arithmetic": - operators = arithmetic_operators - elif args.domain == "strings": - operators = string_operators - else: - raise Exception('Domain not recognized. Must be either "arithmetic" or "string".') - - # iterate over each level - for weight in range(2, args.max_weight): - - # print message - print(f"- Searching level {weight} with {len(program_bank)} primitives.") - - # iterate over each operator - for op in operators: - - # get all possible combinations of primitives in program bank - combinations = itertools.combinations(program_bank, op.arity) - - # iterate over each combination - for combination in combinations: - - # get type signature - type_signature = [p.type for p in combination] - - # check if type signature matches operator - if type_signature != op.arg_types: - continue - - # check that sum of weights of arguments <= w - if sum([p.weight for p in combination]) > weight: - continue - - # create new program - program = OperatorNode(op, combination) - - # check if program is in program bank using string representation - if program.str() in program_bank_str: - continue - - # check if program is observationally equivalent to any program in program bank - if any([observationally_equivalent(program, p, examples) for p in program_bank]): - continue - - # add program to program bank - program_bank.append(program) - program_bank_str.append(program.str()) - - # check if program passes all examples - if check_program(program, examples): - return(program) - - # return None if no program is found - return None - - -if __name__ == '__main__': - - # parse command line arguments - args = parse_args() - # print(args) - - # run bottom-up enumerative synthesis - start_time = time.time() - program = run_synthesizer(args) - end_time = time.time() - elapsed_time = round(end_time - start_time, 4) - - # check if program was found - print("\nSynthesis Results:") - if program is None: - print(f"- Max weight of {args.max_weight} reached, no program found in {elapsed_time}s.") - else: - print(f"- Program found in {elapsed_time}s.") - print(f"- Program: {program.str()}") - print(f"- Program weight: {program.weight}") - print(f"- Program return type: {program.type.__name__}") diff --git a/spaces/bsenst/keras-image-classifier/app.py b/spaces/bsenst/keras-image-classifier/app.py deleted file mode 100644 index 1f478d4b3c6f51c4891db70354f2a5ae6c19db0d..0000000000000000000000000000000000000000 --- a/spaces/bsenst/keras-image-classifier/app.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -import keras -import numpy as np -import gradio as gr -from tensorflow.keras.applications.xception import preprocess_input - -model = keras.models.load_model("xception_v4_1_07_0.699.h5") - -classes = [ - "akiec", - "bcc", - "bkl", - "df", - "mel", - "nv", - "vasc", -] - -def image_classifier(inp): - x = np.array(inp) - X = np.array([x]) - X = preprocess_input(X) - pred = model.predict(X).flatten() - result = {classes[i]: float(pred[i]) for i in range(7)} - return result - -app = gr.Interface( - fn=image_classifier, - inputs=gr.inputs.Image(shape=(150,150)), - outputs="label", - examples=["img/"+img for img in os.listdir("img")], - title="Experimental Skin Lesion Identifier", - description="Disclaimer: This work is part of an educational project. It is not intended for clinical application. As such it can not make real world predictions for skin lesions. To get recommendations regarding skin lesions one should ask for expert advice such as provided by a dermatologist.

The code repository: https://github.com/bsenst/capstone1-skin-lesion-classifier

The dataset is available under CC BY-NC-SA 4.0 License and can be found here: https://www.kaggle.com/datasets/kmader/skin-cancer-mnist-ham10000

The neural network model labels images using the following classes: Actinic keratoses and intraepithelial carcinoma / Bowen's disease (akiec), basal cell carcinoma (bcc), benign keratosis-like lesions (solar lentigines / seborrheic keratoses and lichen-planus like keratoses, bkl), dermatofibroma (df), melanoma (mel), melanocytic nevi (nv) and vascular lesions (angiomas, angiokeratomas, pyogenic granulomas and hemorrhage, vasc)", - ) -app.launch() \ No newline at end of file diff --git a/spaces/camenduru-com/audioldm-text-to-audio-generation/audioldm/clap/open_clip/version.py b/spaces/camenduru-com/audioldm-text-to-audio-generation/audioldm/clap/open_clip/version.py deleted file mode 100644 index 3ced3581bb601ae91b1e1da4b8f4f520855a065e..0000000000000000000000000000000000000000 --- a/spaces/camenduru-com/audioldm-text-to-audio-generation/audioldm/clap/open_clip/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.2.1" diff --git a/spaces/camenduru-com/chisel/Dockerfile b/spaces/camenduru-com/chisel/Dockerfile deleted file mode 100644 index 6b4cfcf65ff3d68ef3526a733b8d55fba82c3d4d..0000000000000000000000000000000000000000 --- a/spaces/camenduru-com/chisel/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM heroku/heroku:22 -RUN curl -sSL https://github.com/jpillora/chisel/releases/download/v1.7.7/chisel_1.7.7_linux_amd64.gz | zcat > /usr/bin/chisel -RUN chmod +x /usr/bin/chisel -EXPOSE 7860 -CMD chisel server --socks5 --reverse --auth potato:potato --port 7860 \ No newline at end of file diff --git a/spaces/chansung/zero2story/constants/init_values.py b/spaces/chansung/zero2story/constants/init_values.py deleted file mode 100644 index ad2723c06560410585419d5e7cb58065cf38638d..0000000000000000000000000000000000000000 --- a/spaces/chansung/zero2story/constants/init_values.py +++ /dev/null @@ -1,48 +0,0 @@ -genres = ["Middle Ages", "Cyberpunk", "Science Fiction", "Horror", "Romance", "Mystery", "Thriller", "Survival", "Post-apocalyptic", "Historical Fiction"] - -places = { - "Middle Ages": ["Royal Palace", "Small Village", "Enchanted Forest", "Church", "City Walls and Beyond", "Wizard's Tower", "Inn", "Battlefield", "Grand Library", "Royal Gardens"], - "Cyberpunk": ["Neon-lit City Streets", "Underground Bar", "Rave Club", "Tech Market", "Hacker Lounge", "Metropolis Central", "Virtual Reality Hub", "Flying Car Docking Station", "Illegal Cybernetic Clinic", "Information Trade Point"], - "Science Fiction": ["Space Station", "Futuristic City", "Alien Planet", "Hidden Moon Base", "Cybernetic Hub", "Galactic Headquarters", "Robotics Factory", "Intergalactic Trading Post", "Alien Cultural Center", "Virtual Reality Realm"], - "Horror": ["Abandoned House", "Cemetery", "Mental Hospital", "Cathedral", "Forest", "Museum", "Basement", "Abandoned Theme Park", "Abandoned School", "Dark Alley"], - "Romance": ["Beach", "Library", "Starlit Bridge", "Lake", "Flower Shop", "Candlelit Restaurant", "Garden", "Cobblestone Alley", "Windy Road", "Ocean View Deck"], - "Mystery": ["Haunted House", "Ancient Castle", "Secret Lab", "Dark City Alleyways", "Underground Laboratory", "Historic Art Museum", "Antique Library", "Mythical Ruins", "Modern City Skyscraper", "Deserted Island"], - "Thriller": ["Labyrinth", "Abandoned Hospital", "Downtown Alleyway", "Locked Room", "Basement", "Cabin in the Woods", "Abandoned Amusement Park", "Police Station", "Underground Warehouse", "Secret Research Lab"], - "Survival": ["Desert", "Forest", "Glacier", "Urban Ruins", "Underwater", "Island", "Mountain Range", "Stormy Ocean", "Wasteland", "Jungle"], - "Post-apocalyptic": ["Abandoned City", "Underground Bunker", "Desert Wastelands", "Radioactive Zones", "Ruined Metropolis", "Overgrown Countryside", "Fortified Community", "Lost Library", "Strategic Bridge", "Ghost Town"], - "Historical Fiction": ["Castle", "Ancient City", "Countryside", "Temple", "Town Square", "Expedition Base", "Fortress", "Royal Court", "Medieval Market", "Training Ground"] -} - -moods = { - "Middle Ages": ["Epic Adventure", "Deep Romance", "Intense Tension", "Mystical and Magical", "Honor and Principle", "Pain and Despair", "Danger and Peril", "Grand Feast and Court Life", "Hope in Darkness", "Traditional National and Cultural"], - "Cyberpunk": ["Neon Nights", "Rain-soaked Ambiance", "Electric Energy", "Holographic Illusions", "Cyber Rhythm", "Dark Alley Mysteries", "High-speed Chase", "Augmented Reality Fashion", "Tech-induced Uncertainty", "Tranquility amidst Chaos"], - "Science Fiction": ["Technological Advancement", "First Contact", "Galactic Warfare", "Deep Space Exploration", "Intergalactic Romance", "Survival in Space", "Political Intrigue", "Covert Operations", "Interstellar Festival", "Technological Dystopia"], - "Horror": ["Ominous", "Mysterious", "Brutal", "Supernatural", "Intense", "Unexpected", "Silent Horror", "Confusing", "Insanity", "Atmospheric Horror"], - "Romance": ["Poetic", "Dreamy", "Heartfelt", "Cheerful", "Melancholic", "Innocent", "Exhilarating", "Sweet", "Cozy", "Sunlit"], - "Mystery": ["Dark and Gritty", "Silent Suspense", "Time-sensitive Thrill", "Unpredictable Twist", "Momentary Peace", "Unknown Anxiety", "Suspicion and Uncertainty", "Unsettling Atmosphere", "Shocking Revelation", "Loneliness and Isolation"], - "Thriller": ["Uneasiness", "Suspicion", "Tension", "Anxiety", "Chase", "Mystery", "Darkness", "Escape", "Secrecy", "Danger"], - "Survival": ["Desperate", "Tense", "Adventurous", "Dangerous", "Frightening", "Desolate", "Primitive", "Stealthy", "Stagnant", "Clinical"], - "Post-apocalyptic": ["Struggle for Survival", "Beacon of Hope", "Mistrust and Suspicion", "Constant Danger", "Sole Survivor", "Gradual Recovery", "Rebellion Against Oppression", "Pockets of Serenity", "Nature's Emptiness", "Desperate Solidarity"], - "Historical Fiction": ["Anticipation", "Awe", "Tranquility", "Tension", "Festive", "Mysterious", "Unexpected", "Focused", "Dichotomy"] -} - -jobs = { - "Middle Ages": ["Knight", "Archer", "Wizard/Mage", "Ruler", "Cleric/Priest", "Merchant", "Blacksmith", "Bard", "Barbarian", "Alchemist"], - "Cyberpunk": ["Hacker", "Bounty Hunter", "Corporate Executive", "Rebel", "Data Courier", "Cyborg", "Street Mercenary", "Investigative Journalist", "VR Designer", "Virtual Artist"], - "Science Fiction": ["Astronaut", "Space Engineer", "Exoplanet Researcher", "Xenobiologist", "Space Bounty Hunter", "Starship Explorer", "AI Developer", "Intergalactic Trader", "Galactic Diplomat", "Virtual Reality Game Developer"], - "Horror": ["Doctor", "Detective", "Artist", "Nurse", "Astrologer", "Shaman", "Exorcist", "Journalist", "Scientist", "Gravekeeper"], - "Romance": ["Novelist", "Florist", "Barista", "Violinist", "Actor", "Photographer", "Diary Keeper", "Fashion Designer", "Chef", "Traveler"], - "Mystery": ["Detective", "Investigative Journalist", "Crime Scene Investigator", "Mystery Novelist", "Defense Attorney", "Psychologist", "Archaeologist", "Secret Agent", "Hacker", "Museum Curator"], - "Thriller": ["Detective", "Journalist", "Forensic Scientist", "Hacker", "Police Officer", "Profiler", "Secret Agent", "Security Specialist", "Fraud Investigator", "Criminal Psychologist"], - "Survival": ["Explorer", "Marine", "Jungle Guide", "Rescue Worker", "Survivalist", "Mountaineer", "Diver", "Pilot", "Extreme Weather Researcher", "Hunter"], - "Post-apocalyptic": ["Scout", "Survivalist", "Archaeologist", "Trader", "Mechanic", "Medical Aid", "Militia Leader", "Craftsman", "Farmer", "Builder"], - "Historical Fiction": ["Knight", "Explorer", "Diplomat", "Historian", "General", "Monarch", "Merchant", "Archer", "Landlord", "Priest"] -} - -ages = ["10s", "20s", "30s", "40s", "50s"] -random_names = ["Aaron", "Abigail", "Adam", "Adrian", "Alan", "Alexandra", "Alyssa", "Amanda", "Amber", "Amy", "Andrea", "Andrew", "Angela", "Angelina", "Anthony", "Antonio", "Ashley", "Austin", "Benjamin", "Brandon", "Brian", "Brittany", "Brooke", "Bruce", "Bryan", "Caleb", "Cameron", "Carol", "Caroline", "Catherine", "Charles", "Charlotte", "Chase", "Chelsea", "Christopher", "Cody", "Colin", "Connor", "Cooper", "Corey", "Cristian", "Daniel", "David", "Deborah", "Denise", "Dennis", "Derek", "Diana", "Dorothy", "Douglas", "Dylan", "Edward", "Elizabeth", "Emily", "Emma", "Eric", "Ethan", "Evan", "Gabriel", "Gavin", "George", "Gina", "Grace", "Gregory", "Hannah", "Harrison", "Hayden", "Heather", "Helen", "Henry", "Holly", "Hope", "Hunter", "Ian", "Isaac", "Isabella", "Jack", "Jacob", "James", "Jason", "Jeffrey", "Jenna", "Jennifer", "Jessica", "Jesse", "Joan", "John", "Jonathan", "Joseph", "Joshua", "Justin", "Kayla", "Kevin", "Kimberly", "Kyle", "Laura", "Lauren", "Lawrence", "Leah", "Leo", "Leslie", "Levi", "Lewis", "Liam", "Logan", "Lucas", "Lucy", "Luis", "Luke", "Madison", "Maegan", "Maria", "Mark", "Matthew", "Megan", "Michael", "Michelle", "Molly", "Morgan", "Nathan", "Nathaniel", "Nicholas", "Nicole", "Noah", "Olivia", "Owen", "Paige", "Parker", "Patrick", "Paul", "Peter", "Philip", "Phoebe", "Rachel", "Randy", "Rebecca", "Richard", "Robert", "Roger", "Ronald", "Rose", "Russell", "Ryan", "Samantha", "Samuel", "Sandra", "Sarah", "Scott", "Sean", "Sebastian", "Seth", "Shannon", "Shawn", "Shelby", "Sierra", "Simon", "Sophia", "Stephanie", "Stephen", "Steven", "Sue", "Susan", "Sydney", "Taylor", "Teresa", "Thomas", "Tiffany", "Timothy", "Todd", "Tom", "Tommy", "Tracy", "Travis", "Tyler", "Victoria", "Vincent", "Violet", "Warren", "William", "Zach", "Zachary", "Zoe"] -personalities = ['Optimistic', 'Kind', 'Resilient', 'Generous', 'Humorous', 'Creative', 'Empathetic', 'Ambitious', 'Adventurous'] - -default_character_images = ["assets/image.png"] - -styles = ["sd character", "cartoon", "realistic"] \ No newline at end of file diff --git a/spaces/chasemcdo/hf_localai/examples/slack-qa-bot/README.md b/spaces/chasemcdo/hf_localai/examples/slack-qa-bot/README.md deleted file mode 100644 index 7844d6699f38dae0eaf79f4c6960c3bc9c0be6d3..0000000000000000000000000000000000000000 --- a/spaces/chasemcdo/hf_localai/examples/slack-qa-bot/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Slack QA Bot - -This example uses https://github.com/spectrocloud-labs/Slack-QA-bot to deploy a slack bot that can answer to your documentation! - -- Create a new Slack app using the manifest-dev.yml file -- Install the app into your Slack workspace -- Retrieve your slack keys and edit `.env` -- Start the app - -```bash -# Clone LocalAI -git clone https://github.com/go-skynet/LocalAI - -cd LocalAI/examples/slack-qa-bot - -cp -rfv .env.example .env - -# Edit .env and add slackbot api keys, or repository settings to scan -vim .env - -# run the bot -docker-compose up -``` diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/_cffi_include.h b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/_cffi_include.h deleted file mode 100644 index e4c0a672405298ddb3dcb2e2ca6da9eea3d2e162..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/_cffi_include.h +++ /dev/null @@ -1,385 +0,0 @@ -#define _CFFI_ - -/* We try to define Py_LIMITED_API before including Python.h. - - Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and - Py_REF_DEBUG are not defined. This is a best-effort approximation: - we can learn about Py_DEBUG from pyconfig.h, but it is unclear if - the same works for the other two macros. Py_DEBUG implies them, - but not the other way around. - - The implementation is messy (issue #350): on Windows, with _MSC_VER, - we have to define Py_LIMITED_API even before including pyconfig.h. - In that case, we guess what pyconfig.h will do to the macros above, - and check our guess after the #include. - - Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv - version >= 16.0.0. With older versions of either, you don't get a - copy of PYTHON3.DLL in the virtualenv. We can't check the version of - CPython *before* we even include pyconfig.h. ffi.set_source() puts - a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is - running on Windows < 3.5, as an attempt at fixing it, but that's - arguably wrong because it may not be the target version of Python. - Still better than nothing I guess. As another workaround, you can - remove the definition of Py_LIMITED_API here. - - See also 'py_limited_api' in cffi/setuptools_ext.py. -*/ -#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API) -# ifdef _MSC_VER -# if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) -# define Py_LIMITED_API -# endif -# include - /* sanity-check: Py_LIMITED_API will cause crashes if any of these - are also defined. Normally, the Python file PC/pyconfig.h does not - cause any of these to be defined, with the exception that _DEBUG - causes Py_DEBUG. Double-check that. */ -# ifdef Py_LIMITED_API -# if defined(Py_DEBUG) -# error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set" -# endif -# if defined(Py_TRACE_REFS) -# error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set" -# endif -# if defined(Py_REF_DEBUG) -# error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set" -# endif -# endif -# else -# include -# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) -# define Py_LIMITED_API -# endif -# endif -#endif - -#include -#ifdef __cplusplus -extern "C" { -#endif -#include -#include "parse_c_type.h" - -/* this block of #ifs should be kept exactly identical between - c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py - and cffi/_cffi_include.h */ -#if defined(_MSC_VER) -# include /* for alloca() */ -# if _MSC_VER < 1600 /* MSVC < 2010 */ - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; - typedef __int8 int_least8_t; - typedef __int16 int_least16_t; - typedef __int32 int_least32_t; - typedef __int64 int_least64_t; - typedef unsigned __int8 uint_least8_t; - typedef unsigned __int16 uint_least16_t; - typedef unsigned __int32 uint_least32_t; - typedef unsigned __int64 uint_least64_t; - typedef __int8 int_fast8_t; - typedef __int16 int_fast16_t; - typedef __int32 int_fast32_t; - typedef __int64 int_fast64_t; - typedef unsigned __int8 uint_fast8_t; - typedef unsigned __int16 uint_fast16_t; - typedef unsigned __int32 uint_fast32_t; - typedef unsigned __int64 uint_fast64_t; - typedef __int64 intmax_t; - typedef unsigned __int64 uintmax_t; -# else -# include -# endif -# if _MSC_VER < 1800 /* MSVC < 2013 */ -# ifndef __cplusplus - typedef unsigned char _Bool; -# endif -# endif -#else -# include -# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) -# include -# endif -#endif - -#ifdef __GNUC__ -# define _CFFI_UNUSED_FN __attribute__((unused)) -#else -# define _CFFI_UNUSED_FN /* nothing */ -#endif - -#ifdef __cplusplus -# ifndef _Bool - typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */ -# endif -#endif - -/********** CPython-specific section **********/ -#ifndef PYPY_VERSION - - -#if PY_MAJOR_VERSION >= 3 -# define PyInt_FromLong PyLong_FromLong -#endif - -#define _cffi_from_c_double PyFloat_FromDouble -#define _cffi_from_c_float PyFloat_FromDouble -#define _cffi_from_c_long PyInt_FromLong -#define _cffi_from_c_ulong PyLong_FromUnsignedLong -#define _cffi_from_c_longlong PyLong_FromLongLong -#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong -#define _cffi_from_c__Bool PyBool_FromLong - -#define _cffi_to_c_double PyFloat_AsDouble -#define _cffi_to_c_float PyFloat_AsDouble - -#define _cffi_from_c_int(x, type) \ - (((type)-1) > 0 ? /* unsigned */ \ - (sizeof(type) < sizeof(long) ? \ - PyInt_FromLong((long)x) : \ - sizeof(type) == sizeof(long) ? \ - PyLong_FromUnsignedLong((unsigned long)x) : \ - PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ - (sizeof(type) <= sizeof(long) ? \ - PyInt_FromLong((long)x) : \ - PyLong_FromLongLong((long long)x))) - -#define _cffi_to_c_int(o, type) \ - ((type)( \ - sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ - : (type)_cffi_to_c_i8(o)) : \ - sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ - : (type)_cffi_to_c_i16(o)) : \ - sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ - : (type)_cffi_to_c_i32(o)) : \ - sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ - : (type)_cffi_to_c_i64(o)) : \ - (Py_FatalError("unsupported size for type " #type), (type)0))) - -#define _cffi_to_c_i8 \ - ((int(*)(PyObject *))_cffi_exports[1]) -#define _cffi_to_c_u8 \ - ((int(*)(PyObject *))_cffi_exports[2]) -#define _cffi_to_c_i16 \ - ((int(*)(PyObject *))_cffi_exports[3]) -#define _cffi_to_c_u16 \ - ((int(*)(PyObject *))_cffi_exports[4]) -#define _cffi_to_c_i32 \ - ((int(*)(PyObject *))_cffi_exports[5]) -#define _cffi_to_c_u32 \ - ((unsigned int(*)(PyObject *))_cffi_exports[6]) -#define _cffi_to_c_i64 \ - ((long long(*)(PyObject *))_cffi_exports[7]) -#define _cffi_to_c_u64 \ - ((unsigned long long(*)(PyObject *))_cffi_exports[8]) -#define _cffi_to_c_char \ - ((int(*)(PyObject *))_cffi_exports[9]) -#define _cffi_from_c_pointer \ - ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10]) -#define _cffi_to_c_pointer \ - ((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11]) -#define _cffi_get_struct_layout \ - not used any more -#define _cffi_restore_errno \ - ((void(*)(void))_cffi_exports[13]) -#define _cffi_save_errno \ - ((void(*)(void))_cffi_exports[14]) -#define _cffi_from_c_char \ - ((PyObject *(*)(char))_cffi_exports[15]) -#define _cffi_from_c_deref \ - ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16]) -#define _cffi_to_c \ - ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17]) -#define _cffi_from_c_struct \ - ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18]) -#define _cffi_to_c_wchar_t \ - ((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19]) -#define _cffi_from_c_wchar_t \ - ((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20]) -#define _cffi_to_c_long_double \ - ((long double(*)(PyObject *))_cffi_exports[21]) -#define _cffi_to_c__Bool \ - ((_Bool(*)(PyObject *))_cffi_exports[22]) -#define _cffi_prepare_pointer_call_argument \ - ((Py_ssize_t(*)(struct _cffi_ctypedescr *, \ - PyObject *, char **))_cffi_exports[23]) -#define _cffi_convert_array_from_object \ - ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24]) -#define _CFFI_CPIDX 25 -#define _cffi_call_python \ - ((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX]) -#define _cffi_to_c_wchar3216_t \ - ((int(*)(PyObject *))_cffi_exports[26]) -#define _cffi_from_c_wchar3216_t \ - ((PyObject *(*)(int))_cffi_exports[27]) -#define _CFFI_NUM_EXPORTS 28 - -struct _cffi_ctypedescr; - -static void *_cffi_exports[_CFFI_NUM_EXPORTS]; - -#define _cffi_type(index) ( \ - assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \ - (struct _cffi_ctypedescr *)_cffi_types[index]) - -static PyObject *_cffi_init(const char *module_name, Py_ssize_t version, - const struct _cffi_type_context_s *ctx) -{ - PyObject *module, *o_arg, *new_module; - void *raw[] = { - (void *)module_name, - (void *)version, - (void *)_cffi_exports, - (void *)ctx, - }; - - module = PyImport_ImportModule("_cffi_backend"); - if (module == NULL) - goto failure; - - o_arg = PyLong_FromVoidPtr((void *)raw); - if (o_arg == NULL) - goto failure; - - new_module = PyObject_CallMethod( - module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg); - - Py_DECREF(o_arg); - Py_DECREF(module); - return new_module; - - failure: - Py_XDECREF(module); - return NULL; -} - - -#ifdef HAVE_WCHAR_H -typedef wchar_t _cffi_wchar_t; -#else -typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */ -#endif - -_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o) -{ - if (sizeof(_cffi_wchar_t) == 2) - return (uint16_t)_cffi_to_c_wchar_t(o); - else - return (uint16_t)_cffi_to_c_wchar3216_t(o); -} - -_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x) -{ - if (sizeof(_cffi_wchar_t) == 2) - return _cffi_from_c_wchar_t((_cffi_wchar_t)x); - else - return _cffi_from_c_wchar3216_t((int)x); -} - -_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o) -{ - if (sizeof(_cffi_wchar_t) == 4) - return (int)_cffi_to_c_wchar_t(o); - else - return (int)_cffi_to_c_wchar3216_t(o); -} - -_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x) -{ - if (sizeof(_cffi_wchar_t) == 4) - return _cffi_from_c_wchar_t((_cffi_wchar_t)x); - else - return _cffi_from_c_wchar3216_t((int)x); -} - -union _cffi_union_alignment_u { - unsigned char m_char; - unsigned short m_short; - unsigned int m_int; - unsigned long m_long; - unsigned long long m_longlong; - float m_float; - double m_double; - long double m_longdouble; -}; - -struct _cffi_freeme_s { - struct _cffi_freeme_s *next; - union _cffi_union_alignment_u alignment; -}; - -_CFFI_UNUSED_FN static int -_cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg, - char **output_data, Py_ssize_t datasize, - struct _cffi_freeme_s **freeme) -{ - char *p; - if (datasize < 0) - return -1; - - p = *output_data; - if (p == NULL) { - struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( - offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); - if (fp == NULL) - return -1; - fp->next = *freeme; - *freeme = fp; - p = *output_data = (char *)&fp->alignment; - } - memset((void *)p, 0, (size_t)datasize); - return _cffi_convert_array_from_object(p, ctptr, arg); -} - -_CFFI_UNUSED_FN static void -_cffi_free_array_arguments(struct _cffi_freeme_s *freeme) -{ - do { - void *p = (void *)freeme; - freeme = freeme->next; - PyObject_Free(p); - } while (freeme != NULL); -} - -/********** end CPython-specific section **********/ -#else -_CFFI_UNUSED_FN -static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *); -# define _cffi_call_python _cffi_call_python_org -#endif - - -#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0])) - -#define _cffi_prim_int(size, sign) \ - ((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \ - (size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \ - (size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \ - (size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \ - _CFFI__UNKNOWN_PRIM) - -#define _cffi_prim_float(size) \ - ((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \ - (size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \ - (size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \ - _CFFI__UNKNOWN_FLOAT_PRIM) - -#define _cffi_check_int(got, got_nonpos, expected) \ - ((got_nonpos) == (expected <= 0) && \ - (got) == (unsigned long long)expected) - -#ifdef MS_WIN32 -# define _cffi_stdcall __stdcall -#else -# define _cffi_stdcall /* nothing */ -#endif - -#ifdef __cplusplus -} -#endif diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fsspec/implementations/dask.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fsspec/implementations/dask.py deleted file mode 100644 index 3e1276463db6866665e6a0fe114efc247971b57e..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fsspec/implementations/dask.py +++ /dev/null @@ -1,152 +0,0 @@ -import dask -from distributed.client import Client, _get_global_client -from distributed.worker import Worker - -from fsspec import filesystem -from fsspec.spec import AbstractBufferedFile, AbstractFileSystem -from fsspec.utils import infer_storage_options - - -def _get_client(client): - if client is None: - return _get_global_client() - elif isinstance(client, Client): - return client - else: - # e.g., connection string - return Client(client) - - -def _in_worker(): - return bool(Worker._instances) - - -class DaskWorkerFileSystem(AbstractFileSystem): - """View files accessible to a worker as any other remote file-system - - When instances are run on the worker, uses the real filesystem. When - run on the client, they call the worker to provide information or data. - - **Warning** this implementation is experimental, and read-only for now. - """ - - def __init__( - self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs - ): - super().__init__(**kwargs) - if not (fs is None) ^ (target_protocol is None): - raise ValueError( - "Please provide one of filesystem instance (fs) or" - " target_protocol, not both" - ) - self.target_protocol = target_protocol - self.target_options = target_options - self.worker = None - self.client = client - self.fs = fs - self._determine_worker() - - @staticmethod - def _get_kwargs_from_urls(path): - so = infer_storage_options(path) - if "host" in so and "port" in so: - return {"client": f"{so['host']}:{so['port']}"} - else: - return {} - - def _determine_worker(self): - if _in_worker(): - self.worker = True - if self.fs is None: - self.fs = filesystem( - self.target_protocol, **(self.target_options or {}) - ) - else: - self.worker = False - self.client = _get_client(self.client) - self.rfs = dask.delayed(self) - - def mkdir(self, *args, **kwargs): - if self.worker: - self.fs.mkdir(*args, **kwargs) - else: - self.rfs.mkdir(*args, **kwargs).compute() - - def rm(self, *args, **kwargs): - if self.worker: - self.fs.rm(*args, **kwargs) - else: - self.rfs.rm(*args, **kwargs).compute() - - def copy(self, *args, **kwargs): - if self.worker: - self.fs.copy(*args, **kwargs) - else: - self.rfs.copy(*args, **kwargs).compute() - - def mv(self, *args, **kwargs): - if self.worker: - self.fs.mv(*args, **kwargs) - else: - self.rfs.mv(*args, **kwargs).compute() - - def ls(self, *args, **kwargs): - if self.worker: - return self.fs.ls(*args, **kwargs) - else: - return self.rfs.ls(*args, **kwargs).compute() - - def _open( - self, - path, - mode="rb", - block_size=None, - autocommit=True, - cache_options=None, - **kwargs, - ): - if self.worker: - return self.fs._open( - path, - mode=mode, - block_size=block_size, - autocommit=autocommit, - cache_options=cache_options, - **kwargs, - ) - else: - return DaskFile( - fs=self, - path=path, - mode=mode, - block_size=block_size, - autocommit=autocommit, - cache_options=cache_options, - **kwargs, - ) - - def fetch_range(self, path, mode, start, end): - if self.worker: - with self._open(path, mode) as f: - f.seek(start) - return f.read(end - start) - else: - return self.rfs.fetch_range(path, mode, start, end).compute() - - -class DaskFile(AbstractBufferedFile): - def __init__(self, mode="rb", **kwargs): - if mode != "rb": - raise ValueError('Remote dask files can only be opened in "rb" mode') - super().__init__(**kwargs) - - def _upload_chunk(self, final=False): - pass - - def _initiate_upload(self): - """Create remote file/upload""" - pass - - def _fetch_range(self, start, end): - """Get the specified set of bytes from remote""" - return self.fs.fetch_range(self.path, self.mode, start, end) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/functorch/dim/op_properties.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/functorch/dim/op_properties.py deleted file mode 100644 index fdfb0b9ae91d320732cb1a1b00e8dc2be2c43f6d..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/functorch/dim/op_properties.py +++ /dev/null @@ -1,282 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the BSD-style license found in the -# LICENSE file in the root directory of this source tree. -import torch -# pointwise operators can go through a faster pathway - -tensor_magic_methods = [ - 'add', - '' -] -pointwise_magic_methods_with_reverse = ( - 'add', 'sub', 'mul', 'floordiv', 'div', 'truediv', 'mod', - 'pow', 'lshift', 'rshift', 'and', 'or', 'xor' -) -pointwise_magic_methods = ( - *(x for m in pointwise_magic_methods_with_reverse for x in (m, 'r' + m)), - 'eq', 'gt', 'le', 'lt', 'ge', 'gt', 'ne', 'neg', 'pos', - 'abs', 'invert', - 'iadd', 'isub', 'imul', 'ifloordiv', 'idiv', - 'itruediv', 'imod', 'ipow', 'ilshift', 'irshift', 'iand', - 'ior', 'ixor', - 'int', 'long', 'float', 'complex', -) - -pointwise_methods = ( - *(f'__{m}__' for m in pointwise_magic_methods), -) - -pointwise = ( - *(getattr(torch.Tensor, m) for m in pointwise_methods), - torch.nn.functional.dropout, - torch.where, - torch.Tensor.abs, - torch.abs, - torch.Tensor.acos, - torch.acos, - torch.Tensor.acosh, - torch.acosh, - torch.Tensor.add, - torch.add, - torch.Tensor.addcdiv, - torch.addcdiv, - torch.Tensor.addcmul, - torch.addcmul, - torch.Tensor.addr, - torch.addr, - torch.Tensor.angle, - torch.angle, - torch.Tensor.asin, - torch.asin, - torch.Tensor.asinh, - torch.asinh, - torch.Tensor.atan, - torch.atan, - torch.Tensor.atan2, - torch.atan2, - torch.Tensor.atanh, - torch.atanh, - torch.Tensor.bitwise_and, - torch.bitwise_and, - torch.Tensor.bitwise_left_shift, - torch.bitwise_left_shift, - torch.Tensor.bitwise_not, - torch.bitwise_not, - torch.Tensor.bitwise_or, - torch.bitwise_or, - torch.Tensor.bitwise_right_shift, - torch.bitwise_right_shift, - torch.Tensor.bitwise_xor, - torch.bitwise_xor, - torch.Tensor.ceil, - torch.ceil, - torch.celu, - torch.nn.functional.celu, - torch.Tensor.clamp, - torch.clamp, - torch.Tensor.clamp_max, - torch.clamp_max, - torch.Tensor.clamp_min, - torch.clamp_min, - torch.Tensor.copysign, - torch.copysign, - torch.Tensor.cos, - torch.cos, - torch.Tensor.cosh, - torch.cosh, - torch.Tensor.deg2rad, - torch.deg2rad, - torch.Tensor.digamma, - torch.digamma, - torch.Tensor.div, - torch.div, - torch.dropout, - torch.nn.functional.dropout, - torch.nn.functional.elu, - torch.Tensor.eq, - torch.eq, - torch.Tensor.erf, - torch.erf, - torch.Tensor.erfc, - torch.erfc, - torch.Tensor.erfinv, - torch.erfinv, - torch.Tensor.exp, - torch.exp, - torch.Tensor.exp2, - torch.exp2, - torch.Tensor.expm1, - torch.expm1, - torch.feature_dropout, - torch.Tensor.float_power, - torch.float_power, - torch.Tensor.floor, - torch.floor, - torch.Tensor.floor_divide, - torch.floor_divide, - torch.Tensor.fmod, - torch.fmod, - torch.Tensor.frac, - torch.frac, - torch.Tensor.frexp, - torch.frexp, - torch.Tensor.gcd, - torch.gcd, - torch.Tensor.ge, - torch.ge, - torch.nn.functional.gelu, - torch.nn.functional.glu, - torch.Tensor.gt, - torch.gt, - torch.Tensor.hardshrink, - torch.hardshrink, - torch.nn.functional.hardshrink, - torch.nn.functional.hardsigmoid, - torch.nn.functional.hardswish, - torch.nn.functional.hardtanh, - torch.Tensor.heaviside, - torch.heaviside, - torch.Tensor.hypot, - torch.hypot, - torch.Tensor.i0, - torch.i0, - torch.Tensor.igamma, - torch.igamma, - torch.Tensor.igammac, - torch.igammac, - torch.Tensor.isclose, - torch.isclose, - torch.Tensor.isfinite, - torch.isfinite, - torch.Tensor.isinf, - torch.isinf, - torch.Tensor.isnan, - torch.isnan, - torch.Tensor.isneginf, - torch.isneginf, - torch.Tensor.isposinf, - torch.isposinf, - torch.Tensor.isreal, - torch.isreal, - torch.Tensor.kron, - torch.kron, - torch.Tensor.lcm, - torch.lcm, - torch.Tensor.ldexp, - torch.ldexp, - torch.Tensor.le, - torch.le, - torch.nn.functional.leaky_relu, - torch.Tensor.lerp, - torch.lerp, - torch.Tensor.lgamma, - torch.lgamma, - torch.Tensor.log, - torch.log, - torch.Tensor.log10, - torch.log10, - torch.Tensor.log1p, - torch.log1p, - torch.Tensor.log2, - torch.log2, - torch.nn.functional.logsigmoid, - torch.Tensor.logical_and, - torch.logical_and, - torch.Tensor.logical_not, - torch.logical_not, - torch.Tensor.logical_or, - torch.logical_or, - torch.Tensor.logical_xor, - torch.logical_xor, - torch.Tensor.logit, - torch.logit, - torch.Tensor.lt, - torch.lt, - torch.Tensor.maximum, - torch.maximum, - torch.Tensor.minimum, - torch.minimum, - torch.nn.functional.mish, - torch.Tensor.mvlgamma, - torch.mvlgamma, - torch.Tensor.nan_to_num, - torch.nan_to_num, - torch.Tensor.ne, - torch.ne, - torch.Tensor.neg, - torch.neg, - torch.Tensor.nextafter, - torch.nextafter, - torch.Tensor.outer, - torch.outer, - torch.polar, - torch.Tensor.polygamma, - torch.polygamma, - torch.Tensor.positive, - torch.positive, - torch.Tensor.pow, - torch.pow, - torch.Tensor.prelu, - torch.prelu, - torch.nn.functional.prelu, - torch.Tensor.rad2deg, - torch.rad2deg, - torch.Tensor.reciprocal, - torch.reciprocal, - torch.Tensor.relu, - torch.relu, - torch.nn.functional.relu, - torch.nn.functional.relu6, - torch.Tensor.remainder, - torch.remainder, - torch.Tensor.round, - torch.round, - torch.rrelu, - torch.nn.functional.rrelu, - torch.Tensor.rsqrt, - torch.rsqrt, - torch.rsub, - torch.selu, - torch.nn.functional.selu, - torch.Tensor.sgn, - torch.sgn, - torch.Tensor.sigmoid, - torch.sigmoid, - torch.nn.functional.sigmoid, - torch.Tensor.sign, - torch.sign, - torch.Tensor.signbit, - torch.signbit, - torch.nn.functional.silu, - torch.Tensor.sin, - torch.sin, - torch.Tensor.sinc, - torch.sinc, - torch.Tensor.sinh, - torch.sinh, - torch.nn.functional.softplus, - torch.nn.functional.softshrink, - torch.Tensor.sqrt, - torch.sqrt, - torch.Tensor.square, - torch.square, - torch.Tensor.sub, - torch.sub, - torch.Tensor.tan, - torch.tan, - torch.Tensor.tanh, - torch.tanh, - torch.nn.functional.tanh, - torch.threshold, - torch.nn.functional.threshold, - torch.trapz, - torch.Tensor.true_divide, - torch.true_divide, - torch.Tensor.trunc, - torch.trunc, - torch.Tensor.xlogy, - torch.xlogy, - torch.rand_like, -) diff --git a/spaces/cihyFjudo/fairness-paper-search/Advanced Media Player 2.0 Free BETTER Download.md b/spaces/cihyFjudo/fairness-paper-search/Advanced Media Player 2.0 Free BETTER Download.md deleted file mode 100644 index 957f224553d3c2a48a63b6ea687c2cdf58698b23..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Advanced Media Player 2.0 Free BETTER Download.md +++ /dev/null @@ -1,26 +0,0 @@ - -

Advanced Systems Format (.asf)The Advanced Systems Format (ASF) is the preferred Windows Media file format. With Windows Media Player, if the appropriate codecs are installed on your computer, you can play audio content, video content, or both, that is compressed with a wide variety of codecs and that is stored in an .asf file. Additionally, you can stream audio and video content with Windows Media Services, or you can package that content with Windows Media Rights Manager.

ASF is an extensible file format that stores synchronized multimedia data. It supports data delivery over a wide variety of networks and protocols. It is also suitable for local playback. ASF supports advanced multimedia capabilities including extensible media types, component download, scalable media types, author-specified stream prioritization, multiple language support, and extensive bibliographic capabilities that include document and content management.

Typically, ASF files that contain audio content that is compressed with the Windows Media Audio (WMA) codec use the .wma extension. Similarly, ASF files that contain audio content, video content, or both, that is compressed with Windows Media Audio (WMA) and Windows Media Video (WMV) codecs use the .wmv extension. Finally, content that is compressed with any other codec use the generic .asf extension. For more information about ASF, visit the following Microsoft Web site:

-

advanced media player 2.0 free download


Download Filehttps://tinurli.com/2uwjXq



-

Windows Media Download (WMD) packages combine Windows Media Player skin borders, playlist information, and multimedia content in a single downloadable file that uses a .wmd extension. A .wmd package can include a whole album of music videos that also displays advertising in the form of graphical branding and links to an online music retailer Web site.

To download a .wmd package from a Web site, click the link to the package. When the package is downloaded to your computer, Windows Media Player automatically extracts the files that are contained in the package, adds the playlists in the package, adds the content to Media Library, displays the border skin in the
Now Playing pane of Windows Media Player (in full mode), and then plays the first item in the playlist. For more information about .wmd files, visit the following Microsoft Web site:

-

  • Play all files, in all formats, including exotic ones, like classic VLC media player.
  • Play MKV, multiple audio tracks (including 5.1), and subtitles tracks (including SSA!).
  • Support for network streams, including HLS, MMS or RTSP.
  • Include video filters, playback speed manipulation, and fine seeking.
  • A media library, with WiFi Uploads & Downloads, Dropbox, Google Drive, iCloud Drive, OneDrive & Box.com integration and optional passcode lock.
  • Web Interface for easy uploads and downloads to/from device.
  • Integration for bluetooth headsets and AirPlay including spatial audio for AirPods Pro and Max.
  • Full support for file servers (SMB / Windows shares, NFS, SFTP and FTP)
  • Local Network service discovery with UPnP and native support for Plex
  • On-the-fly audio and subtitles track synchronization
  • Supports iOS 9.0 or later
  • Full 64bit support on latest iPhone and latest iPad
  • Completely free, libre and open source.
  • -

    Legal | Report Trademark Abuse
    VideoLAN, VLC, VLC media player and x264 are trademarks internationally registered by the VideoLAN non-profit organization.
    VideoLAN software is licensed under various open-source licenses: use and distribution are defined by each software license.

    -

    -

    Open-source software is software whose source code is publicly accessible for use, modification, redistribution, and other uses. As a result, anyone can download and use an open-source media player to play back media without paying anything.

    -

    There are many free video players for PC, but the best one I think is EaseUS RecExperts. This software lets you play almost all video and audio files, change the playback speed freely, and even edit them as you like.

    -

    Although many media players for Windows 10 and Mac are available for viewing videos on your desktop or portable devices, open source video player programs are consistently highly rated for their advantages. No matter what operating system you use; Linux, Mac, or Windows; you can always have access to open-source software that will help you easily play any media file format. The post below provides information on the top 7 free, open-source media players. Now, let's take a look.

    -

    The MPV video player is another free, open-source video player. It is a video player built on the FFMPEG platform that supports playing audio and video files in various formats, including MP4, AVI, WMV, MKV, VOB, M4V, 3GP, MP3, AAC, and WAV. Plus, you can flexibly speed up video playback while watching any video.

    -

    Bino is another open-source video player available for free on Windows and Mac. The primary purpose of this software is to play and view HD, 3D, or stereoscopic films. Most of its capabilities, such as Left View, Right View, Top View, and Bottom View, are offered to change two distinct video streams of a 3D video. However, this HD video player also supports playing common 2D video formats, including MP4, AVI, WMV, MPEG, and others.

    -

    Another free, open-source media player is Kodi. In reality, it is an open-source entertainment center package that includes media management tools, a player for opening audio and video files, a library, and more. Its video player supports various well-known file types, including MP4, AVI, WMV, MKV, WMV, ASF, and more. You can adjust several video properties, such as Video Scaling, Brightness, Contrast, and Pixel Ratio, from the Video Settings menu and watch the video.

    -

    SMPlayer is a Windows video player that is entirely free and open source. It has numerous integrated programs that allow you to play almost audio and video files in any format. This freeware includes a special Video Menu with several tools for customizing video playback. You can adjust the aspect ratio, add filters (noise, post-processing, deblock, etc.), rotate the video, take screenshots, and perform other functions using the video menu.

    -

    Another free, open-source video player is ExMplayer. In addition to 3D media, this player can play SD, HD, and FULL HD videos. In this versatile video and music player for Windows 10, audio files can also be played. It allows you to change the playing speed, apply video filters, change the aspect ratio, change the video equalizer settings, and tweak the video quality and characteristics. Similarly, you can alter the audio settings using an audio equalization, an audio booster, an audio filter, etc., to change the audio quality.

    -

    This media player also includes several extra tools, including a Media Cutter (for cutting a portion of a video), an Audio Extractor (for extracting audio from the video file), an Audio Converter (for converting audio file formats), a Video Downloader (for downloading online videos), and a Movie Animator.

    -

    While EaseUS RecExperts is primarily a Windows screen recorder, it also includes an advanced Media Player. It is a versatile media player that can quickly and easily open various common media files, including MP4, MOV, MKV, MP3, and AAC. You can also speed up video playback from 0.5X to 2X to suit your needs. If needed, you can even choose to extract audio from video with a simple click.

    -

    So, in this article, you can read and understand the features and the pros and cons of each open-source video player, which will guide you to download the most app software. You can always use the EaseUS RecExperts tool as an alternative if nothing else works out for you.

    -

    Windows Media Player is the sole name that strikes a chord when we talk about playing a media file on a PC. Windows Media player has been used to listen to the most recent hits and, therefore, is prone to some technical errors, the main ones being songs duplication. It occurs after you add different files from different folders and CDs. You may find two or more copies of a single music file after it gets duplicated.

    -

    File duplication may also occur when you move advanced media files on your PC. While doing so, the file name and file data stay unaltered in your library. Then, at that point, when you select a file to open from its new location, Windows Media Player duplicate songs in library.

    -

    4DDiG Duplicate File Deleter is the best duplicate song remover, and an absolute answer to your "windows media player duplicates all my songs" query. It used advanced search algorithms to track down the duplicated files on your device.

    -

    If you receive an email with a link to a Webex recording, just click on the link to watch it. There's no player required. Or if you've downloaded a file, get the Webex Player below (file types are .ARF or .WRF) for your operating system.

    -

    Ultra HD live production switcher with so many features, you can combine them all to make an incredibly powerful 8K switcher! This massive 4 M/E switcher features 40 12G-SDI inputs, 24 12G-SDI aux outputs, 4 DVEs, 16 ATEM Advanced Chroma Keyers, 4 media players, 4 independent Ultra HD multi viewers, 2 SuperSource processors and even standards conversion on all inputs! When switched to work in 8K, all of these features are be combined to make a powerful native 8K switcher! You even get built in talkback and a professional 156 channel Fairlight audio mixer with EQ and dynamics!

    -

    The new ATEM 2 M/E Production Studio 4K lets you produce broadcast quality live multi camera production in SD, HD or amazing Ultra HD! Featuring 20 inputs with built in re-synchronizers so you can connect the widest range of video sources such as cameras, disk recorders and computers for incredible live music, sport and more! ATEM 2 M/E Production Studio 4K has advanced broadcast features such as chroma key, customizable transitions, upstream and downstream keyers, DVE, Super Source, audio mixer, 2 x multi views, media pool and more! You also get 6G-SDI and HDMI 4K connections and 6 auxiliary outputs for the most advanced live production switching!

    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/cihyFjudo/fairness-paper-search/Adventure Chronicles The Search For Lost Treasure Full Crack [Patch].md b/spaces/cihyFjudo/fairness-paper-search/Adventure Chronicles The Search For Lost Treasure Full Crack [Patch].md deleted file mode 100644 index aeac48fd21b2b831133ea8f0d1caa75ed6ad7753..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Adventure Chronicles The Search For Lost Treasure Full Crack [Patch].md +++ /dev/null @@ -1,6 +0,0 @@ -

    Adventure Chronicles: The Search For Lost Treasure Full Crack [Patch]


    Download Filehttps://tinurli.com/2uwklH



    - - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/cihyFjudo/fairness-paper-search/AliensColonialMarinesRarPassword The Complete Walkthrough of the Game.md b/spaces/cihyFjudo/fairness-paper-search/AliensColonialMarinesRarPassword The Complete Walkthrough of the Game.md deleted file mode 100644 index 90ade3a20e653034e7f6fad835a10d974a4f18b4..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/AliensColonialMarinesRarPassword The Complete Walkthrough of the Game.md +++ /dev/null @@ -1,6 +0,0 @@ -

    AliensColonialMarinesRarPassword


    Download Zip ::: https://tinurli.com/2uwipC



    - - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/cihyFjudo/fairness-paper-search/Antares AutoTune Pro 9.1.0 Crack Serial Key Free Download ((EXCLUSIVE)).md b/spaces/cihyFjudo/fairness-paper-search/Antares AutoTune Pro 9.1.0 Crack Serial Key Free Download ((EXCLUSIVE)).md deleted file mode 100644 index 714cfb2aa1a76af61866412711baaa560b42e474..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Antares AutoTune Pro 9.1.0 Crack Serial Key Free Download ((EXCLUSIVE)).md +++ /dev/null @@ -1,6 +0,0 @@ -

    Antares AutoTune Pro 9.1.0 Crack Serial Key Free Download


    Downloadhttps://tinurli.com/2uwkN7



    - - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/cihyFjudo/fairness-paper-search/Facebook Auto Likes.com.md b/spaces/cihyFjudo/fairness-paper-search/Facebook Auto Likes.com.md deleted file mode 100644 index 7a1f9087e4a8e28f097b8aa4ef46d9a206a547b8..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Facebook Auto Likes.com.md +++ /dev/null @@ -1,27 +0,0 @@ - -

    We Use All Token after 1 minutes Interval so Facebook never detect unusual activity and not Lock Your Account, If you're using multiple website of auto liker at the same time then not our responsibility.

    -

    facebook auto likes.com


    Download Zip ->>->>->> https://tinurli.com/2uwjOm



    -

    By Invite via your Referral link, you earn money with Increase Your Likes Sending count or Quantity but Is only valid for active members. If someone invited stop using or Deactivate members will automatically decrease from credits and Your Like send Quantity decrease.

    -

    Its Simple, Fast, Easy to Use and best quality platform so This Website Popular Worldwide. and we always updated with latest API and Give better Service from other auto liker. Per Day Use Hug of Users From 200+ Country, Mostly Indian User, and All Are Real User.

    -

    The most important thiing while buying facebook page likes is you need to verify the source & autheticity of the website because many sites claimsto deliver Pages Likes but afterr taking order they are not capable to deliver it.

    -

    It is sometimes not just about post likes but also Facebook status likes as nowadays these time-limited kinds of stuff are also giving a great mileage to brands and businesses. Gaining Facebook likes on your posts goes on to show how influential a person or business you are, and that particular thing can actually take you a long way. If you want Facebook likes, buy cheap and real likes for your Facebook posts by visiting Fbpostlikes.com. Once you gain Facebook post likes from Fbpostlikes.com, you will consistently look to buy from this portal only. It is a piece of very magical advice to buy Facebook post likes as it can help your Facebook post to grow and get viral; along with that, it can create a good space for you in the world of Facebook and social media as a whole.

    -

    When you are developing a Facebook post like a Facebook photo, Facebook video, or just another Facebook write-up, you are just baking a great cake, but it must need to reach out to the ones who love such tasty cakes. By buying Facebook post likes, you are ensuring that it reaches your audience. Facebook post likes are a casual affinity towards your Facebook page or profile, and it shows that a person has an interest in your work or business most of the time. Facebook page likes and post likes play a very vital role in the growth of your profile or page. Usually, that is why smart people never hesitate to buy Facebook page likes or buy Facebook post likes from reliable sites like Fbpostlikes.com.

    -

    -

    If you are looking to buy Facebook page likes or buy Facebook post likes, never hesitate to look out for sites like Fbpostlikes. Fbpostlikes.com is quite popular for Facebook website likes, Facebook page likes, and mostly Facebook post likes. The experts working in the team of this portal understand the requirements of the customers when they are looking to buy likes for Facebook posts, in particular buy likes for Facebook photos and Facebook videos, and give the customers exactly the thing they desire. Buy Facebook likes cheap for your posts, including the photos and videos from this site, and you will never feel a bit disappointed. Just buy Facebook likes on a post from Fbpostlikes.com, and it will make you feel wonderful!

    -

    Are you wondering how to get likes on Facebook? Well, there are many ways, they will say, but you need to be sure what way exactly you want! You can go organic, or maybe inorganic, or maybe just buy real Facebook likes from portals like Fbpostlikes.com that are genuine, and you can trust them with all your money!

    -

    Organically growing is still the way many prefer to save their bucks. It is a very slow process, and in this world where time is valuable, it can be said to be a very outdated method. You can check out Facebook ads to get Facebook page likes or post likes in a very quick manner. Setting up Facebook ads is a skill, and if you are not getting paid Facebook likes at a cost you desire, then you can look to buy Facebook likes cheaply by looking for sites like Fbpostlikes.com. It has been there in business for a very long time, and the customers who have once used its service are regularly coming back to use its services.

    -

    If you are looking to buy real Facebook likes as you are looking to save time and money, then you have made the right decision by visiting Fbpostlikes.com, and after coming here, you do not need to think about how to get likes on Facebook at all because it becomes the headache of this portal. It takes care that you gain high-quality and real Facebook likes of the niche and geographical location you exactly need. This particular thing makes this portal the best one in the market as of now, without any doubt.

    -

    If you trust the process of technology and its usage, then you must meet the team members of Fbpostlikes.com, which use high-end technology, so that we can get real Facebook page likes and post likes from them very easily if you are looking for Facebook page likes and post likes then you never need to look beyond this highly trusted portal that has been serving the customers for years. With the number of reoccurring customers coming to this portal, you can always be confident that this portal is all about quality Facebook page likes and post likes and nothing else.

    -

    Getting Facebook likes from pages is very simple. Just ask any Facebook page admin or editor to share your Facebook page or post, and if its audience like your content, they end up liking that post or page quite easily. If you cannot afford paid Facebook likes, then you can look to gain Facebook likes from pages. It is a very slow process but usually costs you not much. If you want cheap Facebook likes rather than getting Facebook likes from pages, you can also visit trusted sites like Fbpostlikes.com, which is one of the rare portals that provide real Facebook page likes and post likes.

    -

    Buying Facebook likes is very easy; it does not matter if you are buying Facebook page likes or post likes. Just visit popular sites like Fbpostlikes.com and check the offers they have. Choose the right option for you and get real Facebook likes in no time. It is not rocket science at all because Fbpostlikes.com do not look to complicate the process of buying Facebook likes for its customers at all. If you still have confusion, then you can seek support from the customer support team of this site. You do not need to panic thinking how to buy Facebook likes at all.

    -

    RajeLiker is the toppest website in the market which helps you facebook, YouTube and Instagram users to get more likes with reaction on your latest posts. It helps you to get more reaction and comments on your photos and stories. If you are up the page on facebook, then the better performance of your page depends on likes there on the pages. If you have page blank, then you are good, if you need someone to get this work done for you something different. Auto Free Liker is the one who does it best for you.

    -

    RajeLiker is the one different way that you can post in FB and IG in groups, pages or friends given you likes on your Timeline Script. This is the most popular website for a job to post everywhere and it is saving your time. Auto Free Liker that does not take minutes. So try this amazing Auto Liker App with fun on facebook and Instagram with the help of Raje Liker.

    -

    Facebook Auto Liker may be a free tool that will allow you to submit your facebook videos and photos on Facebook Timeline Script, users can be given likes and comments. If you can add your website web pages on facebook Timeline liker to be ranked high through the usage of Auto Liker App on your Blog post on Auto Follow.

    -

    Free FB Auto Likes is implemented which is uniquely designed for Facebook Auto Liker lovers. RajeLiker site helps you to give many parts of Auto liker with Autolike script and comments on your post like pictures, contents and status etc. We will also provide you assistance in building followers and auto group posting with no charge.

    -

    Yes, here is an Auto Liker app that can easily make posts on social media automatically - RajeLiker. You can use the Free IG Auto Likes tool to maintain content directly to the Photo-sharing app easily.

    -

    RajeLiker is an all-in-one tool that's very useful for our autolike script. It makes posts indirectly on social media platforms, you can use this tool to monitor your page and post analytics. Have you checked the engagements and many other important posts concerning your postures or status to know how well they are going well.

    -

    Now, Social Media platforms are advanced and you can react normally to your post, not only likes or comments. There are different reactions to our photos, videos and contents like Smile, Heart, Anger and sadness. Anyone can react to your posts in bulk by using our help. You don't need to have your post full of actions. We also provide auto Liker App, Auto Follow Script and Instant Likes Panel. Now you have filled your Auto Liker or Timeline Liker.

    -

    Facebook is a growing social networking site where most people are connected with each other. Facebook provides you a best platform to interact or communicate with your friends, family or colleagues and as well as business connections. Use facebook auto liker for your growing business, you can make a list of facebook auto liker apps.

    -

    Facebook accounts tell everyone about your education or your photos or your friends list. In facebook accounts you should keep your personal information correctly. If you want to be famous, you need to post daily with a hashtag on your page then get thousands of billions likes, comments to attract followers. It will help you to grow your business by promoting the products and services with images or hashtags.

    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/cihyFjudo/fairness-paper-search/Free Download Swords and Sandals 3 Trainer The Ultimate Cheat Engine for the Game.md b/spaces/cihyFjudo/fairness-paper-search/Free Download Swords and Sandals 3 Trainer The Ultimate Cheat Engine for the Game.md deleted file mode 100644 index f0d861e9dbbf327fbababddcacfd2c37e5702e70..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Free Download Swords and Sandals 3 Trainer The Ultimate Cheat Engine for the Game.md +++ /dev/null @@ -1,5 +0,0 @@ - -

    If youre talking about swords and sandals 3 then you need to goto the little fat boy. You seehim on the top of the tower. He isjust on top of the Guitarists. You will need enough money to buy aspell. Then you go to your inventory click on your spellbook. Dragthe square card on one of the blank sqaures then voila ready tobattle. But in order for it to work you will also need enoughmagica or it wont work it will just stay blanc when you fight.

    -

    swords and sandals 3 trainer free download


    Download File https://tinurli.com/2uwjaO



    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/clement13430/lab1_iris/app.py b/spaces/clement13430/lab1_iris/app.py deleted file mode 100644 index 09215bf40a1b2cad6fa1171de74463d289bf9f57..0000000000000000000000000000000000000000 --- a/spaces/clement13430/lab1_iris/app.py +++ /dev/null @@ -1,47 +0,0 @@ -import gradio as gr -import numpy as np -from PIL import Image -import requests - -import hopsworks -import joblib - -project = hopsworks.login() -fs = project.get_feature_store() - - -mr = project.get_model_registry() -model = mr.get_model("iris_modal", version=1) -model_dir = model.download() -model = joblib.load(model_dir + "/iris_model.pkl") - - -def iris(sepal_length, sepal_width, petal_length, petal_width): - input_list = [] - input_list.append(sepal_length) - input_list.append(sepal_width) - input_list.append(petal_length) - input_list.append(petal_width) - # 'res' is a list of predictions returned as the label. - res = model.predict(np.asarray(input_list).reshape(1, -1)) - # We add '[0]' to the result of the transformed 'res', because 'res' is a list, and we only want - # the first element. - flower_url = "https://raw.githubusercontent.com/featurestoreorg/serverless-ml-course/main/src/01-module/assets/" + res[0] + ".png" - img = Image.open(requests.get(flower_url, stream=True).raw) - return img - -demo = gr.Interface( - fn=iris, - title="Iris Flower Predictive Analytics", - description="Experiment with sepal/petal lengths/widths to predict which flower it is.", - allow_flagging="never", - inputs=[ - gr.inputs.Number(default=1.0, label="sepal length (cm)"), - gr.inputs.Number(default=1.0, label="sepal width (cm)"), - gr.inputs.Number(default=1.0, label="petal length (cm)"), - gr.inputs.Number(default=1.0, label="petal width (cm)"), - ], - outputs=gr.Image(type="pil")) - -demo.launch() - diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/Makefile b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/Makefile deleted file mode 100644 index b0971ce833e3df4e2291d3ddca61e8abce904aca..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/Makefile +++ /dev/null @@ -1,1377 +0,0 @@ -NAME = avcodec -DESC = FFmpeg codec library - -HEADERS = ac3_parser.h \ - adts_parser.h \ - avcodec.h \ - avdct.h \ - avfft.h \ - bsf.h \ - codec.h \ - codec_desc.h \ - codec_id.h \ - codec_par.h \ - d3d11va.h \ - defs.h \ - dirac.h \ - dv_profile.h \ - dxva2.h \ - jni.h \ - mediacodec.h \ - packet.h \ - qsv.h \ - vdpau.h \ - version.h \ - version_major.h \ - videotoolbox.h \ - vorbis_parser.h \ - xvmc.h \ - -OBJS = ac3_parser.o \ - adts_parser.o \ - allcodecs.o \ - avcodec.o \ - avdct.o \ - avpacket.o \ - bitstream.o \ - bitstream_filters.o \ - bsf.o \ - codec_desc.o \ - codec_par.o \ - d3d11va.o \ - decode.o \ - dirac.o \ - dv_profile.o \ - encode.o \ - get_buffer.o \ - imgconvert.o \ - jni.o \ - mathtables.o \ - mediacodec.o \ - mpeg12framerate.o \ - options.o \ - parser.o \ - parsers.o \ - profiles.o \ - qsv_api.o \ - raw.o \ - utils.o \ - version.o \ - vlc.o \ - vorbis_parser.o \ - xiph.o \ - -# subsystems -OBJS-$(CONFIG_AANDCTTABLES) += aandcttab.o -OBJS-$(CONFIG_AC3DSP) += ac3dsp.o ac3.o ac3tab.o -OBJS-$(CONFIG_ADTS_HEADER) += adts_header.o mpeg4audio_sample_rates.o -OBJS-$(CONFIG_AMF) += amfenc.o -OBJS-$(CONFIG_AUDIO_FRAME_QUEUE) += audio_frame_queue.o -OBJS-$(CONFIG_ATSC_A53) += atsc_a53.o -OBJS-$(CONFIG_AUDIODSP) += audiodsp.o -OBJS-$(CONFIG_BLOCKDSP) += blockdsp.o -OBJS-$(CONFIG_BSWAPDSP) += bswapdsp.o -OBJS-$(CONFIG_CABAC) += cabac.o -OBJS-$(CONFIG_CBS) += cbs.o cbs_bsf.o -OBJS-$(CONFIG_CBS_AV1) += cbs_av1.o -OBJS-$(CONFIG_CBS_H264) += cbs_h2645.o cbs_sei.o h2645_parse.o -OBJS-$(CONFIG_CBS_H265) += cbs_h2645.o cbs_sei.o h2645_parse.o -OBJS-$(CONFIG_CBS_JPEG) += cbs_jpeg.o -OBJS-$(CONFIG_CBS_MPEG2) += cbs_mpeg2.o -OBJS-$(CONFIG_CBS_VP9) += cbs_vp9.o -OBJS-$(CONFIG_CRYSTALHD) += crystalhd.o -OBJS-$(CONFIG_DCT) += dct.o dct32_fixed.o dct32_float.o -OBJS-$(CONFIG_DEFLATE_WRAPPER) += zlib_wrapper.o -OBJS-$(CONFIG_DOVI_RPU) += dovi_rpu.o -OBJS-$(CONFIG_ERROR_RESILIENCE) += error_resilience.o -OBJS-$(CONFIG_EXIF) += exif.o tiff_common.o -OBJS-$(CONFIG_FAANDCT) += faandct.o -OBJS-$(CONFIG_FAANIDCT) += faanidct.o -OBJS-$(CONFIG_FDCTDSP) += fdctdsp.o jfdctfst.o jfdctint.o -FFT-OBJS-$(CONFIG_HARDCODED_TABLES) += cos_tables.o -OBJS-$(CONFIG_FFT) += avfft.o fft_float.o fft_fixed_32.o \ - fft_init_table.o $(FFT-OBJS-yes) -OBJS-$(CONFIG_FMTCONVERT) += fmtconvert.o -OBJS-$(CONFIG_GOLOMB) += golomb.o -OBJS-$(CONFIG_H263DSP) += h263dsp.o -OBJS-$(CONFIG_H264CHROMA) += h264chroma.o -OBJS-$(CONFIG_H264DSP) += h264dsp.o h264idct.o -OBJS-$(CONFIG_H264PARSE) += h264_parse.o h264_ps.o h2645data.o \ - h2645_parse.o h2645_vui.o -OBJS-$(CONFIG_H264PRED) += h264pred.o -OBJS-$(CONFIG_H264QPEL) += h264qpel.o -OBJS-$(CONFIG_H264_SEI) += h264_sei.o h2645_sei.o -OBJS-$(CONFIG_HEVCPARSE) += hevc_parse.o hevc_ps.o hevc_data.o \ - h2645data.o h2645_parse.o h2645_vui.o -OBJS-$(CONFIG_HEVC_SEI) += hevc_sei.o h2645_sei.o \ - dynamic_hdr_vivid.o -OBJS-$(CONFIG_HPELDSP) += hpeldsp.o -OBJS-$(CONFIG_HUFFMAN) += huffman.o -OBJS-$(CONFIG_HUFFYUVDSP) += huffyuvdsp.o -OBJS-$(CONFIG_HUFFYUVENCDSP) += huffyuvencdsp.o -OBJS-$(CONFIG_IDCTDSP) += idctdsp.o simple_idct.o jrevdct.o -OBJS-$(CONFIG_IIRFILTER) += iirfilter.o -OBJS-$(CONFIG_INFLATE_WRAPPER) += zlib_wrapper.o -OBJS-$(CONFIG_INTRAX8) += intrax8.o intrax8dsp.o msmpeg4data.o -OBJS-$(CONFIG_IVIDSP) += ivi_dsp.o -OBJS-$(CONFIG_JNI) += ffjni.o jni.o -OBJS-$(CONFIG_JPEGTABLES) += jpegtables.o -OBJS-$(CONFIG_LCMS2) += fflcms2.o -OBJS-$(CONFIG_LLAUDDSP) += lossless_audiodsp.o -OBJS-$(CONFIG_LLVIDDSP) += lossless_videodsp.o -OBJS-$(CONFIG_LLVIDENCDSP) += lossless_videoencdsp.o -OBJS-$(CONFIG_LPC) += lpc.o -OBJS-$(CONFIG_LSP) += lsp.o -OBJS-$(CONFIG_LZF) += lzf.o -OBJS-$(CONFIG_MDCT) += mdct_float.o mdct_fixed_32.o -OBJS-$(CONFIG_ME_CMP) += me_cmp.o -OBJS-$(CONFIG_MEDIACODEC) += mediacodecdec_common.o mediacodec_surface.o mediacodec_wrapper.o mediacodec_sw_buffer.o -OBJS-$(CONFIG_MPEG_ER) += mpeg_er.o -OBJS-$(CONFIG_MPEGAUDIO) += mpegaudio.o mpegaudiodec_common.o \ - mpegaudiodata.o -OBJS-$(CONFIG_MPEGAUDIODSP) += mpegaudiodsp.o \ - mpegaudiodsp_data.o \ - mpegaudiodsp_fixed.o \ - mpegaudiodsp_float.o -OBJS-$(CONFIG_MPEGAUDIOHEADER) += mpegaudiodecheader.o mpegaudiotabs.o -OBJS-$(CONFIG_MPEG4AUDIO) += mpeg4audio.o mpeg4audio_sample_rates.o -OBJS-$(CONFIG_MPEGVIDEO) += mpegvideo.o rl.o \ - mpegvideo_motion.o \ - mpegvideodata.o mpegpicture.o \ - to_upper4.o -OBJS-$(CONFIG_MPEGVIDEODEC) += mpegvideo_dec.o mpegutils.o -OBJS-$(CONFIG_MPEGVIDEOENC) += mpegvideo_enc.o mpeg12data.o \ - motion_est.o ratecontrol.o \ - mpegvideoencdsp.o -OBJS-$(CONFIG_MSMPEG4DEC) += msmpeg4dec.o msmpeg4.o msmpeg4data.o \ - msmpeg4_vc1_data.o -OBJS-$(CONFIG_MSMPEG4ENC) += msmpeg4enc.o msmpeg4.o msmpeg4data.o \ - msmpeg4_vc1_data.o -OBJS-$(CONFIG_MSS34DSP) += mss34dsp.o jpegquanttables.o -OBJS-$(CONFIG_PIXBLOCKDSP) += pixblockdsp.o -OBJS-$(CONFIG_QPELDSP) += qpeldsp.o -OBJS-$(CONFIG_QSV) += qsv.o -OBJS-$(CONFIG_QSVDEC) += qsvdec.o -OBJS-$(CONFIG_QSVENC) += qsvenc.o -OBJS-$(CONFIG_RANGECODER) += rangecoder.o -OBJS-$(CONFIG_RDFT) += rdft.o -OBJS-$(CONFIG_RV34DSP) += rv34dsp.o -OBJS-$(CONFIG_SINEWIN) += sinewin.o -OBJS-$(CONFIG_SNAPPY) += snappy.o -OBJS-$(CONFIG_STARTCODE) += startcode.o -OBJS-$(CONFIG_TEXTUREDSP) += texturedsp.o -OBJS-$(CONFIG_TEXTUREDSPENC) += texturedspenc.o -OBJS-$(CONFIG_TPELDSP) += tpeldsp.o -OBJS-$(CONFIG_VAAPI_ENCODE) += vaapi_encode.o -OBJS-$(CONFIG_AV1_AMF_ENCODER) += amfenc_av1.o -OBJS-$(CONFIG_VC1DSP) += vc1dsp.o -OBJS-$(CONFIG_VIDEODSP) += videodsp.o -OBJS-$(CONFIG_VP3DSP) += vp3dsp.o -OBJS-$(CONFIG_VP56DSP) += vp56dsp.o -OBJS-$(CONFIG_VP8DSP) += vp8dsp.o -OBJS-$(CONFIG_V4L2_M2M) += v4l2_m2m.o v4l2_context.o v4l2_buffers.o v4l2_fmt.o -OBJS-$(CONFIG_WMA_FREQS) += wma_freqs.o -OBJS-$(CONFIG_WMV2DSP) += wmv2dsp.o - -# decoders/encoders -OBJS-$(CONFIG_ZERO12V_DECODER) += 012v.o -OBJS-$(CONFIG_A64MULTI_ENCODER) += a64multienc.o elbg.o -OBJS-$(CONFIG_A64MULTI5_ENCODER) += a64multienc.o elbg.o -OBJS-$(CONFIG_AAC_DECODER) += aacdec.o aactab.o aacsbr.o aacps_common.o aacps_float.o \ - kbdwin.o \ - sbrdsp.o aacpsdsp_float.o cbrt_data.o -OBJS-$(CONFIG_AAC_FIXED_DECODER) += aacdec_fixed.o aactab.o aacsbr_fixed.o aacps_common.o aacps_fixed.o \ - kbdwin.o \ - sbrdsp_fixed.o aacpsdsp_fixed.o cbrt_data_fixed.o -OBJS-$(CONFIG_AAC_ENCODER) += aacenc.o aaccoder.o aacenctab.o \ - aacpsy.o aactab.o \ - aacenc_is.o \ - aacenc_tns.o \ - aacenc_ltp.o \ - aacenc_pred.o \ - psymodel.o kbdwin.o \ - mpeg4audio_sample_rates.o -OBJS-$(CONFIG_AAC_MF_ENCODER) += mfenc.o mf_utils.o -OBJS-$(CONFIG_AASC_DECODER) += aasc.o msrledec.o -OBJS-$(CONFIG_AC3_DECODER) += ac3dec_float.o ac3dec_data.o ac3.o \ - kbdwin.o ac3tab.o ac3_channel_layout_tab.o -OBJS-$(CONFIG_AC3_FIXED_DECODER) += ac3dec_fixed.o ac3dec_data.o ac3.o \ - kbdwin.o ac3tab.o ac3_channel_layout_tab.o -OBJS-$(CONFIG_AC3_ENCODER) += ac3enc_float.o ac3enc.o ac3tab.o \ - ac3.o kbdwin.o -OBJS-$(CONFIG_AC3_FIXED_ENCODER) += ac3enc_fixed.o ac3enc.o ac3tab.o ac3.o kbdwin.o -OBJS-$(CONFIG_AC3_MF_ENCODER) += mfenc.o mf_utils.o -OBJS-$(CONFIG_ACELP_KELVIN_DECODER) += g729dec.o lsp.o celp_math.o celp_filters.o acelp_filters.o acelp_pitch_delay.o acelp_vectors.o g729postfilter.o -OBJS-$(CONFIG_AGM_DECODER) += agm.o jpegquanttables.o -OBJS-$(CONFIG_AIC_DECODER) += aic.o -OBJS-$(CONFIG_ALAC_DECODER) += alac.o alac_data.o alacdsp.o -OBJS-$(CONFIG_ALAC_ENCODER) += alacenc.o alac_data.o -OBJS-$(CONFIG_ALIAS_PIX_DECODER) += aliaspixdec.o -OBJS-$(CONFIG_ALIAS_PIX_ENCODER) += aliaspixenc.o -OBJS-$(CONFIG_ALS_DECODER) += alsdec.o bgmc.o mlz.o -OBJS-$(CONFIG_AMRNB_DECODER) += amrnbdec.o celp_filters.o \ - celp_math.o acelp_filters.o \ - acelp_vectors.o \ - acelp_pitch_delay.o -OBJS-$(CONFIG_AMRWB_DECODER) += amrwbdec.o celp_filters.o \ - celp_math.o acelp_filters.o \ - acelp_vectors.o \ - acelp_pitch_delay.o -OBJS-$(CONFIG_AMV_ENCODER) += mjpegenc.o mjpegenc_common.o -OBJS-$(CONFIG_ANM_DECODER) += anm.o -OBJS-$(CONFIG_ANULL_DECODER) += null.o -OBJS-$(CONFIG_ANULL_ENCODER) += null.o -OBJS-$(CONFIG_ANSI_DECODER) += ansi.o cga_data.o -OBJS-$(CONFIG_APAC_DECODER) += apac.o -OBJS-$(CONFIG_APE_DECODER) += apedec.o -OBJS-$(CONFIG_APTX_DECODER) += aptxdec.o aptx.o -OBJS-$(CONFIG_APTX_ENCODER) += aptxenc.o aptx.o -OBJS-$(CONFIG_APTX_HD_DECODER) += aptxdec.o aptx.o -OBJS-$(CONFIG_APTX_HD_ENCODER) += aptxenc.o aptx.o -OBJS-$(CONFIG_APNG_DECODER) += png.o pngdec.o pngdsp.o -OBJS-$(CONFIG_APNG_ENCODER) += png.o pngenc.o -OBJS-$(CONFIG_ARBC_DECODER) += arbc.o -OBJS-$(CONFIG_ARGO_DECODER) += argo.o -OBJS-$(CONFIG_SSA_DECODER) += assdec.o ass.o -OBJS-$(CONFIG_SSA_ENCODER) += assenc.o ass.o -OBJS-$(CONFIG_ASS_DECODER) += assdec.o ass.o -OBJS-$(CONFIG_ASS_ENCODER) += assenc.o ass.o -OBJS-$(CONFIG_ASV1_DECODER) += asvdec.o asv.o mpeg12data.o -OBJS-$(CONFIG_ASV1_ENCODER) += asvenc.o asv.o mpeg12data.o -OBJS-$(CONFIG_ASV2_DECODER) += asvdec.o asv.o mpeg12data.o -OBJS-$(CONFIG_ASV2_ENCODER) += asvenc.o asv.o mpeg12data.o -OBJS-$(CONFIG_ATRAC1_DECODER) += atrac1.o atrac.o -OBJS-$(CONFIG_ATRAC3_DECODER) += atrac3.o atrac.o -OBJS-$(CONFIG_ATRAC3AL_DECODER) += atrac3.o atrac.o -OBJS-$(CONFIG_ATRAC3P_DECODER) += atrac3plusdec.o atrac3plus.o \ - atrac3plusdsp.o atrac.o -OBJS-$(CONFIG_ATRAC3PAL_DECODER) += atrac3plusdec.o atrac3plus.o \ - atrac3plusdsp.o atrac.o -OBJS-$(CONFIG_ATRAC9_DECODER) += atrac9dec.o -OBJS-$(CONFIG_AURA_DECODER) += cyuv.o -OBJS-$(CONFIG_AURA2_DECODER) += aura.o -OBJS-$(CONFIG_AV1_DECODER) += av1dec.o -OBJS-$(CONFIG_AV1_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_AV1_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_AV1_NVENC_ENCODER) += nvenc_av1.o nvenc.o -OBJS-$(CONFIG_AV1_QSV_ENCODER) += qsvenc_av1.o -OBJS-$(CONFIG_AVRN_DECODER) += avrndec.o -OBJS-$(CONFIG_AVRP_DECODER) += r210dec.o -OBJS-$(CONFIG_AVRP_ENCODER) += r210enc.o -OBJS-$(CONFIG_AVS_DECODER) += avs.o -OBJS-$(CONFIG_AVUI_DECODER) += avuidec.o -OBJS-$(CONFIG_AVUI_ENCODER) += avuienc.o -OBJS-$(CONFIG_AYUV_DECODER) += v408dec.o -OBJS-$(CONFIG_AYUV_ENCODER) += v408enc.o -OBJS-$(CONFIG_BETHSOFTVID_DECODER) += bethsoftvideo.o -OBJS-$(CONFIG_BFI_DECODER) += bfi.o -OBJS-$(CONFIG_BINK_DECODER) += bink.o binkdsp.o -OBJS-$(CONFIG_BINKAUDIO_DCT_DECODER) += binkaudio.o -OBJS-$(CONFIG_BINKAUDIO_RDFT_DECODER) += binkaudio.o -OBJS-$(CONFIG_BINTEXT_DECODER) += bintext.o cga_data.o -OBJS-$(CONFIG_BITPACKED_DECODER) += bitpacked_dec.o -OBJS-$(CONFIG_BITPACKED_ENCODER) += bitpacked_enc.o -OBJS-$(CONFIG_BMP_DECODER) += bmp.o msrledec.o -OBJS-$(CONFIG_BMP_ENCODER) += bmpenc.o -OBJS-$(CONFIG_BMV_AUDIO_DECODER) += bmvaudio.o -OBJS-$(CONFIG_BMV_VIDEO_DECODER) += bmvvideo.o -OBJS-$(CONFIG_BONK_DECODER) += bonk.o -OBJS-$(CONFIG_BRENDER_PIX_DECODER) += brenderpix.o -OBJS-$(CONFIG_C93_DECODER) += c93.o -OBJS-$(CONFIG_CAVS_DECODER) += cavs.o cavsdec.o cavsdsp.o \ - cavsdata.o -OBJS-$(CONFIG_CBD2_DECODER) += dpcm.o -OBJS-$(CONFIG_CCAPTION_DECODER) += ccaption_dec.o ass.o -OBJS-$(CONFIG_CDGRAPHICS_DECODER) += cdgraphics.o -OBJS-$(CONFIG_CDTOONS_DECODER) += cdtoons.o -OBJS-$(CONFIG_CDXL_DECODER) += cdxl.o -OBJS-$(CONFIG_CFHD_DECODER) += cfhd.o cfhddata.o cfhddsp.o -OBJS-$(CONFIG_CFHD_ENCODER) += cfhdenc.o cfhddata.o cfhdencdsp.o -OBJS-$(CONFIG_CINEPAK_DECODER) += cinepak.o -OBJS-$(CONFIG_CINEPAK_ENCODER) += cinepakenc.o elbg.o -OBJS-$(CONFIG_CLEARVIDEO_DECODER) += clearvideo.o -OBJS-$(CONFIG_CLJR_DECODER) += cljrdec.o -OBJS-$(CONFIG_CLJR_ENCODER) += cljrenc.o -OBJS-$(CONFIG_CLLC_DECODER) += cllc.o canopus.o -OBJS-$(CONFIG_COMFORTNOISE_DECODER) += cngdec.o celp_filters.o -OBJS-$(CONFIG_COMFORTNOISE_ENCODER) += cngenc.o -OBJS-$(CONFIG_COOK_DECODER) += cook.o -OBJS-$(CONFIG_CPIA_DECODER) += cpia.o -OBJS-$(CONFIG_CRI_DECODER) += cri.o -OBJS-$(CONFIG_CSCD_DECODER) += cscd.o -OBJS-$(CONFIG_CYUV_DECODER) += cyuv.o -OBJS-$(CONFIG_DCA_DECODER) += dcadec.o dca.o dcadata.o dcahuff.o \ - dca_core.o dca_exss.o dca_xll.o dca_lbr.o \ - dcadsp.o dcadct.o dca_sample_rate_tab.o \ - synth_filter.o -OBJS-$(CONFIG_DCA_ENCODER) += dcaenc.o dcadata.o dcahuff.o \ - dcaadpcm.o -OBJS-$(CONFIG_DDS_DECODER) += dds.o -OBJS-$(CONFIG_DERF_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_DIRAC_DECODER) += diracdec.o dirac.o diracdsp.o diractab.o \ - dirac_arith.o dirac_dwt.o dirac_vlc.o -OBJS-$(CONFIG_DFA_DECODER) += dfa.o -OBJS-$(CONFIG_DFPWM_DECODER) += dfpwmdec.o -OBJS-$(CONFIG_DFPWM_ENCODER) += dfpwmenc.o -OBJS-$(CONFIG_DNXHD_DECODER) += dnxhddec.o dnxhddata.o -OBJS-$(CONFIG_DNXHD_ENCODER) += dnxhdenc.o dnxhddata.o -OBJS-$(CONFIG_DOLBY_E_DECODER) += dolby_e.o dolby_e_parse.o kbdwin.o -OBJS-$(CONFIG_DPX_DECODER) += dpx.o -OBJS-$(CONFIG_DPX_ENCODER) += dpxenc.o -OBJS-$(CONFIG_DSD_LSBF_DECODER) += dsddec.o dsd.o -OBJS-$(CONFIG_DSD_MSBF_DECODER) += dsddec.o dsd.o -OBJS-$(CONFIG_DSD_LSBF_PLANAR_DECODER) += dsddec.o dsd.o -OBJS-$(CONFIG_DSD_MSBF_PLANAR_DECODER) += dsddec.o dsd.o -OBJS-$(CONFIG_DSICINAUDIO_DECODER) += dsicinaudio.o -OBJS-$(CONFIG_DSICINVIDEO_DECODER) += dsicinvideo.o -OBJS-$(CONFIG_DSS_SP_DECODER) += dss_sp.o -OBJS-$(CONFIG_DST_DECODER) += dstdec.o dsd.o -OBJS-$(CONFIG_DVBSUB_DECODER) += dvbsubdec.o -OBJS-$(CONFIG_DVBSUB_ENCODER) += dvbsubenc.o -OBJS-$(CONFIG_DVDSUB_DECODER) += dvdsubdec.o dvdsub.o -OBJS-$(CONFIG_DVDSUB_ENCODER) += dvdsubenc.o dvdsub.o -OBJS-$(CONFIG_DVAUDIO_DECODER) += dvaudiodec.o -OBJS-$(CONFIG_DVVIDEO_DECODER) += dvdec.o dv.o dvdata.o -OBJS-$(CONFIG_DVVIDEO_ENCODER) += dvenc.o dv.o dvdata.o -OBJS-$(CONFIG_DXA_DECODER) += dxa.o -OBJS-$(CONFIG_DXTORY_DECODER) += dxtory.o -OBJS-$(CONFIG_DXV_DECODER) += dxv.o -OBJS-$(CONFIG_EAC3_DECODER) += eac3_data.o -OBJS-$(CONFIG_EAC3_ENCODER) += eac3enc.o eac3_data.o -OBJS-$(CONFIG_EACMV_DECODER) += eacmv.o -OBJS-$(CONFIG_EAMAD_DECODER) += eamad.o eaidct.o mpeg12.o \ - mpeg12data.o -OBJS-$(CONFIG_EATGQ_DECODER) += eatgq.o eaidct.o -OBJS-$(CONFIG_EATGV_DECODER) += eatgv.o -OBJS-$(CONFIG_EATQI_DECODER) += eatqi.o eaidct.o mpeg12.o \ - mpeg12data.o -OBJS-$(CONFIG_EIGHTBPS_DECODER) += 8bps.o -OBJS-$(CONFIG_EIGHTSVX_EXP_DECODER) += 8svx.o -OBJS-$(CONFIG_EIGHTSVX_FIB_DECODER) += 8svx.o -OBJS-$(CONFIG_ESCAPE124_DECODER) += escape124.o -OBJS-$(CONFIG_ESCAPE130_DECODER) += escape130.o -OBJS-$(CONFIG_EVRC_DECODER) += evrcdec.o acelp_vectors.o lsp.o -OBJS-$(CONFIG_EXR_DECODER) += exr.o exrdsp.o half2float.o -OBJS-$(CONFIG_EXR_ENCODER) += exrenc.o float2half.o -OBJS-$(CONFIG_FASTAUDIO_DECODER) += fastaudio.o -OBJS-$(CONFIG_FFV1_DECODER) += ffv1dec.o ffv1.o -OBJS-$(CONFIG_FFV1_ENCODER) += ffv1enc.o ffv1.o -OBJS-$(CONFIG_FFWAVESYNTH_DECODER) += ffwavesynth.o -OBJS-$(CONFIG_FIC_DECODER) += fic.o -OBJS-$(CONFIG_FITS_DECODER) += fitsdec.o fits.o -OBJS-$(CONFIG_FITS_ENCODER) += fitsenc.o -OBJS-$(CONFIG_FLAC_DECODER) += flacdec.o flacdata.o flacdsp.o flac.o -OBJS-$(CONFIG_FLAC_ENCODER) += flacenc.o flacdata.o flacencdsp.o -OBJS-$(CONFIG_FLASHSV_DECODER) += flashsv.o -OBJS-$(CONFIG_FLASHSV_ENCODER) += flashsvenc.o -OBJS-$(CONFIG_FLASHSV2_ENCODER) += flashsv2enc.o -OBJS-$(CONFIG_FLASHSV2_DECODER) += flashsv.o -OBJS-$(CONFIG_FLIC_DECODER) += flicvideo.o -OBJS-$(CONFIG_FLV_DECODER) += flvdec.o -OBJS-$(CONFIG_FLV_ENCODER) += flvenc.o -OBJS-$(CONFIG_FMVC_DECODER) += fmvc.o -OBJS-$(CONFIG_FOURXM_DECODER) += 4xm.o -OBJS-$(CONFIG_FRAPS_DECODER) += fraps.o -OBJS-$(CONFIG_FRWU_DECODER) += frwu.o -OBJS-$(CONFIG_FTR_DECODER) += ftr.o -OBJS-$(CONFIG_G2M_DECODER) += g2meet.o elsdec.o mjpegdec_common.o -OBJS-$(CONFIG_G723_1_DECODER) += g723_1dec.o g723_1.o \ - acelp_vectors.o celp_filters.o celp_math.o -OBJS-$(CONFIG_G723_1_ENCODER) += g723_1enc.o g723_1.o \ - acelp_vectors.o celp_filters.o celp_math.o -OBJS-$(CONFIG_G729_DECODER) += g729dec.o lsp.o celp_math.o celp_filters.o acelp_filters.o acelp_pitch_delay.o acelp_vectors.o g729postfilter.o -OBJS-$(CONFIG_GDV_DECODER) += gdv.o -OBJS-$(CONFIG_GEM_DECODER) += gemdec.o -OBJS-$(CONFIG_GIF_DECODER) += gifdec.o lzw.o -OBJS-$(CONFIG_GIF_ENCODER) += gif.o lzwenc.o -OBJS-$(CONFIG_GREMLIN_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_GSM_DECODER) += gsmdec.o gsmdec_data.o msgsmdec.o -OBJS-$(CONFIG_GSM_MS_DECODER) += gsmdec.o gsmdec_data.o msgsmdec.o -OBJS-$(CONFIG_H261_DECODER) += h261dec.o h261data.o h261.o -OBJS-$(CONFIG_H261_ENCODER) += h261enc.o h261data.o h261.o -OBJS-$(CONFIG_H263_DECODER) += h263dec.o h263.o ituh263dec.o \ - mpeg4video.o mpeg4videodec.o \ - h263data.o -OBJS-$(CONFIG_H263I_DECODER) += intelh263dec.o -OBJS-$(CONFIG_H263_ENCODER) += mpeg4video.o \ - h263.o ituh263enc.o h263data.o -OBJS-$(CONFIG_H263_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_H263_V4L2M2M_ENCODER) += v4l2_m2m_enc.o -OBJS-$(CONFIG_H264_DECODER) += h264dec.o h264_cabac.o h264_cavlc.o \ - h264_direct.o h264_loopfilter.o \ - h264_mb.o h264_picture.o \ - h264_refs.o \ - h264_slice.o h264data.o h274.o -OBJS-$(CONFIG_H264_AMF_ENCODER) += amfenc_h264.o -OBJS-$(CONFIG_H264_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_H264_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_H264_MEDIACODEC_ENCODER) += mediacodecenc.o -OBJS-$(CONFIG_H264_MF_ENCODER) += mfenc.o mf_utils.o -OBJS-$(CONFIG_H264_MMAL_DECODER) += mmaldec.o -OBJS-$(CONFIG_H264_NVENC_ENCODER) += nvenc_h264.o nvenc.o -OBJS-$(CONFIG_H264_OMX_ENCODER) += omx.o -OBJS-$(CONFIG_H264_QSV_DECODER) += qsvdec.o -OBJS-$(CONFIG_H264_QSV_ENCODER) += qsvenc_h264.o -OBJS-$(CONFIG_H264_RKMPP_DECODER) += rkmppdec.o -OBJS-$(CONFIG_H264_VAAPI_ENCODER) += vaapi_encode_h264.o h264_levels.o \ - h2645data.o -OBJS-$(CONFIG_H264_VIDEOTOOLBOX_ENCODER) += videotoolboxenc.o -OBJS-$(CONFIG_H264_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_H264_V4L2M2M_ENCODER) += v4l2_m2m_enc.o -OBJS-$(CONFIG_HAP_DECODER) += hapdec.o hap.o -OBJS-$(CONFIG_HAP_ENCODER) += hapenc.o hap.o -OBJS-$(CONFIG_HCA_DECODER) += hcadec.o -OBJS-$(CONFIG_HCOM_DECODER) += hcom.o -OBJS-$(CONFIG_HDR_DECODER) += hdrdec.o -OBJS-$(CONFIG_HDR_ENCODER) += hdrenc.o -OBJS-$(CONFIG_HEVC_DECODER) += hevcdec.o hevc_mvs.o \ - hevc_cabac.o hevc_refs.o hevcpred.o \ - hevcdsp.o hevc_filter.o hevc_data.o \ - h274.o -OBJS-$(CONFIG_HEVC_AMF_ENCODER) += amfenc_hevc.o -OBJS-$(CONFIG_HEVC_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_HEVC_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_HEVC_MEDIACODEC_ENCODER) += mediacodecenc.o -OBJS-$(CONFIG_HEVC_MF_ENCODER) += mfenc.o mf_utils.o -OBJS-$(CONFIG_HEVC_NVENC_ENCODER) += nvenc_hevc.o nvenc.o -OBJS-$(CONFIG_HEVC_QSV_DECODER) += qsvdec.o -OBJS-$(CONFIG_HEVC_QSV_ENCODER) += qsvenc_hevc.o hevc_ps_enc.o \ - hevc_data.o -OBJS-$(CONFIG_HEVC_RKMPP_DECODER) += rkmppdec.o -OBJS-$(CONFIG_HEVC_VAAPI_ENCODER) += vaapi_encode_h265.o h265_profile_level.o \ - h2645data.o -OBJS-$(CONFIG_HEVC_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_HEVC_V4L2M2M_ENCODER) += v4l2_m2m_enc.o -OBJS-$(CONFIG_HEVC_VIDEOTOOLBOX_ENCODER) += videotoolboxenc.o -OBJS-$(CONFIG_HNM4_VIDEO_DECODER) += hnm4video.o -OBJS-$(CONFIG_HQ_HQA_DECODER) += hq_hqa.o hq_hqadata.o hq_hqadsp.o \ - canopus.o -OBJS-$(CONFIG_HQX_DECODER) += hqx.o hqxvlc.o hqxdsp.o canopus.o -OBJS-$(CONFIG_HUFFYUV_DECODER) += huffyuv.o huffyuvdec.o -OBJS-$(CONFIG_HUFFYUV_ENCODER) += huffyuv.o huffyuvenc.o -OBJS-$(CONFIG_HYMT_DECODER) += huffyuv.o huffyuvdec.o -OBJS-$(CONFIG_IDCIN_DECODER) += idcinvideo.o -OBJS-$(CONFIG_IDF_DECODER) += bintext.o cga_data.o -OBJS-$(CONFIG_IFF_ILBM_DECODER) += iff.o -OBJS-$(CONFIG_ILBC_DECODER) += ilbcdec.o -OBJS-$(CONFIG_IMC_DECODER) += imc.o -OBJS-$(CONFIG_IMM4_DECODER) += imm4.o -OBJS-$(CONFIG_IMM5_DECODER) += imm5.o -OBJS-$(CONFIG_INDEO2_DECODER) += indeo2.o -OBJS-$(CONFIG_INDEO3_DECODER) += indeo3.o -OBJS-$(CONFIG_INDEO4_DECODER) += indeo4.o ivi.o -OBJS-$(CONFIG_INDEO5_DECODER) += indeo5.o ivi.o -OBJS-$(CONFIG_INTERPLAY_ACM_DECODER) += interplayacm.o -OBJS-$(CONFIG_INTERPLAY_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_INTERPLAY_VIDEO_DECODER) += interplayvideo.o -OBJS-$(CONFIG_IPU_DECODER) += mpeg12dec.o mpeg12.o mpeg12data.o -OBJS-$(CONFIG_JACOSUB_DECODER) += jacosubdec.o ass.o -OBJS-$(CONFIG_JPEG2000_ENCODER) += j2kenc.o mqcenc.o mqc.o jpeg2000.o \ - jpeg2000dwt.o -OBJS-$(CONFIG_JPEG2000_DECODER) += jpeg2000dec.o jpeg2000.o jpeg2000dsp.o \ - jpeg2000dwt.o mqcdec.o mqc.o jpeg2000htdec.o -OBJS-$(CONFIG_JPEGLS_DECODER) += jpeglsdec.o jpegls.o -OBJS-$(CONFIG_JPEGLS_ENCODER) += jpeglsenc.o jpegls.o -OBJS-$(CONFIG_JV_DECODER) += jvdec.o -OBJS-$(CONFIG_KGV1_DECODER) += kgv1dec.o -OBJS-$(CONFIG_KMVC_DECODER) += kmvc.o -OBJS-$(CONFIG_LAGARITH_DECODER) += lagarith.o lagarithrac.o -OBJS-$(CONFIG_LJPEG_ENCODER) += ljpegenc.o mjpegenc_common.o -OBJS-$(CONFIG_LOCO_DECODER) += loco.o -OBJS-$(CONFIG_LSCR_DECODER) += lscrdec.o png.o pngdec.o pngdsp.o -OBJS-$(CONFIG_M101_DECODER) += m101.o -OBJS-$(CONFIG_MACE3_DECODER) += mace.o -OBJS-$(CONFIG_MACE6_DECODER) += mace.o -OBJS-$(CONFIG_MAGICYUV_DECODER) += magicyuv.o -OBJS-$(CONFIG_MAGICYUV_ENCODER) += magicyuvenc.o -OBJS-$(CONFIG_MDEC_DECODER) += mdec.o mpeg12.o mpeg12data.o -OBJS-$(CONFIG_MEDIA100_DECODER) += mjpegbdec.o -OBJS-$(CONFIG_METASOUND_DECODER) += metasound.o twinvq.o -OBJS-$(CONFIG_MICRODVD_DECODER) += microdvddec.o ass.o -OBJS-$(CONFIG_MIMIC_DECODER) += mimic.o -OBJS-$(CONFIG_MISC4_DECODER) += misc4.o -OBJS-$(CONFIG_MJPEG_DECODER) += mjpegdec.o mjpegdec_common.o -OBJS-$(CONFIG_MJPEG_QSV_DECODER) += qsvdec.o -OBJS-$(CONFIG_MJPEG_ENCODER) += mjpegenc.o mjpegenc_common.o \ - mjpegenc_huffman.o -OBJS-$(CONFIG_MJPEGB_DECODER) += mjpegbdec.o -OBJS-$(CONFIG_MJPEG_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_MJPEG_QSV_ENCODER) += qsvenc_jpeg.o -OBJS-$(CONFIG_MJPEG_VAAPI_ENCODER) += vaapi_encode_mjpeg.o -OBJS-$(CONFIG_MLP_DECODER) += mlpdec.o mlpdsp.o -OBJS-$(CONFIG_MLP_ENCODER) += mlpenc.o mlp.o -OBJS-$(CONFIG_MMVIDEO_DECODER) += mmvideo.o -OBJS-$(CONFIG_MOBICLIP_DECODER) += mobiclip.o -OBJS-$(CONFIG_MOTIONPIXELS_DECODER) += motionpixels.o -OBJS-$(CONFIG_MOVTEXT_DECODER) += movtextdec.o ass.o -OBJS-$(CONFIG_MOVTEXT_ENCODER) += movtextenc.o ass_split.o -OBJS-$(CONFIG_MP1_DECODER) += mpegaudiodec_fixed.o -OBJS-$(CONFIG_MP1FLOAT_DECODER) += mpegaudiodec_float.o -OBJS-$(CONFIG_MP2_DECODER) += mpegaudiodec_fixed.o -OBJS-$(CONFIG_MP2_ENCODER) += mpegaudioenc_float.o mpegaudio.o \ - mpegaudiodata.o mpegaudiodsp_data.o \ - mpegaudiotabs.o -OBJS-$(CONFIG_MP2FIXED_ENCODER) += mpegaudioenc_fixed.o mpegaudio.o \ - mpegaudiodata.o mpegaudiodsp_data.o \ - mpegaudiotabs.o -OBJS-$(CONFIG_MP2FLOAT_DECODER) += mpegaudiodec_float.o -OBJS-$(CONFIG_MP3_DECODER) += mpegaudiodec_fixed.o -OBJS-$(CONFIG_MP3_MF_ENCODER) += mfenc.o mf_utils.o -OBJS-$(CONFIG_MP3ADU_DECODER) += mpegaudiodec_fixed.o -OBJS-$(CONFIG_MP3ADUFLOAT_DECODER) += mpegaudiodec_float.o -OBJS-$(CONFIG_MP3FLOAT_DECODER) += mpegaudiodec_float.o -OBJS-$(CONFIG_MP3ON4_DECODER) += mpegaudiodec_fixed.o -OBJS-$(CONFIG_MP3ON4FLOAT_DECODER) += mpegaudiodec_float.o -OBJS-$(CONFIG_MPC7_DECODER) += mpc7.o mpc.o -OBJS-$(CONFIG_MPC8_DECODER) += mpc8.o mpc.o -OBJS-$(CONFIG_MPEGVIDEO_DECODER) += mpeg12dec.o mpeg12.o mpeg12data.o -OBJS-$(CONFIG_MPEG1VIDEO_DECODER) += mpeg12dec.o mpeg12.o mpeg12data.o -OBJS-$(CONFIG_MPEG1VIDEO_ENCODER) += mpeg12enc.o mpeg12.o -OBJS-$(CONFIG_MPEG1_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_MPEG1_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_MPEG2_MMAL_DECODER) += mmaldec.o -OBJS-$(CONFIG_MPEG2_QSV_DECODER) += qsvdec.o -OBJS-$(CONFIG_MPEG2_QSV_ENCODER) += qsvenc_mpeg2.o -OBJS-$(CONFIG_MPEG2VIDEO_DECODER) += mpeg12dec.o mpeg12.o mpeg12data.o -OBJS-$(CONFIG_MPEG2VIDEO_ENCODER) += mpeg12enc.o mpeg12.o -OBJS-$(CONFIG_MPEG2_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_MPEG2_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_MPEG2_VAAPI_ENCODER) += vaapi_encode_mpeg2.o -OBJS-$(CONFIG_MPEG2_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_MPEG4_DECODER) += mpeg4videodsp.o xvididct.o -OBJS-$(CONFIG_MPEG4_ENCODER) += mpeg4videoenc.o -OBJS-$(CONFIG_MPEG4_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_MPEG4_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_MPEG4_MEDIACODEC_ENCODER) += mediacodecenc.o -OBJS-$(CONFIG_MPEG4_OMX_ENCODER) += omx.o -OBJS-$(CONFIG_MPEG4_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_MPEG4_V4L2M2M_ENCODER) += v4l2_m2m_enc.o -OBJS-$(CONFIG_MPL2_DECODER) += mpl2dec.o ass.o -OBJS-$(CONFIG_MSA1_DECODER) += mss3.o -OBJS-$(CONFIG_MSCC_DECODER) += mscc.o -OBJS-$(CONFIG_MSNSIREN_DECODER) += siren.o -OBJS-$(CONFIG_MSP2_DECODER) += msp2dec.o -OBJS-$(CONFIG_MSRLE_DECODER) += msrle.o msrledec.o -OBJS-$(CONFIG_MSS1_DECODER) += mss1.o mss12.o -OBJS-$(CONFIG_MSS2_DECODER) += mss2.o mss12.o mss2dsp.o wmv2data.o -OBJS-$(CONFIG_MSVIDEO1_DECODER) += msvideo1.o -OBJS-$(CONFIG_MSVIDEO1_ENCODER) += msvideo1enc.o elbg.o -OBJS-$(CONFIG_MSZH_DECODER) += lcldec.o -OBJS-$(CONFIG_MTS2_DECODER) += mss4.o -OBJS-$(CONFIG_MV30_DECODER) += mv30.o -OBJS-$(CONFIG_MVC1_DECODER) += mvcdec.o -OBJS-$(CONFIG_MVC2_DECODER) += mvcdec.o -OBJS-$(CONFIG_MVDV_DECODER) += midivid.o -OBJS-$(CONFIG_MVHA_DECODER) += mvha.o -OBJS-$(CONFIG_MWSC_DECODER) += mwsc.o -OBJS-$(CONFIG_MXPEG_DECODER) += mxpegdec.o -OBJS-$(CONFIG_NELLYMOSER_DECODER) += nellymoserdec.o nellymoser.o -OBJS-$(CONFIG_NELLYMOSER_ENCODER) += nellymoserenc.o nellymoser.o -OBJS-$(CONFIG_NOTCHLC_DECODER) += notchlc.o -OBJS-$(CONFIG_NUV_DECODER) += nuv.o rtjpeg.o jpegquanttables.o -OBJS-$(CONFIG_ON2AVC_DECODER) += on2avc.o on2avcdata.o -OBJS-$(CONFIG_OPUS_DECODER) += opusdec.o opusdec_celt.o opus_celt.o \ - opus_pvq.o opus_silk.o opustab.o vorbis_data.o \ - opusdsp.o opus_parse.o opus_rc.o -OBJS-$(CONFIG_OPUS_ENCODER) += opusenc.o opusenc_psy.o opus_celt.o \ - opus_pvq.o opus_rc.o opustab.o -OBJS-$(CONFIG_PAF_AUDIO_DECODER) += pafaudio.o -OBJS-$(CONFIG_PAF_VIDEO_DECODER) += pafvideo.o -OBJS-$(CONFIG_PAM_DECODER) += pnmdec.o pnm.o -OBJS-$(CONFIG_PAM_ENCODER) += pamenc.o -OBJS-$(CONFIG_PBM_DECODER) += pnmdec.o pnm.o -OBJS-$(CONFIG_PBM_ENCODER) += pnmenc.o -OBJS-$(CONFIG_PCX_DECODER) += pcx.o -OBJS-$(CONFIG_PCX_ENCODER) += pcxenc.o -OBJS-$(CONFIG_PDV_DECODER) += pdvdec.o -OBJS-$(CONFIG_PFM_DECODER) += pnmdec.o pnm.o -OBJS-$(CONFIG_PFM_ENCODER) += pnmenc.o -OBJS-$(CONFIG_PGM_DECODER) += pnmdec.o pnm.o -OBJS-$(CONFIG_PGM_ENCODER) += pnmenc.o -OBJS-$(CONFIG_PGMYUV_DECODER) += pnmdec.o pnm.o -OBJS-$(CONFIG_PGMYUV_ENCODER) += pnmenc.o -OBJS-$(CONFIG_PGSSUB_DECODER) += pgssubdec.o -OBJS-$(CONFIG_PGX_DECODER) += pgxdec.o -OBJS-$(CONFIG_PHM_DECODER) += pnmdec.o pnm.o half2float.o -OBJS-$(CONFIG_PHM_ENCODER) += pnmenc.o float2half.o -OBJS-$(CONFIG_PHOTOCD_DECODER) += photocd.o -OBJS-$(CONFIG_PICTOR_DECODER) += pictordec.o cga_data.o -OBJS-$(CONFIG_PIXLET_DECODER) += pixlet.o -OBJS-$(CONFIG_PJS_DECODER) += textdec.o ass.o -OBJS-$(CONFIG_PNG_DECODER) += png.o pngdec.o pngdsp.o -OBJS-$(CONFIG_PNG_ENCODER) += png.o pngenc.o -OBJS-$(CONFIG_PPM_DECODER) += pnmdec.o pnm.o -OBJS-$(CONFIG_PPM_ENCODER) += pnmenc.o -OBJS-$(CONFIG_PRORES_DECODER) += proresdec2.o proresdsp.o proresdata.o -OBJS-$(CONFIG_PRORES_ENCODER) += proresenc_anatoliy.o proresdata.o -OBJS-$(CONFIG_PRORES_AW_ENCODER) += proresenc_anatoliy.o proresdata.o -OBJS-$(CONFIG_PRORES_KS_ENCODER) += proresenc_kostya.o proresdata.o -OBJS-$(CONFIG_PRORES_VIDEOTOOLBOX_ENCODER) += videotoolboxenc.o -OBJS-$(CONFIG_PROSUMER_DECODER) += prosumer.o -OBJS-$(CONFIG_PSD_DECODER) += psd.o -OBJS-$(CONFIG_PTX_DECODER) += ptx.o -OBJS-$(CONFIG_QCELP_DECODER) += qcelpdec.o \ - celp_filters.o acelp_vectors.o \ - acelp_filters.o -OBJS-$(CONFIG_QDM2_DECODER) += qdm2.o -OBJS-$(CONFIG_QDMC_DECODER) += qdmc.o -OBJS-$(CONFIG_QDRAW_DECODER) += qdrw.o -OBJS-$(CONFIG_QOI_DECODER) += qoidec.o -OBJS-$(CONFIG_QOI_ENCODER) += qoienc.o -OBJS-$(CONFIG_QPEG_DECODER) += qpeg.o -OBJS-$(CONFIG_QTRLE_DECODER) += qtrle.o -OBJS-$(CONFIG_QTRLE_ENCODER) += qtrleenc.o -OBJS-$(CONFIG_R10K_DECODER) += r210dec.o -OBJS-$(CONFIG_R10K_ENCODER) += r210enc.o -OBJS-$(CONFIG_R210_DECODER) += r210dec.o -OBJS-$(CONFIG_R210_ENCODER) += r210enc.o -OBJS-$(CONFIG_RA_144_DECODER) += ra144dec.o ra144.o celp_filters.o -OBJS-$(CONFIG_RA_144_ENCODER) += ra144enc.o ra144.o celp_filters.o -OBJS-$(CONFIG_RA_288_DECODER) += ra288.o celp_filters.o -OBJS-$(CONFIG_RALF_DECODER) += ralf.o -OBJS-$(CONFIG_RASC_DECODER) += rasc.o -OBJS-$(CONFIG_RAWVIDEO_DECODER) += rawdec.o -OBJS-$(CONFIG_RAWVIDEO_ENCODER) += rawenc.o -OBJS-$(CONFIG_REALTEXT_DECODER) += realtextdec.o ass.o -OBJS-$(CONFIG_RKA_DECODER) += rka.o -OBJS-$(CONFIG_RL2_DECODER) += rl2.o -OBJS-$(CONFIG_ROQ_DECODER) += roqvideodec.o roqvideo.o -OBJS-$(CONFIG_ROQ_ENCODER) += roqvideoenc.o roqvideo.o elbg.o -OBJS-$(CONFIG_ROQ_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_ROQ_DPCM_ENCODER) += roqaudioenc.o -OBJS-$(CONFIG_RPZA_DECODER) += rpza.o -OBJS-$(CONFIG_RPZA_ENCODER) += rpzaenc.o -OBJS-$(CONFIG_RSCC_DECODER) += rscc.o -OBJS-$(CONFIG_RV10_DECODER) += rv10.o -OBJS-$(CONFIG_RV10_ENCODER) += rv10enc.o -OBJS-$(CONFIG_RV20_DECODER) += rv10.o -OBJS-$(CONFIG_RV20_ENCODER) += rv20enc.o -OBJS-$(CONFIG_RV30_DECODER) += rv30.o rv34.o rv30dsp.o -OBJS-$(CONFIG_RV40_DECODER) += rv40.o rv34.o rv40dsp.o -OBJS-$(CONFIG_SAMI_DECODER) += samidec.o ass.o htmlsubtitles.o -OBJS-$(CONFIG_S302M_DECODER) += s302m.o -OBJS-$(CONFIG_S302M_ENCODER) += s302menc.o -OBJS-$(CONFIG_SANM_DECODER) += sanm.o -OBJS-$(CONFIG_SCPR_DECODER) += scpr.o -OBJS-$(CONFIG_SCREENPRESSO_DECODER) += screenpresso.o -OBJS-$(CONFIG_SDX2_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_SGA_DECODER) += sga.o -OBJS-$(CONFIG_SGI_DECODER) += sgidec.o -OBJS-$(CONFIG_SGI_ENCODER) += sgienc.o rle.o -OBJS-$(CONFIG_SGIRLE_DECODER) += sgirledec.o -OBJS-$(CONFIG_SHEERVIDEO_DECODER) += sheervideo.o -OBJS-$(CONFIG_SHORTEN_DECODER) += shorten.o -OBJS-$(CONFIG_SIPR_DECODER) += sipr.o acelp_pitch_delay.o \ - celp_math.o acelp_vectors.o \ - acelp_filters.o celp_filters.o \ - sipr16k.o -OBJS-$(CONFIG_SIREN_DECODER) += siren.o -OBJS-$(CONFIG_SIMBIOSIS_IMX_DECODER) += imx.o -OBJS-$(CONFIG_SMACKAUD_DECODER) += smacker.o -OBJS-$(CONFIG_SMACKER_DECODER) += smacker.o -OBJS-$(CONFIG_SMC_DECODER) += smc.o -OBJS-$(CONFIG_SMC_ENCODER) += smcenc.o -OBJS-$(CONFIG_SNOW_DECODER) += snowdec.o snow.o snow_dwt.o -OBJS-$(CONFIG_SNOW_ENCODER) += snowenc.o snow.o snow_dwt.o \ - h263.o h263data.o ituh263enc.o -OBJS-$(CONFIG_SOL_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_SONIC_DECODER) += sonic.o -OBJS-$(CONFIG_SONIC_ENCODER) += sonic.o -OBJS-$(CONFIG_SONIC_LS_ENCODER) += sonic.o -OBJS-$(CONFIG_SPEEDHQ_DECODER) += speedhqdec.o speedhq.o mpeg12.o \ - mpeg12data.o -OBJS-$(CONFIG_SPEEDHQ_ENCODER) += speedhq.o mpeg12data.o mpeg12enc.o speedhqenc.o -OBJS-$(CONFIG_SPEEX_DECODER) += speexdec.o -OBJS-$(CONFIG_SP5X_DECODER) += sp5xdec.o -OBJS-$(CONFIG_SRGC_DECODER) += mscc.o -OBJS-$(CONFIG_SRT_DECODER) += srtdec.o ass.o htmlsubtitles.o -OBJS-$(CONFIG_SRT_ENCODER) += srtenc.o ass_split.o -OBJS-$(CONFIG_STL_DECODER) += textdec.o ass.o -OBJS-$(CONFIG_SUBRIP_DECODER) += srtdec.o ass.o htmlsubtitles.o -OBJS-$(CONFIG_SUBRIP_ENCODER) += srtenc.o ass_split.o -OBJS-$(CONFIG_SUBVIEWER1_DECODER) += textdec.o ass.o -OBJS-$(CONFIG_SUBVIEWER_DECODER) += subviewerdec.o ass.o -OBJS-$(CONFIG_SUNRAST_DECODER) += sunrast.o -OBJS-$(CONFIG_SUNRAST_ENCODER) += sunrastenc.o -OBJS-$(CONFIG_LIBRSVG_DECODER) += librsvgdec.o -OBJS-$(CONFIG_SBC_DECODER) += sbcdec.o sbcdec_data.o sbc.o -OBJS-$(CONFIG_SBC_ENCODER) += sbcenc.o sbc.o sbcdsp.o sbcdsp_data.o -OBJS-$(CONFIG_SVQ1_DECODER) += svq1dec.o svq1.o h263data.o -OBJS-$(CONFIG_SVQ1_ENCODER) += svq1enc.o svq1.o h263data.o \ - h263.o ituh263enc.o -OBJS-$(CONFIG_SVQ3_DECODER) += svq3.o mpegutils.o h264data.o -OBJS-$(CONFIG_TEXT_DECODER) += textdec.o ass.o -OBJS-$(CONFIG_TEXT_ENCODER) += srtenc.o ass_split.o -OBJS-$(CONFIG_TAK_DECODER) += takdec.o tak.o takdsp.o -OBJS-$(CONFIG_TARGA_DECODER) += targa.o -OBJS-$(CONFIG_TARGA_ENCODER) += targaenc.o rle.o -OBJS-$(CONFIG_TARGA_Y216_DECODER) += targa_y216dec.o -OBJS-$(CONFIG_TDSC_DECODER) += tdsc.o -OBJS-$(CONFIG_TIERTEXSEQVIDEO_DECODER) += tiertexseqv.o -OBJS-$(CONFIG_TIFF_DECODER) += tiff.o lzw.o faxcompr.o tiff_common.o -OBJS-$(CONFIG_TIFF_ENCODER) += tiffenc.o rle.o lzwenc.o -OBJS-$(CONFIG_TMV_DECODER) += tmv.o cga_data.o -OBJS-$(CONFIG_TRUEHD_DECODER) += mlpdec.o mlpdsp.o -OBJS-$(CONFIG_TRUEHD_ENCODER) += mlpenc.o mlp.o -OBJS-$(CONFIG_TRUEMOTION1_DECODER) += truemotion1.o -OBJS-$(CONFIG_TRUEMOTION2_DECODER) += truemotion2.o -OBJS-$(CONFIG_TRUEMOTION2RT_DECODER) += truemotion2rt.o -OBJS-$(CONFIG_TRUESPEECH_DECODER) += truespeech.o -OBJS-$(CONFIG_TSCC_DECODER) += tscc.o msrledec.o -OBJS-$(CONFIG_TSCC2_DECODER) += tscc2.o -OBJS-$(CONFIG_TTA_DECODER) += tta.o ttadata.o ttadsp.o -OBJS-$(CONFIG_TTA_ENCODER) += ttaenc.o ttaencdsp.o ttadata.o -OBJS-$(CONFIG_TTML_ENCODER) += ttmlenc.o ass_split.o -OBJS-$(CONFIG_TWINVQ_DECODER) += twinvqdec.o twinvq.o -OBJS-$(CONFIG_TXD_DECODER) += txd.o -OBJS-$(CONFIG_ULTI_DECODER) += ulti.o -OBJS-$(CONFIG_UTVIDEO_DECODER) += utvideodec.o utvideodsp.o -OBJS-$(CONFIG_UTVIDEO_ENCODER) += utvideoenc.o -OBJS-$(CONFIG_V210_DECODER) += v210dec.o -OBJS-$(CONFIG_V210_ENCODER) += v210enc.o -OBJS-$(CONFIG_V210X_DECODER) += v210x.o -OBJS-$(CONFIG_V308_DECODER) += v308dec.o -OBJS-$(CONFIG_V308_ENCODER) += v308enc.o -OBJS-$(CONFIG_V408_DECODER) += v408dec.o -OBJS-$(CONFIG_V408_ENCODER) += v408enc.o -OBJS-$(CONFIG_V410_DECODER) += v410dec.o -OBJS-$(CONFIG_V410_ENCODER) += v410enc.o -OBJS-$(CONFIG_VB_DECODER) += vb.o -OBJS-$(CONFIG_VBN_DECODER) += vbndec.o -OBJS-$(CONFIG_VBN_ENCODER) += vbnenc.o -OBJS-$(CONFIG_VBLE_DECODER) += vble.o -OBJS-$(CONFIG_VC1_DECODER) += vc1dec.o vc1_block.o vc1_loopfilter.o \ - vc1_mc.o vc1_pred.o vc1.o vc1data.o \ - msmpeg4_vc1_data.o wmv2data.o -OBJS-$(CONFIG_VC1_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_VC1_MMAL_DECODER) += mmaldec.o -OBJS-$(CONFIG_VC1_QSV_DECODER) += qsvdec.o -OBJS-$(CONFIG_VC1_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_VC2_ENCODER) += vc2enc.o vc2enc_dwt.o diractab.o -OBJS-$(CONFIG_VCR1_DECODER) += vcr1.o -OBJS-$(CONFIG_VMDAUDIO_DECODER) += vmdaudio.o -OBJS-$(CONFIG_VMDVIDEO_DECODER) += vmdvideo.o -OBJS-$(CONFIG_VMNC_DECODER) += vmnc.o -OBJS-$(CONFIG_VNULL_DECODER) += null.o -OBJS-$(CONFIG_VNULL_ENCODER) += null.o -OBJS-$(CONFIG_VORBIS_DECODER) += vorbisdec.o vorbisdsp.o vorbis.o \ - vorbis_data.o -OBJS-$(CONFIG_VORBIS_ENCODER) += vorbisenc.o vorbis.o \ - vorbis_data.o -OBJS-$(CONFIG_VP3_DECODER) += vp3.o jpegquanttables.o -OBJS-$(CONFIG_VP5_DECODER) += vp5.o vp56.o vp56data.o vpx_rac.o -OBJS-$(CONFIG_VP6_DECODER) += vp6.o vp56.o vp56data.o \ - vp6dsp.o vpx_rac.o -OBJS-$(CONFIG_VP7_DECODER) += vp8.o vpx_rac.o -OBJS-$(CONFIG_VP8_DECODER) += vp8.o vpx_rac.o -OBJS-$(CONFIG_VP8_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_VP8_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_VP8_QSV_DECODER) += qsvdec.o -OBJS-$(CONFIG_VP8_RKMPP_DECODER) += rkmppdec.o -OBJS-$(CONFIG_VP8_VAAPI_ENCODER) += vaapi_encode_vp8.o -OBJS-$(CONFIG_VP8_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_VP8_V4L2M2M_ENCODER) += v4l2_m2m_enc.o -OBJS-$(CONFIG_VP9_DECODER) += vp9.o vp9data.o vp9dsp.o vp9lpf.o vp9recon.o \ - vp9block.o vp9prob.o vp9mvs.o vpx_rac.o \ - vp9dsp_8bpp.o vp9dsp_10bpp.o vp9dsp_12bpp.o -OBJS-$(CONFIG_VP9_CUVID_DECODER) += cuviddec.o -OBJS-$(CONFIG_VP9_MEDIACODEC_DECODER) += mediacodecdec.o -OBJS-$(CONFIG_VP9_MEDIACODEC_ENCODER) += mediacodecenc.o -OBJS-$(CONFIG_VP9_RKMPP_DECODER) += rkmppdec.o -OBJS-$(CONFIG_VP9_VAAPI_ENCODER) += vaapi_encode_vp9.o -OBJS-$(CONFIG_VP9_QSV_ENCODER) += qsvenc_vp9.o -OBJS-$(CONFIG_VPLAYER_DECODER) += textdec.o ass.o -OBJS-$(CONFIG_VP9_V4L2M2M_DECODER) += v4l2_m2m_dec.o -OBJS-$(CONFIG_VQA_DECODER) += vqavideo.o -OBJS-$(CONFIG_VQC_DECODER) += vqcdec.o -OBJS-$(CONFIG_WADY_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_WAVARC_DECODER) += wavarc.o -OBJS-$(CONFIG_WAVPACK_DECODER) += wavpack.o wavpackdata.o dsd.o -OBJS-$(CONFIG_WAVPACK_ENCODER) += wavpackdata.o wavpackenc.o -OBJS-$(CONFIG_WBMP_DECODER) += wbmpdec.o -OBJS-$(CONFIG_WBMP_ENCODER) += wbmpenc.o -OBJS-$(CONFIG_WCMV_DECODER) += wcmv.o -OBJS-$(CONFIG_WEBP_DECODER) += webp.o -OBJS-$(CONFIG_WEBVTT_DECODER) += webvttdec.o ass.o -OBJS-$(CONFIG_WEBVTT_ENCODER) += webvttenc.o ass_split.o -OBJS-$(CONFIG_WMALOSSLESS_DECODER) += wmalosslessdec.o wma_common.o -OBJS-$(CONFIG_WMAPRO_DECODER) += wmaprodec.o wma.o wma_common.o -OBJS-$(CONFIG_WMAV1_DECODER) += wmadec.o wma.o wma_common.o aactab.o -OBJS-$(CONFIG_WMAV1_ENCODER) += wmaenc.o wma.o wma_common.o aactab.o -OBJS-$(CONFIG_WMAV2_DECODER) += wmadec.o wma.o wma_common.o aactab.o -OBJS-$(CONFIG_WMAV2_ENCODER) += wmaenc.o wma.o wma_common.o aactab.o -OBJS-$(CONFIG_WMAVOICE_DECODER) += wmavoice.o \ - celp_filters.o \ - acelp_vectors.o acelp_filters.o -OBJS-$(CONFIG_WMV2_DECODER) += wmv2dec.o wmv2.o wmv2data.o -OBJS-$(CONFIG_WMV2_ENCODER) += wmv2enc.o wmv2.o wmv2data.o -OBJS-$(CONFIG_WNV1_DECODER) += wnv1.o -OBJS-$(CONFIG_WRAPPED_AVFRAME_DECODER) += wrapped_avframe.o -OBJS-$(CONFIG_WRAPPED_AVFRAME_ENCODER) += wrapped_avframe.o -OBJS-$(CONFIG_WS_SND1_DECODER) += ws-snd1.o -OBJS-$(CONFIG_XAN_DPCM_DECODER) += dpcm.o -OBJS-$(CONFIG_XAN_WC3_DECODER) += xan.o -OBJS-$(CONFIG_XAN_WC4_DECODER) += xxan.o -OBJS-$(CONFIG_XBIN_DECODER) += bintext.o cga_data.o -OBJS-$(CONFIG_XBM_DECODER) += xbmdec.o -OBJS-$(CONFIG_XBM_ENCODER) += xbmenc.o -OBJS-$(CONFIG_XFACE_DECODER) += xfacedec.o xface.o -OBJS-$(CONFIG_XFACE_ENCODER) += xfaceenc.o xface.o -OBJS-$(CONFIG_XL_DECODER) += xl.o -OBJS-$(CONFIG_XMA1_DECODER) += wmaprodec.o wma.o wma_common.o -OBJS-$(CONFIG_XMA2_DECODER) += wmaprodec.o wma.o wma_common.o -OBJS-$(CONFIG_XPM_DECODER) += xpmdec.o -OBJS-$(CONFIG_XSUB_DECODER) += xsubdec.o -OBJS-$(CONFIG_XSUB_ENCODER) += xsubenc.o -OBJS-$(CONFIG_XWD_DECODER) += xwddec.o -OBJS-$(CONFIG_XWD_ENCODER) += xwdenc.o -OBJS-$(CONFIG_Y41P_DECODER) += y41pdec.o -OBJS-$(CONFIG_Y41P_ENCODER) += y41penc.o -OBJS-$(CONFIG_YLC_DECODER) += ylc.o -OBJS-$(CONFIG_YOP_DECODER) += yop.o -OBJS-$(CONFIG_YUV4_DECODER) += yuv4dec.o -OBJS-$(CONFIG_YUV4_ENCODER) += yuv4enc.o -OBJS-$(CONFIG_ZEROCODEC_DECODER) += zerocodec.o -OBJS-$(CONFIG_ZLIB_DECODER) += lcldec.o -OBJS-$(CONFIG_ZLIB_ENCODER) += lclenc.o -OBJS-$(CONFIG_ZMBV_DECODER) += zmbv.o -OBJS-$(CONFIG_ZMBV_ENCODER) += zmbvenc.o - -# (AD)PCM decoders/encoders -OBJS-$(CONFIG_PCM_ALAW_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_ALAW_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_BLURAY_ENCODER) += pcm-blurayenc.o -OBJS-$(CONFIG_PCM_BLURAY_DECODER) += pcm-bluray.o -OBJS-$(CONFIG_PCM_DVD_DECODER) += pcm-dvd.o -OBJS-$(CONFIG_PCM_DVD_ENCODER) += pcm-dvdenc.o -OBJS-$(CONFIG_PCM_F16LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_F24LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_F32BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_F32BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_F32LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_F32LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_F64BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_F64BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_F64LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_F64LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_LXF_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_MULAW_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_MULAW_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S8_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S8_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S8_PLANAR_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S8_PLANAR_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S16BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S16BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S16BE_PLANAR_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S16BE_PLANAR_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S16LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S16LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S16LE_PLANAR_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S16LE_PLANAR_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S24BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S24BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S24DAUD_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S24DAUD_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S24LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S24LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S24LE_PLANAR_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S24LE_PLANAR_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S32BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S32BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S32LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S32LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S32LE_PLANAR_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S32LE_PLANAR_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S64BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S64BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_S64LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_S64LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_SGA_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U8_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U8_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_U16BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U16BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_U16LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U16LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_U24BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U24BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_U24LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U24LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_U32BE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U32BE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_U32LE_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_U32LE_ENCODER) += pcm.o -OBJS-$(CONFIG_PCM_VIDC_DECODER) += pcm.o -OBJS-$(CONFIG_PCM_VIDC_ENCODER) += pcm.o - -OBJS-$(CONFIG_ADPCM_4XM_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_ADX_DECODER) += adxdec.o adx.o -OBJS-$(CONFIG_ADPCM_ADX_ENCODER) += adxenc.o adx.o -OBJS-$(CONFIG_ADPCM_AFC_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_AGM_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_AICA_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_ARGO_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_ARGO_ENCODER) += adpcm.o adpcm_data.o adpcmenc.o -OBJS-$(CONFIG_ADPCM_CT_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_DTK_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_EA_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_EA_MAXIS_XA_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_EA_R1_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_EA_R2_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_EA_R3_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_EA_XAS_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_G722_DECODER) += g722.o g722dsp.o g722dec.o -OBJS-$(CONFIG_ADPCM_G722_ENCODER) += g722.o g722dsp.o g722enc.o -OBJS-$(CONFIG_ADPCM_G726_DECODER) += g726.o -OBJS-$(CONFIG_ADPCM_G726_ENCODER) += g726.o -OBJS-$(CONFIG_ADPCM_G726LE_DECODER) += g726.o -OBJS-$(CONFIG_ADPCM_G726LE_ENCODER) += g726.o -OBJS-$(CONFIG_ADPCM_IMA_ACORN_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_AMV_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_AMV_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_ALP_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_ALP_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_APC_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_APM_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_APM_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_CUNNING_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_DAT4_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_DK3_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_DK4_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_EA_EACS_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_EA_SEAD_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_ISS_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_MOFLEX_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_MTF_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_OKI_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_QT_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_QT_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_RAD_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_SSI_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_SSI_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_SMJPEG_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_WAV_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_WAV_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_WS_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_IMA_WS_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_MS_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_MS_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_MTAF_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_PSX_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_SBPRO_2_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_SBPRO_3_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_SBPRO_4_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_SWF_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_SWF_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_THP_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_THP_LE_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_VIMA_DECODER) += vima.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_XA_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_XMD_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_YAMAHA_DECODER) += adpcm.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_YAMAHA_ENCODER) += adpcmenc.o adpcm_data.o -OBJS-$(CONFIG_ADPCM_ZORK_DECODER) += adpcm.o adpcm_data.o - -# hardware accelerators -OBJS-$(CONFIG_D3D11VA) += dxva2.o -OBJS-$(CONFIG_DXVA2) += dxva2.o -OBJS-$(CONFIG_NVDEC) += nvdec.o -OBJS-$(CONFIG_VAAPI) += vaapi_decode.o -OBJS-$(CONFIG_VIDEOTOOLBOX) += videotoolbox.o -OBJS-$(CONFIG_VDPAU) += vdpau.o - -OBJS-$(CONFIG_AV1_D3D11VA_HWACCEL) += dxva2_av1.o -OBJS-$(CONFIG_AV1_DXVA2_HWACCEL) += dxva2_av1.o -OBJS-$(CONFIG_AV1_NVDEC_HWACCEL) += nvdec_av1.o -OBJS-$(CONFIG_AV1_VAAPI_HWACCEL) += vaapi_av1.o -OBJS-$(CONFIG_AV1_VDPAU_HWACCEL) += vdpau_av1.o -OBJS-$(CONFIG_H263_VAAPI_HWACCEL) += vaapi_mpeg4.o -OBJS-$(CONFIG_H263_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o -OBJS-$(CONFIG_H264_D3D11VA_HWACCEL) += dxva2_h264.o -OBJS-$(CONFIG_H264_DXVA2_HWACCEL) += dxva2_h264.o -OBJS-$(CONFIG_H264_NVDEC_HWACCEL) += nvdec_h264.o -OBJS-$(CONFIG_H264_QSV_HWACCEL) += qsvdec.o -OBJS-$(CONFIG_H264_VAAPI_HWACCEL) += vaapi_h264.o -OBJS-$(CONFIG_H264_VDPAU_HWACCEL) += vdpau_h264.o -OBJS-$(CONFIG_H264_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o -OBJS-$(CONFIG_HEVC_D3D11VA_HWACCEL) += dxva2_hevc.o -OBJS-$(CONFIG_HEVC_DXVA2_HWACCEL) += dxva2_hevc.o -OBJS-$(CONFIG_HEVC_NVDEC_HWACCEL) += nvdec_hevc.o -OBJS-$(CONFIG_HEVC_QSV_HWACCEL) += qsvdec.o -OBJS-$(CONFIG_HEVC_VAAPI_HWACCEL) += vaapi_hevc.o h265_profile_level.o -OBJS-$(CONFIG_HEVC_VDPAU_HWACCEL) += vdpau_hevc.o h265_profile_level.o -OBJS-$(CONFIG_MJPEG_NVDEC_HWACCEL) += nvdec_mjpeg.o -OBJS-$(CONFIG_MJPEG_VAAPI_HWACCEL) += vaapi_mjpeg.o -OBJS-$(CONFIG_MPEG1_NVDEC_HWACCEL) += nvdec_mpeg12.o -OBJS-$(CONFIG_MPEG1_VDPAU_HWACCEL) += vdpau_mpeg12.o -OBJS-$(CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o -OBJS-$(CONFIG_MPEG2_D3D11VA_HWACCEL) += dxva2_mpeg2.o -OBJS-$(CONFIG_MPEG2_DXVA2_HWACCEL) += dxva2_mpeg2.o -OBJS-$(CONFIG_MPEG2_NVDEC_HWACCEL) += nvdec_mpeg12.o -OBJS-$(CONFIG_MPEG2_QSV_HWACCEL) += qsvdec.o -OBJS-$(CONFIG_MPEG2_VAAPI_HWACCEL) += vaapi_mpeg2.o -OBJS-$(CONFIG_MPEG2_VDPAU_HWACCEL) += vdpau_mpeg12.o -OBJS-$(CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o -OBJS-$(CONFIG_MPEG4_NVDEC_HWACCEL) += nvdec_mpeg4.o -OBJS-$(CONFIG_MPEG4_VAAPI_HWACCEL) += vaapi_mpeg4.o -OBJS-$(CONFIG_MPEG4_VDPAU_HWACCEL) += vdpau_mpeg4.o -OBJS-$(CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o -OBJS-$(CONFIG_VC1_D3D11VA_HWACCEL) += dxva2_vc1.o -OBJS-$(CONFIG_VC1_DXVA2_HWACCEL) += dxva2_vc1.o -OBJS-$(CONFIG_VC1_NVDEC_HWACCEL) += nvdec_vc1.o -OBJS-$(CONFIG_VC1_QSV_HWACCEL) += qsvdec.o -OBJS-$(CONFIG_VC1_VAAPI_HWACCEL) += vaapi_vc1.o -OBJS-$(CONFIG_VC1_VDPAU_HWACCEL) += vdpau_vc1.o -OBJS-$(CONFIG_VP8_NVDEC_HWACCEL) += nvdec_vp8.o -OBJS-$(CONFIG_VP8_VAAPI_HWACCEL) += vaapi_vp8.o -OBJS-$(CONFIG_VP9_D3D11VA_HWACCEL) += dxva2_vp9.o -OBJS-$(CONFIG_VP9_DXVA2_HWACCEL) += dxva2_vp9.o -OBJS-$(CONFIG_VP9_NVDEC_HWACCEL) += nvdec_vp9.o -OBJS-$(CONFIG_VP9_VAAPI_HWACCEL) += vaapi_vp9.o -OBJS-$(CONFIG_VP9_VDPAU_HWACCEL) += vdpau_vp9.o -OBJS-$(CONFIG_VP9_VIDEOTOOLBOX_HWACCEL) += videotoolbox_vp9.o -OBJS-$(CONFIG_VP8_QSV_HWACCEL) += qsvdec.o - -# Objects duplicated from other libraries for shared builds -SHLIBOBJS += log2_tab.o reverse.o - -# General libavformat dependencies -OBJS-$(CONFIG_FITS_DEMUXER) += fits.o -OBJS-$(CONFIG_TAK_DEMUXER) += tak.o - -# libavformat dependencies for static builds -STLIBOBJS-$(CONFIG_AVFORMAT) += to_upper4.o -STLIBOBJS-$(CONFIG_ISO_MEDIA) += mpegaudiotabs.o -STLIBOBJS-$(CONFIG_FLV_MUXER) += mpeg4audio_sample_rates.o -STLIBOBJS-$(CONFIG_HLS_DEMUXER) += ac3_channel_layout_tab.o -STLIBOBJS-$(CONFIG_MATROSKA_DEMUXER) += mpeg4audio_sample_rates.o -STLIBOBJS-$(CONFIG_MOV_DEMUXER) += ac3_channel_layout_tab.o -STLIBOBJS-$(CONFIG_MXF_MUXER) += golomb.o -STLIBOBJS-$(CONFIG_MP3_MUXER) += mpegaudiotabs.o -STLIBOBJS-$(CONFIG_NUT_MUXER) += mpegaudiotabs.o -STLIBOBJS-$(CONFIG_RTPDEC) += jpegtables.o -STLIBOBJS-$(CONFIG_RTP_MUXER) += golomb.o jpegtables.o \ - mpeg4audio_sample_rates.o -STLIBOBJS-$(CONFIG_SPDIF_MUXER) += dca_sample_rate_tab.o - -# libavfilter dependencies -OBJS-$(CONFIG_ELBG_FILTER) += elbg.o - -# external codec libraries -OBJS-$(CONFIG_AAC_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_AC3_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_ADPCM_IMA_QT_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_ALAC_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_AMR_NB_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_EAC3_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_GSM_MS_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_ILBC_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_MP1_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_MP2_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_MP3_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_PCM_MULAW_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_PCM_ALAW_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_QDMC_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_QDM2_AT_DECODER) += audiotoolboxdec.o -OBJS-$(CONFIG_AAC_AT_ENCODER) += audiotoolboxenc.o -OBJS-$(CONFIG_ALAC_AT_ENCODER) += audiotoolboxenc.o -OBJS-$(CONFIG_ILBC_AT_ENCODER) += audiotoolboxenc.o -OBJS-$(CONFIG_PCM_ALAW_AT_ENCODER) += audiotoolboxenc.o -OBJS-$(CONFIG_PCM_MULAW_AT_ENCODER) += audiotoolboxenc.o -OBJS-$(CONFIG_LIBAOM_AV1_DECODER) += libaomdec.o libaom.o -OBJS-$(CONFIG_LIBAOM_AV1_ENCODER) += libaomenc.o libaom.o -OBJS-$(CONFIG_LIBARIBB24_DECODER) += libaribb24.o ass.o -OBJS-$(CONFIG_LIBARIBCAPTION_DECODER) += libaribcaption.o ass.o -OBJS-$(CONFIG_LIBCELT_DECODER) += libcelt_dec.o -OBJS-$(CONFIG_LIBCODEC2_DECODER) += libcodec2.o -OBJS-$(CONFIG_LIBCODEC2_ENCODER) += libcodec2.o -OBJS-$(CONFIG_LIBDAV1D_DECODER) += libdav1d.o -OBJS-$(CONFIG_LIBDAVS2_DECODER) += libdavs2.o -OBJS-$(CONFIG_LIBFDK_AAC_DECODER) += libfdk-aacdec.o -OBJS-$(CONFIG_LIBFDK_AAC_ENCODER) += libfdk-aacenc.o -OBJS-$(CONFIG_LIBGSM_DECODER) += libgsmdec.o -OBJS-$(CONFIG_LIBGSM_ENCODER) += libgsmenc.o -OBJS-$(CONFIG_LIBGSM_MS_DECODER) += libgsmdec.o -OBJS-$(CONFIG_LIBGSM_MS_ENCODER) += libgsmenc.o -OBJS-$(CONFIG_LIBILBC_DECODER) += libilbc.o -OBJS-$(CONFIG_LIBILBC_ENCODER) += libilbc.o -OBJS-$(CONFIG_LIBJXL_DECODER) += libjxldec.o libjxl.o -OBJS-$(CONFIG_LIBJXL_ENCODER) += libjxlenc.o libjxl.o -OBJS-$(CONFIG_LIBKVAZAAR_ENCODER) += libkvazaar.o -OBJS-$(CONFIG_LIBMP3LAME_ENCODER) += libmp3lame.o -OBJS-$(CONFIG_LIBOPENCORE_AMRNB_DECODER) += libopencore-amr.o -OBJS-$(CONFIG_LIBOPENCORE_AMRNB_ENCODER) += libopencore-amr.o -OBJS-$(CONFIG_LIBOPENCORE_AMRWB_DECODER) += libopencore-amr.o -OBJS-$(CONFIG_LIBOPENH264_DECODER) += libopenh264dec.o libopenh264.o -OBJS-$(CONFIG_LIBOPENH264_ENCODER) += libopenh264enc.o libopenh264.o -OBJS-$(CONFIG_LIBOPENJPEG_ENCODER) += libopenjpegenc.o -OBJS-$(CONFIG_LIBOPUS_DECODER) += libopusdec.o libopus.o \ - vorbis_data.o -OBJS-$(CONFIG_LIBOPUS_ENCODER) += libopusenc.o libopus.o \ - vorbis_data.o -OBJS-$(CONFIG_LIBRAV1E_ENCODER) += librav1e.o -OBJS-$(CONFIG_LIBSHINE_ENCODER) += libshine.o -OBJS-$(CONFIG_LIBSPEEX_DECODER) += libspeexdec.o -OBJS-$(CONFIG_LIBSPEEX_ENCODER) += libspeexenc.o -OBJS-$(CONFIG_LIBSVTAV1_ENCODER) += libsvtav1.o -OBJS-$(CONFIG_LIBTHEORA_ENCODER) += libtheoraenc.o -OBJS-$(CONFIG_LIBTWOLAME_ENCODER) += libtwolame.o -OBJS-$(CONFIG_LIBUAVS3D_DECODER) += libuavs3d.o -OBJS-$(CONFIG_LIBVO_AMRWBENC_ENCODER) += libvo-amrwbenc.o -OBJS-$(CONFIG_LIBVORBIS_DECODER) += libvorbisdec.o -OBJS-$(CONFIG_LIBVORBIS_ENCODER) += libvorbisenc.o \ - vorbis_data.o -OBJS-$(CONFIG_LIBVPX_VP8_DECODER) += libvpxdec.o -OBJS-$(CONFIG_LIBVPX_VP8_ENCODER) += libvpxenc.o -OBJS-$(CONFIG_LIBVPX_VP9_DECODER) += libvpxdec.o -OBJS-$(CONFIG_LIBVPX_VP9_ENCODER) += libvpxenc.o -OBJS-$(CONFIG_LIBWEBP_ENCODER) += libwebpenc_common.o libwebpenc.o -OBJS-$(CONFIG_LIBWEBP_ANIM_ENCODER) += libwebpenc_common.o libwebpenc_animencoder.o -OBJS-$(CONFIG_LIBX262_ENCODER) += libx264.o -OBJS-$(CONFIG_LIBX264_ENCODER) += libx264.o -OBJS-$(CONFIG_LIBX265_ENCODER) += libx265.o -OBJS-$(CONFIG_LIBXAVS_ENCODER) += libxavs.o -OBJS-$(CONFIG_LIBXAVS2_ENCODER) += libxavs2.o -OBJS-$(CONFIG_LIBXVID_ENCODER) += libxvid.o -OBJS-$(CONFIG_LIBZVBI_TELETEXT_DECODER) += libzvbi-teletextdec.o ass.o - -# parsers -OBJS-$(CONFIG_AAC_LATM_PARSER) += latm_parser.o -OBJS-$(CONFIG_AAC_PARSER) += aac_parser.o aac_ac3_parser.o -OBJS-$(CONFIG_AC3_PARSER) += aac_ac3_parser.o ac3tab.o \ - ac3_channel_layout_tab.o -OBJS-$(CONFIG_ADX_PARSER) += adx_parser.o -OBJS-$(CONFIG_AMR_PARSER) += amr_parser.o -OBJS-$(CONFIG_AV1_PARSER) += av1_parser.o -OBJS-$(CONFIG_AVS2_PARSER) += avs2.o avs2_parser.o -OBJS-$(CONFIG_AVS3_PARSER) += avs3_parser.o -OBJS-$(CONFIG_BMP_PARSER) += bmp_parser.o -OBJS-$(CONFIG_CAVSVIDEO_PARSER) += cavs_parser.o -OBJS-$(CONFIG_COOK_PARSER) += cook_parser.o -OBJS-$(CONFIG_CRI_PARSER) += cri_parser.o -OBJS-$(CONFIG_DCA_PARSER) += dca_parser.o dca_exss.o dca.o \ - dca_sample_rate_tab.o -OBJS-$(CONFIG_DIRAC_PARSER) += dirac_parser.o -OBJS-$(CONFIG_DNXHD_PARSER) += dnxhd_parser.o dnxhddata.o -OBJS-$(CONFIG_DOLBY_E_PARSER) += dolby_e_parser.o dolby_e_parse.o -OBJS-$(CONFIG_DPX_PARSER) += dpx_parser.o -OBJS-$(CONFIG_DVAUDIO_PARSER) += dvaudio_parser.o -OBJS-$(CONFIG_DVBSUB_PARSER) += dvbsub_parser.o -OBJS-$(CONFIG_DVD_NAV_PARSER) += dvd_nav_parser.o -OBJS-$(CONFIG_DVDSUB_PARSER) += dvdsub_parser.o -OBJS-$(CONFIG_FLAC_PARSER) += flac_parser.o flacdata.o flac.o -OBJS-$(CONFIG_FTR_PARSER) += ftr_parser.o -OBJS-$(CONFIG_G723_1_PARSER) += g723_1_parser.o -OBJS-$(CONFIG_G729_PARSER) += g729_parser.o -OBJS-$(CONFIG_GIF_PARSER) += gif_parser.o -OBJS-$(CONFIG_GSM_PARSER) += gsm_parser.o -OBJS-$(CONFIG_H261_PARSER) += h261_parser.o -OBJS-$(CONFIG_H263_PARSER) += h263_parser.o -OBJS-$(CONFIG_H264_PARSER) += h264_parser.o h264data.o -OBJS-$(CONFIG_HEVC_PARSER) += hevc_parser.o hevc_data.o -OBJS-$(CONFIG_HDR_PARSER) += hdr_parser.o -OBJS-$(CONFIG_IPU_PARSER) += ipu_parser.o -OBJS-$(CONFIG_JPEG2000_PARSER) += jpeg2000_parser.o -OBJS-$(CONFIG_MISC4_PARSER) += misc4_parser.o -OBJS-$(CONFIG_MJPEG_PARSER) += mjpeg_parser.o -OBJS-$(CONFIG_MLP_PARSER) += mlp_parse.o mlp_parser.o mlp.o -OBJS-$(CONFIG_MPEG4VIDEO_PARSER) += mpeg4video_parser.o h263.o \ - mpeg4videodec.o mpeg4video.o \ - ituh263dec.o h263dec.o h263data.o -OBJS-$(CONFIG_MPEGAUDIO_PARSER) += mpegaudio_parser.o -OBJS-$(CONFIG_MPEGVIDEO_PARSER) += mpegvideo_parser.o \ - mpeg12.o mpeg12data.o -OBJS-$(CONFIG_OPUS_PARSER) += opus_parser.o opus_parse.o \ - vorbis_data.o -OBJS-$(CONFIG_PNG_PARSER) += png_parser.o -OBJS-$(CONFIG_PNM_PARSER) += pnm_parser.o pnm.o -OBJS-$(CONFIG_QOI_PARSER) += qoi_parser.o -OBJS-$(CONFIG_RV30_PARSER) += rv34_parser.o -OBJS-$(CONFIG_RV40_PARSER) += rv34_parser.o -OBJS-$(CONFIG_SBC_PARSER) += sbc_parser.o -OBJS-$(CONFIG_SIPR_PARSER) += sipr_parser.o -OBJS-$(CONFIG_TAK_PARSER) += tak_parser.o tak.o -OBJS-$(CONFIG_VC1_PARSER) += vc1_parser.o vc1.o vc1data.o \ - wmv2data.o -OBJS-$(CONFIG_VP3_PARSER) += vp3_parser.o -OBJS-$(CONFIG_VP8_PARSER) += vp8_parser.o -OBJS-$(CONFIG_VP9_PARSER) += vp9_parser.o -OBJS-$(CONFIG_WEBP_PARSER) += webp_parser.o -OBJS-$(CONFIG_XBM_PARSER) += xbm_parser.o -OBJS-$(CONFIG_XMA_PARSER) += xma_parser.o -OBJS-$(CONFIG_XWD_PARSER) += xwd_parser.o - -# bitstream filters -OBJS-$(CONFIG_AAC_ADTSTOASC_BSF) += aac_adtstoasc_bsf.o -OBJS-$(CONFIG_AV1_METADATA_BSF) += av1_metadata_bsf.o -OBJS-$(CONFIG_AV1_FRAME_MERGE_BSF) += av1_frame_merge_bsf.o -OBJS-$(CONFIG_AV1_FRAME_SPLIT_BSF) += av1_frame_split_bsf.o -OBJS-$(CONFIG_CHOMP_BSF) += chomp_bsf.o -OBJS-$(CONFIG_DUMP_EXTRADATA_BSF) += dump_extradata_bsf.o -OBJS-$(CONFIG_DCA_CORE_BSF) += dca_core_bsf.o -OBJS-$(CONFIG_DTS2PTS_BSF) += dts2pts_bsf.o -OBJS-$(CONFIG_DV_ERROR_MARKER_BSF) += dv_error_marker_bsf.o -OBJS-$(CONFIG_EAC3_CORE_BSF) += eac3_core_bsf.o -OBJS-$(CONFIG_EXTRACT_EXTRADATA_BSF) += extract_extradata_bsf.o \ - av1_parse.o h2645_parse.o -OBJS-$(CONFIG_FILTER_UNITS_BSF) += filter_units_bsf.o -OBJS-$(CONFIG_H264_METADATA_BSF) += h264_metadata_bsf.o h264_levels.o \ - h2645data.o -OBJS-$(CONFIG_H264_MP4TOANNEXB_BSF) += h264_mp4toannexb_bsf.o -OBJS-$(CONFIG_H264_REDUNDANT_PPS_BSF) += h264_redundant_pps_bsf.o -OBJS-$(CONFIG_HAPQA_EXTRACT_BSF) += hapqa_extract_bsf.o hap.o -OBJS-$(CONFIG_HEVC_METADATA_BSF) += h265_metadata_bsf.o h265_profile_level.o \ - h2645data.o -OBJS-$(CONFIG_HEVC_MP4TOANNEXB_BSF) += hevc_mp4toannexb_bsf.o -OBJS-$(CONFIG_IMX_DUMP_HEADER_BSF) += imx_dump_header_bsf.o -OBJS-$(CONFIG_MEDIA100_TO_MJPEGB_BSF) += media100_to_mjpegb_bsf.o -OBJS-$(CONFIG_MJPEG2JPEG_BSF) += mjpeg2jpeg_bsf.o -OBJS-$(CONFIG_MJPEGA_DUMP_HEADER_BSF) += mjpega_dump_header_bsf.o -OBJS-$(CONFIG_MPEG4_UNPACK_BFRAMES_BSF) += mpeg4_unpack_bframes_bsf.o -OBJS-$(CONFIG_MOV2TEXTSUB_BSF) += movsub_bsf.o -OBJS-$(CONFIG_MP3_HEADER_DECOMPRESS_BSF) += mp3_header_decompress_bsf.o \ - mpegaudiotabs.o -OBJS-$(CONFIG_MPEG2_METADATA_BSF) += mpeg2_metadata_bsf.o -OBJS-$(CONFIG_NOISE_BSF) += noise_bsf.o -OBJS-$(CONFIG_NULL_BSF) += null_bsf.o -OBJS-$(CONFIG_OPUS_METADATA_BSF) += opus_metadata_bsf.o -OBJS-$(CONFIG_PCM_RECHUNK_BSF) += pcm_rechunk_bsf.o -OBJS-$(CONFIG_PGS_FRAME_MERGE_BSF) += pgs_frame_merge_bsf.o -OBJS-$(CONFIG_PRORES_METADATA_BSF) += prores_metadata_bsf.o -OBJS-$(CONFIG_REMOVE_EXTRADATA_BSF) += remove_extradata_bsf.o av1_parse.o -OBJS-$(CONFIG_SETTS_BSF) += setts_bsf.o -OBJS-$(CONFIG_TEXT2MOVSUB_BSF) += movsub_bsf.o -OBJS-$(CONFIG_TRACE_HEADERS_BSF) += trace_headers_bsf.o -OBJS-$(CONFIG_TRUEHD_CORE_BSF) += truehd_core_bsf.o mlp_parse.o mlp.o -OBJS-$(CONFIG_VP9_METADATA_BSF) += vp9_metadata_bsf.o -OBJS-$(CONFIG_VP9_RAW_REORDER_BSF) += vp9_raw_reorder_bsf.o -OBJS-$(CONFIG_VP9_SUPERFRAME_BSF) += vp9_superframe_bsf.o -OBJS-$(CONFIG_VP9_SUPERFRAME_SPLIT_BSF) += vp9_superframe_split_bsf.o - -# thread libraries -OBJS-$(HAVE_LIBC_MSVCRT) += file_open.o -OBJS-$(HAVE_THREADS) += pthread.o pthread_slice.o pthread_frame.o - -OBJS-$(CONFIG_FRAME_THREAD_ENCODER) += frame_thread_encoder.o - -# Windows resource file -SHLIBOBJS-$(HAVE_GNU_WINDRES) += avcodecres.o - -SKIPHEADERS += %_tablegen.h \ - %_tables.h \ - tableprint.h \ - tableprint_vlc.h \ - aaccoder_twoloop.h \ - aaccoder_trellis.h \ - aacenc_quantization.h \ - aacenc_quantization_misc.h \ - bitstream_template.h \ - $(ARCH)/vpx_arith.h \ - -SKIPHEADERS-$(CONFIG_AMF) += amfenc.h -SKIPHEADERS-$(CONFIG_D3D11VA) += d3d11va.h dxva2_internal.h -SKIPHEADERS-$(CONFIG_DXVA2) += dxva2.h dxva2_internal.h -SKIPHEADERS-$(CONFIG_JNI) += ffjni.h -SKIPHEADERS-$(CONFIG_LCMS2) += fflcms2.h -SKIPHEADERS-$(CONFIG_LIBAOM) += libaom.h -SKIPHEADERS-$(CONFIG_LIBJXL) += libjxl.h -SKIPHEADERS-$(CONFIG_LIBVPX) += libvpx.h -SKIPHEADERS-$(CONFIG_LIBWEBP_ENCODER) += libwebpenc_common.h -SKIPHEADERS-$(CONFIG_MEDIACODEC) += mediacodecdec_common.h mediacodec_surface.h mediacodec_wrapper.h mediacodec_sw_buffer.h -SKIPHEADERS-$(CONFIG_MEDIAFOUNDATION) += mf_utils.h -SKIPHEADERS-$(CONFIG_NVDEC) += nvdec.h -SKIPHEADERS-$(CONFIG_NVENC) += nvenc.h -SKIPHEADERS-$(CONFIG_QSV) += qsv.h qsv_internal.h -SKIPHEADERS-$(CONFIG_QSVENC) += qsvenc.h -SKIPHEADERS-$(CONFIG_XVMC) += xvmc.h -SKIPHEADERS-$(CONFIG_VAAPI) += vaapi_decode.h vaapi_hevc.h vaapi_encode.h -SKIPHEADERS-$(CONFIG_VDPAU) += vdpau.h vdpau_internal.h -SKIPHEADERS-$(CONFIG_VIDEOTOOLBOX) += videotoolbox.h vt_internal.h -SKIPHEADERS-$(CONFIG_V4L2_M2M) += v4l2_buffers.h v4l2_context.h v4l2_m2m.h -SKIPHEADERS-$(CONFIG_ZLIB) += zlib_wrapper.h - -TESTPROGS = avcodec \ - avpacket \ - bitstream_be \ - bitstream_le \ - celp_math \ - codec_desc \ - htmlsubtitles \ - jpeg2000dwt \ - mathops \ - -TESTPROGS-$(CONFIG_CABAC) += cabac -TESTPROGS-$(CONFIG_DCT) += avfft -TESTPROGS-$(CONFIG_FFT) += fft fft-fixed32 -TESTPROGS-$(CONFIG_GOLOMB) += golomb -TESTPROGS-$(CONFIG_IDCTDSP) += dct -TESTPROGS-$(CONFIG_IIRFILTER) += iirfilter -TESTPROGS-$(CONFIG_MJPEG_ENCODER) += mjpegenc_huffman -TESTPROGS-$(HAVE_MMX) += motion -TESTPROGS-$(CONFIG_MPEGVIDEO) += mpeg12framerate -TESTPROGS-$(CONFIG_H264_METADATA_BSF) += h264_levels -TESTPROGS-$(CONFIG_HEVC_METADATA_BSF) += h265_levels -TESTPROGS-$(CONFIG_RANGECODER) += rangecoder -TESTPROGS-$(CONFIG_SNOW_ENCODER) += snowenc - -TESTOBJS = dctref.o - -TOOLS = fourcc2pixfmt - -HOSTPROGS = aacps_tablegen \ - aacps_fixed_tablegen \ - cbrt_tablegen \ - cbrt_fixed_tablegen \ - cos_tablegen \ - dv_tablegen \ - motionpixels_tablegen \ - mpegaudio_tablegen \ - mpegaudiodec_common_tablegen \ - pcm_tablegen \ - qdm2_tablegen \ - sinewin_tablegen \ - sinewin_fixed_tablegen \ - -CLEANFILES = *_tables.c *_tables.h *_tablegen$(HOSTEXESUF) - -$(SUBDIR)tests/dct$(EXESUF): $(SUBDIR)dctref.o $(SUBDIR)aandcttab.o -$(SUBDIR)dv_tablegen$(HOSTEXESUF): $(SUBDIR)dvdata_host.o - -TRIG_TABLES = cos cos_fixed sin -TRIG_TABLES := $(TRIG_TABLES:%=$(SUBDIR)%_tables.c) - -$(TRIG_TABLES): $(SUBDIR)%_tables.c: $(SUBDIR)cos_tablegen$(HOSTEXESUF) - $(M)./$< $* > $@ - -ifdef CONFIG_SMALL -$(SUBDIR)%_tablegen$(HOSTEXESUF): HOSTCFLAGS += -DCONFIG_SMALL=1 -else -$(SUBDIR)%_tablegen$(HOSTEXESUF): HOSTCFLAGS += -DCONFIG_SMALL=0 -endif - -GEN_HEADERS = cbrt_tables.h cbrt_fixed_tables.h aacps_tables.h aacps_fixed_tables.h \ - dv_tables.h \ - sinewin_tables.h sinewin_fixed_tables.h mpegaudio_tables.h \ - mpegaudiodec_common_tables.h motionpixels_tables.h \ - pcm_tables.h qdm2_tables.h -GEN_HEADERS := $(addprefix $(SUBDIR), $(GEN_HEADERS)) - -$(GEN_HEADERS): $(SUBDIR)%_tables.h: $(SUBDIR)%_tablegen$(HOSTEXESUF) - $(M)./$< > $@ - -ifdef CONFIG_HARDCODED_TABLES -$(SUBDIR)cbrt_data.o: $(SUBDIR)cbrt_tables.h -$(SUBDIR)cbrt_data_fixed.o: $(SUBDIR)cbrt_fixed_tables.h -$(SUBDIR)aacdec_fixed.o: $(SUBDIR)sinewin_fixed_tables.h -$(SUBDIR)aacps_float.o: $(SUBDIR)aacps_tables.h -$(SUBDIR)aacps_fixed.o: $(SUBDIR)aacps_fixed_tables.h -$(SUBDIR)dvenc.o: $(SUBDIR)dv_tables.h -$(SUBDIR)motionpixels.o: $(SUBDIR)motionpixels_tables.h -$(SUBDIR)mpegaudiodec_common.o: $(SUBDIR)mpegaudiodec_common_tables.h -$(SUBDIR)mpegaudiodec_fixed.o: $(SUBDIR)mpegaudio_tables.h -$(SUBDIR)mpegaudiodec_float.o: $(SUBDIR)mpegaudio_tables.h -$(SUBDIR)pcm.o: $(SUBDIR)pcm_tables.h -$(SUBDIR)qdm2.o: $(SUBDIR)qdm2_tables.h -$(SUBDIR)sinewin.o: $(SUBDIR)sinewin_tables.h -endif diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download Vidmate Lite for PC - The Ultimate Video Downloader for Windows.md b/spaces/congsaPfin/Manga-OCR/logs/Download Vidmate Lite for PC - The Ultimate Video Downloader for Windows.md deleted file mode 100644 index 488a3c493c68bd409095ce595e89cfccef09fae6..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Download Vidmate Lite for PC - The Ultimate Video Downloader for Windows.md +++ /dev/null @@ -1,142 +0,0 @@ - -

    Download Vidmate Lite: A Free and Fast Video Downloader for Android

    -

    Do you love watching videos and listening to music on your Android device? Do you wish you could download them easily and quickly from various online platforms? If yes, then you should try Vidmate Lite, a free and fast video downloader app that lets you enjoy your favorite content offline. In this article, we will tell you everything you need to know about Vidmate Lite, including its features, how to download and install it, why to choose it over other video downloaders, and how to use it to download videos and music. Read on to find out more.

    -

    What is Vidmate Lite?

    -

    Vidmate Lite is a lightweight version of the popular Vidmate app, which is one of the best video downloader apps for Android. Vidmate Lite allows you to download videos and music from various online platforms, such as YouTube, Facebook, Instagram, TikTok, Dailymotion, Vimeo, and more. You can choose from different formats and resolutions, ranging from 144p to 1080p. You can also download multiple files at once with high speed and resume broken downloads. Vidmate Lite is compatible with most Android devices and does not require much storage space or RAM.

    -

    download vidmate lite


    Download ===== https://urlca.com/2uObJm



    -

    Features of Vidmate Lite

    -

    Some of the main features of Vidmate Lite are:

    -
      -
    • Free and fast video downloader app for Android
    • -
    • Supports downloading videos and music from various online platforms
    • -
    • Offers different formats and resolutions to choose from
    • -
    • Supports downloading multiple files at once with high speed
    • -
    • Supports resuming broken downloads
    • -
    • Compatible with most Android devices
    • -
    • Does not require much storage space or RAM
    • -
    -

    How to download and install Vidmate Lite?

    -

    To download and install Vidmate Lite on your Android device, follow these simple steps:

    -
      -
    1. Go to the official website of Vidmate Lite or and click on the download button.
    2. -
    3. Once the APK file is downloaded, open it and tap on install.
    4. -
    5. If you see a warning message that says "Install blocked", go to your device settings and enable "Unknown sources".
    6. -
    7. After the installation is complete, open the app and grant the necessary permissions.
    8. -
    9. You are now ready to use Vidmate Lite to download videos and music.
    10. -
    -

    Why choose Vidmate Lite over other video downloaders?

    -

    Vidmate Lite is not the only video downloader app available for Android, but it is one of the best ones. Here are some reasons why you should choose Vidmate Lite over other video downloaders:

    -

    Advantages of Vidmate Lite

    -
      -
    • Vidmate Lite is free and does not have any hidden charges or subscriptions.
    • -
    • Vidmate Lite is fast and can download videos and music in a matter of minutes.
    • -
    • Vidmate Lite supports a wide range of online platforms and formats.
    • -
    • Vidmate Lite allows you to download multiple files at once and resume broken downloads.
    • -
    • Vidmate Lite is compatible with most Android devices and does not require much storage space or RAM.
    • -
    -

    Disadvantages of Vidmate Lite

    -
      -
    • Vidmate Lite is not available on Google Play Store and has to be downloaded from third-party sources.
    • -
    • Vidmate Lite may show some ads while using the app.
    • -
    • Vidmate Lite may not support some online platforms or formats that are not very popular or restricted by the original source.
    • -
    -

    How to use Vidmate Lite to download videos and music?

    -

    Using Vidmate Lite to download videos and music is very easy and convenient. Here are the steps you need to follow:

    -

    Steps to download videos and music from Vidmate Lite

    -
      -
    1. Open the app and tap on the search icon on the top right corner.
    2. -
    3. Type in the name of the video or music you want to download or paste the URL of the online platform.
    4. -
    5. Select the video or music from the search results and tap on the download icon on the bottom right corner.
    6. -
    7. Choose the format and resolution you prefer and tap on download again.
    8. -
    9. Wait for the download to finish and enjoy your offline content.
    10. -
    -

    Tips and tricks to optimize your Vidmate Lite experience

    -

    Here are some tips and tricks that can help you optimize your Vidmate Lite experience:

    -
      -
    • You can access your downloaded files from the "Downloaded" tab on the app or from your device's file manager.
    • -
    • You can manage your downloads by pausing, resuming, deleting, or sharing them from the "Downloading" tab on the app.
    • -
    • You can change your download settings, such as the default download path, the maximum number of downloads, or the network preference, from the "Settings" tab on the app.
    • -
    • You can also watch live TV channels, browse popular videos, or discover new content from the "Home" tab on the app.
    • -
    -

    Conclusion

    -

    Vidmate Lite is a free and fast video downloader app for Android that lets you download videos and music from various online platforms. It has many features and advantages that make it one of the best video downloader apps available. It is also easy to use and compatible with most Android devices. If you are looking for a way to enjoy your favorite content offline, you should definitely give Vidmate Lite a try.

    -

    Summary of the main points

    -

    In this article, we have covered:

    -

    How to download vidmate lite for android
    -Download vidmate lite apk latest version
    -Vidmate lite free download for pc
    -Download vidmate lite app for ios
    -Vidmate lite online video downloader
    -Download vidmate lite hd video downloader
    -Vidmate lite pro mod apk download
    -Download vidmate lite for windows 10
    -Vidmate lite vs vidmate full comparison
    -Download vidmate lite for laptop
    -Vidmate lite app download install
    -Download vidmate lite for mac
    -Vidmate lite 2023 download new version
    -Download vidmate lite for jio phone
    -Vidmate lite review and features
    -Download vidmate lite for smart tv
    -Vidmate lite old version download 2019
    -Download vidmate lite for firestick
    -Vidmate lite app download uptodown
    -Download vidmate lite for chromebook
    -Vidmate lite apk download apkpure
    -Download vidmate lite for iphone
    -Vidmate lite app download 9apps
    -Download vidmate lite for blackberry
    -Vidmate lite app download play store
    -Download vidmate lite for nokia x2
    -Vidmate lite app download apk mirror
    -Download vidmate lite for kindle fire
    -Vidmate lite app download softonic
    -Download vidmate lite for samsung z2
    -Vidmate lite app download mobango
    -Download vidmate lite for mi tv
    -Vidmate lite app download apkmonk
    -Download vidmate lite for ubuntu
    -Vidmate lite app download malavida
    -Download vidmate lite for oppo a37f
    -Vidmate lite app download filehippo
    -Download vidmate lite for vivo y51l
    -Vidmate lite app download apkmody
    -Download vidmate lite for lenovo a6000 plus
    -Vidmate lite app download apkdone
    -Download vidmate lite for redmi note 4g
    -Vidmate lite app download apk4fun
    -Download vidmate lite for micromax q402 plus
    -Vidmate lite app download apkhere
    -Download vidmate lite for gionee f103 pro
    -Vidmate lite app download apknite
    -Download vidmate lite for coolpad note 3
    -Vidmate lite app download apkcombo

    -
      -
    • What is Vidmate Lite and what are its features?
    • -
    • How to download and install Vidmate Lite on your Android device?
    • -
    • Why choose Vidmate Lite over other video downloaders?
    • -
    • How to use Vidmate Lite to download videos and music?
    • -
    • Tips and tricks to optimize your Vidmate Lite experience.
    • -
    -

    FAQs

    -

    Here are some frequently asked questions about Vidmate Lite:

    -
      -
    1. Is Vidmate Lite safe to use?
    2. -

      Vidmate Lite is safe to use as long as you download it from its official website or or other trusted sources. It does not contain any viruses or malware that can harm your device or data. However, you should be careful about what you download from online platforms, as some of them may contain harmful content or violate copyright laws.

      -
    3. Is Vidmate Lite legal to use?
    4. -

      Vidmate Lite is legal to use as long as you use it for personal and non-commercial purposes. It does not host any content on its own servers, but only provides a way to download them from online platforms. However, you should respect the rights of the original content creators and owners, and follow their terms and conditions when downloading their content.

      -
    5. How can I update Vidmate Lite?
    6. -

      Vidmate Lite does not have an automatic update feature, so you have to manually update it whenever a new version is available. You can check for updates from the "Settings" tab on the app or from its official website or . You can then download and install the latest APK file as described above.

      -
    7. How can I contact Vidmate Lite support?
    8. -

      If you have any questions, feedback, or issues regarding Vidmate Lite, you can contact its support team by sending an email to vidmatelite@gmail.com. You can also visit its official website or for more information and resources.

      -
    9. What are some alternatives to Vidmate Lite?
    10. -

      If you are looking for some alternatives to Vidmate Lite, you can try these other video downloader apps for Android:

      -
        -
      • Snaptube: A similar app that supports downloading videos and music from various online platforms.
      • -
      • TubeMate: A popular app that specializes in downloading videos from YouTube.Videoder: A versatile app that supports downloading videos and music from over 50 online platforms.
      • -
      • All Video Downloader: A simple and easy-to-use app that supports downloading videos from most online platforms.
      • -
      -
    -

    I hope you found this article helpful and informative. If you did, please share it with your friends and family who might also be interested in downloading videos and music from online platforms. Thank you for reading and happy downloading!

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/GTA 5 Mobile Grand Theft Auto The Most Immersive Action Game on Android.md b/spaces/congsaPfin/Manga-OCR/logs/GTA 5 Mobile Grand Theft Auto The Most Immersive Action Game on Android.md deleted file mode 100644 index 42fdf7ae8f56820e2ab1b512f755b84ebc6ccf99..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/GTA 5 Mobile Grand Theft Auto The Most Immersive Action Game on Android.md +++ /dev/null @@ -1,92 +0,0 @@ - -

    APK Rate GTA 5 APK: What You Need to Know

    -

    GTA 5 is one of the most iconic and highly rated video games of all time, developed by Rockstar Games. It features an expansive open world, a captivating story, and a variety of activities and missions. However, GTA 5 is not available for Android devices, which means that many fans of the game cannot enjoy it on their mobile phones or tablets.

    -

    That's where APK Rate GTA 5 APK comes in. This is an unofficial Android app that lets you play GTA 5 on your mobile device. It has been downloaded by millions of users who want to experience the thrill of GTA 5 on their smartphones. But what exactly is APK Rate GTA 5 APK, how do you download and install it, and what are its pros and cons? In this article, we will answer these questions and more.

    -

    apk rate gta 5 apk


    Download ✓✓✓ https://urlca.com/2uOaiO



    -

    How to Download and Install APK Rate GTA 5 APK on Your Android Device

    -

    If you want to play GTA 5 on your Android device, you will need to download and install APK Rate GTA 5 APK. This is not a regular app that you can find on the Google Play Store, so you will need to follow some steps to get it. Here's how:

    -
      -
    • Step 1: Download the APK file from a trusted source. You can search for "APK Rate GTA 5 APK" on Google or use this link to download it directly.
    • -
    • Step 2: Enable unknown sources on your device settings. This will allow you to install apps that are not from the Google Play Store. To do this, go to Settings > Security > Unknown Sources and toggle it on.
    • -
    • Step 3: Install the APK file and launch the game. Locate the downloaded APK file on your device storage and tap on it to install it. Once the installation is complete, you can open the game and start playing.
    • -
    -

    How to Play GTA 5 Mobile on Your PC or Mac with BlueStacks

    -

    If you prefer to play GTA 5 on your PC or Mac, you can use BlueStacks, which is an app player that supports over 2 million Android games for PC and Mac. With BlueStacks, you can enjoy GTA 5 GTA 5 Mobile on one window and use another window to browse the web, chat with your friends, or watch a video. You can also switch between different instances of GTA 5 Mobile and play with different accounts or characters. - -

    Pros and Cons of APK Rate GTA 5 APK

    -

    APK Rate GTA 5 APK is not a perfect app, and it has its own advantages and disadvantages. Here are some of the pros and cons that you should consider before downloading and installing it:

    -

    apk rate gta 5 mobile download
    -apk rate gta 5 android gameplay
    -apk rate gta 5 mod menu
    -apk rate gta 5 online multiplayer
    -apk rate gta 5 free full version
    -apk rate gta 5 cheats and hacks
    -apk rate gta 5 graphics settings
    -apk rate gta 5 update latest version
    -apk rate gta 5 review and rating
    -apk rate gta 5 offline mode
    -apk rate gta 5 system requirements
    -apk rate gta 5 installation guide
    -apk rate gta 5 missions and heists
    -apk rate gta 5 characters and vehicles
    -apk rate gta 5 tips and tricks
    -apk rate gta 5 best mods and skins
    -apk rate gta 5 comparison with pc and console versions
    -apk rate gta 5 bugs and glitches
    -apk rate gta 5 features and improvements
    -apk rate gta 5 how to play on bluestacks
    -apk rate gta 5 download link and file size
    -apk rate gta 5 obb data and cache
    -apk rate gta 5 support and feedback
    -apk rate gta 5 alternatives and similar games
    -apk rate gta 5 fan art and wallpapers
    -apk rate gta 5 soundtrack and radio stations
    -apk rate gta 5 map and locations
    -apk rate gta 5 weapons and customization
    -apk rate gta 5 story and plot
    -apk rate gta 5 easter eggs and secrets
    -apk rate gta 5 codes and vouchers
    -apk rate gta 5 controller and keyboard support
    -apk rate gta 5 performance and optimization
    -apk rate gta 5 screenshots and videos
    -apk rate gta 5 news and updates
    -apk rate gta 5 forums and communities
    -apk rate gta 5 faq and troubleshooting
    -apk rate gta 5 emulator and compatibility
    -apk rate gta 5 sandbox and open world
    -apk rate gta 5 fun and entertainment

    - - - - - - - - - - - - - - - - - -
    ProsCons
    Pro 1: Free and easy to download and install. APK Rate GTA 5 APK does not cost anything, and you can download it from various sources online. You can also install it on your Android device without any hassle, as long as you enable unknown sources on your settings.Con 1: Not an official app from Rockstar Games. APK Rate GTA 5 APK is not developed or endorsed by Rockstar Games, the creators of GTA 5. This means that it may not have the same quality, features, or updates as the original game. It may also have compatibility issues with some devices or versions of Android.
    Pro 2: Compatible with most Android devices. APK Rate GTA 5 APK can run on most Android devices that have at least 1 GB of RAM and 4 GB of storage space. You do not need a high-end device to play GTA 5 on your mobile phone or tablet.Con 2: May contain bugs, glitches, or malware. APK Rate GTA 5 APK is not a verified or secure app, and it may contain errors, bugs, or glitches that can affect your gameplay experience. It may also contain malicious software that can harm your device or steal your personal information.
    Pro 3: Offers a similar gameplay experience as the original GTA 5. APK Rate GTA 5 APK lets you play GTA 5 on your mobile device with the same graphics, sound, and gameplay as the original game. You can explore the vast open world, complete missions, interact with characters, drive vehicles, and more.Con 3: May violate the terms and conditions of GTA 5. APK Rate GTA 5 APK is an unofficial app that modifies the original game files of GTA 5. This may be considered as piracy or hacking by Rockstar Games, and it may result in legal action or account suspension. You may also lose access to online features or updates of GTA 5.
    -

    Conclusion

    -

    APK Rate GTA 5 APK is a popular Android game that lets you play GTA 5 on your mobile device. It is free and easy to download and install, and it is compatible with most Android devices. However, it is not an official app from Rockstar Games, and it may have some drawbacks and risks. It may contain bugs, glitches, or malware, and it may violate the terms and conditions of GTA 5.

    -

    If you want to play GTA 5 on your PC or Mac, you can use BlueStacks, which is a safe and reliable app player that supports over 2 million Android games for PC and Mac. With BlueStacks, you can enjoy GTA 5 on your PC or Mac with a larger screen, better graphics, and customized controls. You can also run multiple apps and games at once with Multi-Instance.

    -

    Frequently Asked Questions

    -
      -
    • Q: Is APK Rate GTA 5 APK safe to use?
    • -
    • A: APK Rate GTA 5 APK is not a verified or secure app, and it may contain errors, bugs, or glitches that can affect your gameplay experience. It may also contain malicious software that can harm your device or steal your personal information. Therefore, we do not recommend using it unless you are aware of the risks and consequences.
    • -
    • Q: How much space does APK Rate GTA 5 APK take up on my device?
    • -
    • A: APK Rate GTA 5 APK requires at least 4 GB of storage space on your device to install and run properly. You may need more space depending on the updates or additional files that the app may download.
    • -
    • Q: Can I play online with other players using APK Rate GTA 5 APK?
    • -
    • A: No, you cannot play online with other players using APK Rate GTA 5 APK. The app does not support online features or multiplayer modes of GTA 5. You can only play offline with the single-player mode.
    • Q: What is the difference between APK Rate GTA 5 APK and GTA 5 Mobile by Rockstar Games? -
    • A: APK Rate GTA 5 APK is an unofficial app that modifies the original game files of GTA 5 to make it compatible with Android devices. GTA 5 Mobile by Rockstar Games is an official app that is designed and developed by Rockstar Games for Android devices. GTA 5 Mobile by Rockstar Games has better quality, features, and updates than APK Rate GTA 5 APK.
    • -
    • Q: How can I contact the developers of APK Rate GTA 5 APK?
    • -
    • A: There is no official website or contact information for the developers of APK Rate GTA 5 APK. The app is distributed by various sources online, and there is no guarantee that they are trustworthy or reliable. Therefore, we advise you to be careful when downloading or installing the app, and to avoid sharing any personal or sensitive information with the developers or sources.
    • -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Save The Dog No Ads APK The Best Way to Play This Cute Game.md b/spaces/congsaPfin/Manga-OCR/logs/Save The Dog No Ads APK The Best Way to Play This Cute Game.md deleted file mode 100644 index 77646a29adbe99347bd3510dba5549d5239e5285..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Save The Dog No Ads APK The Best Way to Play This Cute Game.md +++ /dev/null @@ -1,102 +0,0 @@ -
    -

    Save the Dog No Ads APK: A Fun and Creative Casual Game

    -

    Do you love dogs? Do you love casual games? Do you hate ads? If you answered yes to all these questions, then you will love Save the Dog No Ads APK. This is a super fun and creative game that will challenge your brain and make you laugh. In this game, you have to help Doge, the famous internet meme, escape from a swarm of angry bees. How will you do that? Let's find out!

    -

    What is Save the Dog No Ads APK?

    -

    Save the Dog No Ads APK is a modded version of Save the Doge, a popular casual game developed by Miracle Games. The modded version removes all the ads from the original game, making it more enjoyable and less annoying. You can download Save the Dog No Ads APK for free from various websites, such as [PlayMods](^1^).

    -

    save the dog no ads apk


    Download Ziphttps://urlca.com/2uOcji



    -

    The story of Doge and the bees

    -

    The game is based on the famous Doge meme, which is a picture of a Shiba Inu dog with a funny expression. In the game, Doge has offended some bees, and they are out for revenge. A huge swarm of bees will chase Doge and try to sting him. You have to save him by drawing lines on the screen to block the bees' path. You can also use various items, such as bombs, magnets, fans, and more, to help Doge escape.

    -

    The gameplay of Save the Dog No Ads APK

    -

    The game is very simple and intuitive. You just have to swipe your finger on the screen to draw lines or use items. The lines will act as walls that will stop or redirect the bees. The items will have different effects, such as exploding, attracting, or repelling the bees. You have to use your creativity and logic to find the best way to save Doge.

    -

    The game has hundreds of levels with increasing difficulty and variety. Each level has a different scenario, such as a forest, a city, a desert, or a space station. You will also encounter different types of bees, such as normal bees, giant bees, electric bees, or alien bees. You have to adapt your strategy according to each situation.

    -

    The features of Save the Dog No Ads APK

    -

    Save the Dog No Ads APK has many features that make it a fun and creative casual game. Some of these features are:

    -
      -
    • No ads: The modded version removes all the annoying ads from the original game, so you can enjoy it without any interruption.
    • -
    • Unlimited coins: The modded version also gives you unlimited coins, which you can use to buy more items or unlock more levels.
    • -
    • Cute graphics: The game has cute and colorful graphics that will appeal to both kids and adults. The animations are smooth and lively, and the sound effects are funny and realistic.
    • -
    • Funny scenarios: The game has hilarious scenarios that will make you laugh out loud. You will see Doge in various situations, such as riding a bike, flying a rocket, or wearing a cowboy hat.
    • -
    • Creative puzzles: The game has clever puzzles that will challenge your brain and test your skills. You will have to think outside the box and use your imagination to save Doge.
    • -
    -

    Why should you download Save the Dog No Ads APK?

    -

    If you are looking for a casual game that is fun, creative, and ad-free, then you should download Save the Dog No Ads APK. Here are some reasons why you should download Save the Dog No Ads APK:

    -

    It's free and ad-free

    -

    One of the best things about Save the Dog No Ads APK is that it is completely free and ad-free. You don't have to pay anything to download or play the game. You also don't have to worry about annoying ads popping up on your screen and ruining your gaming experience. You can enjoy the game without any distraction or interruption.

    -

    save the doge mod apk no ads
    -download save the dog game without ads
    -save the dog apk free no ads
    -save the dog no ads android game
    -save the doge no ads mod apk download
    -how to play save the dog without ads
    -save the dog game apk mod no ads
    -save the dog no ads version apk
    -save the doge game free download no ads
    -save the dog no ads hack apk
    -save the dog mod apk unlimited coins no ads
    -save the dog no ads premium apk
    -save the doge apk mod free no ads
    -save the dog game online no ads
    -save the dog no ads full apk
    -save the doge game mod apk no ads
    -save the dog apk latest version no ads
    -save the dog no ads cracked apk
    -save the doge free game no ads
    -save the dog mod apk download no ads
    -save the dog no ads unlocked apk
    -save the doge mod apk unlimited money no ads
    -save the dog game for android no ads
    -save the dog no ads pro apk
    -save the doge game apk free no ads
    -save the dog mod apk no root no ads
    -save the dog game offline no ads
    -save the dog no ads paid apk
    -save the doge game hack apk no ads
    -save the dog mod apk ad free
    -save the dog game without advertisements apk
    -save the doge mod apk latest version no ads
    -save the dog app no ads apk
    -save the dog game modded apk no ads
    -save the doge game without annoying ads apk
    -save the dog modded apk download no ads
    -save the dog game cheat apk no ads
    -save the doge game ad free mod apk
    -save the dog hacked apk download no ads
    -save the dog game remove ads apk
    -save the doge game cheat mod apk no ads
    -save the dog unlimited coins apk no ads
    -save the dog game for pc no ads apk
    -save the doge game unlimited gems mod apk no ads
    -save the dog ad free version apk download
    -save the dog game tips and tricks no ads apk
    -save the doge game for ios no ads apk
    -save the dog best mod apk without ads
    -save the dog game review and rating no ads apk

    -

    It's easy and addictive

    -

    Another reason why you should download Save the Dog No Ads APK is that it is very easy and addictive. The game has simple and intuitive controls that anyone can master. You just have to swipe your finger on the screen to draw lines or use items. The game also has a smooth and fast gameplay that will keep you hooked for hours. You will always want to play one more level and save Doge from the bees.

    -

    It's cute and funny

    -

    A third reason why you should download Save the Dog No Ads APK is that it is very cute and funny. The game has adorable and hilarious characters that will make you smile. You will love Doge and his expressions, as well as the bees and their reactions. The game also has witty and humorous dialogues that will make you laugh out loud. The game is a great way to relax and have fun.

    -

    How to download and install Save the Dog No Ads APK?

    -

    If you are convinced that Save the Dog No Ads APK is a game worth playing, then you might be wondering how to download and install it on your device. Don't worry, it's very easy and simple. Just follow these steps:

    -

    Download the APK file from a trusted source

    -

    The first step is to download the APK file of Save the Dog No Ads APK from a trusted source, such as [PlayMods]. You can use any browser on your device to access the website and click on the download button. The file size is about 50 MB, so it won't take long to download.

    -

    Enable unknown sources on your device

    -

    The second step is to enable unknown sources on your device, which will allow you to install apps from sources other than the Google Play Store. To do this, go to your device settings and look for security or privacy options. Then, find the option that says unknown sources or allow installation from unknown sources and turn it on.

    -

    Install the APK file and enjoy the game

    -

    The final step is to install the APK file and enjoy the game. To do this, locate the downloaded file on your device and tap on it. You will see a prompt asking you to confirm the installation. Tap on install and wait for a few seconds. Once the installation is complete, you can open the game and start playing.

    -

    Conclusion

    -

    Save the Dog No Ads APK is a fun and creative casual game that will challenge your brain and make you laugh. In this game, you have to help Doge escape from a swarm of angry bees by drawing lines or using items. The game has hundreds of levels with different scenarios, types of bees, and items. The game also has cute graphics, funny scenarios, creative puzzles, no ads, and unlimited coins. You can download Save the Dog No Ads APK for free from [PlayMods] and enjoy it without any interruption.

    -

    FAQs

    -
      -
    • Q: Is Save the Dog No Ads APK safe to download?
    • -
    • A: Yes, Save the Dog No Ads APK is safe to download from [PlayMods], which is a trusted website that provides modded apps and games. However, you should always be careful when downloading apps from unknown sources and scan them with an antivirus before installing them.
    • -
    • Q: Is Save the Dog No Ads APK compatible with my device?
    • -
    • A: Save the Dog No Ads APK is compatible with most Android devices that run on Android 4.4 or higher. However, some devices may not support some features or functions of the game due to hardware limitations or software issues.
    • -
    • Q: How can I update Save the Dog No Ads APK?
    • -
    • A: To update Save the Dog No Ads APK, you have to visit [PlayMods] again and check if there is a new version available. If there is, you can download it and install it over the old version. Alternatively, you can enable auto-update on your device settings, which will automatically update your apps when there is a new version available.
    • -
    • Q: How can I contact the developer of Save the Dog No Ads APK ?
    • -
    • A: To contact the developer of Save the Dog No Ads APK, you can visit their official website, [Miracle Games], or their Facebook page, [Miracle Games Official]. You can also send them an email at [miraclegames@miraclegames.com]. You can give them your feedback, suggestions, or report any issues or bugs you encounter while playing the game.
    • -
    • Q: What are some similar games to Save the Dog No Ads APK?
    • -
    • A: If you like Save the Dog No Ads APK, you might also like some similar games, such as Draw a Stickman: EPIC 2, Brain Out, Cut the Rope, or Doodle God. These are all fun and creative casual games that will test your logic and imagination.
    • -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/3gp Hindi Rajputani Where to Stream or Download the Movie Online.md b/spaces/contluForse/HuggingGPT/assets/3gp Hindi Rajputani Where to Stream or Download the Movie Online.md deleted file mode 100644 index 7161ba847415fbbdd076dd1ea527efea976953f5..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/3gp Hindi Rajputani Where to Stream or Download the Movie Online.md +++ /dev/null @@ -1,6 +0,0 @@ -

    3gp hindi Rajputani


    DOWNLOAD ———>>> https://ssurll.com/2uzvWy



    -
    - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/contluForse/HuggingGPT/assets/Coolorus Serial.rar PATCHED.md b/spaces/contluForse/HuggingGPT/assets/Coolorus Serial.rar PATCHED.md deleted file mode 100644 index 97b2cb05faadf0d5d399c946a46e1df39e4b6558..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Coolorus Serial.rar PATCHED.md +++ /dev/null @@ -1,5 +0,0 @@ - -

    Coolorus 2.5.14. Libro de etica para pancho pdf

    coolorus free


    Nullpk; 1 year ago; 859 Views.. 0 1.. Coolorus is a color wheel plugin for Adobe® Photoshop®, inspired by Corel® Painter® color picker.

    -

    coolorus serial.rar


    Download File 🗸 https://ssurll.com/2uzxZR



    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Deep Freeze Standard 6 7 Unfreezer.rar __FULL__.md b/spaces/contluForse/HuggingGPT/assets/Deep Freeze Standard 6 7 Unfreezer.rar __FULL__.md deleted file mode 100644 index a6345271d18b4c4a8719575490c50e7d98463613..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Deep Freeze Standard 6 7 Unfreezer.rar __FULL__.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Deep Freeze Standard 6 7 Unfreezer.rar


    Download File >>> https://ssurll.com/2uzw6Q



    - -6.7. Table 2: Population under 15 and over 65 over time (in %). In the 1990s, the decline in production there was even deeper. . 52: 2.~5-.~6 and 2.~9. z-I6.~7. PIERRE (J.K.). "Problems du tra-. "Relaq6es de rar, a. ~3". Nou6be-d.~84. Communications~86, N° 199. Societe d'Histoire de France, N° 107. L'Egalite, No 2, January 1989. L'Europe~74, January-February 1989. 55. "Les Nouvelles de France"~19, June-July 1981. "L'Europe"~83, January-February 1989. "Ditr'es de Paris"~111, March 1986. 76. "Le Moniteur"~3, March 1986. 77. "L'Europe"~213, April 1981. 79. "C'est une grande goutte de fa- . Jean-Charles-Michel, vol. 2. 81. "Le Monde"~1, February 1984. "L'Europe"~80, January-February 1989. 82. 8a78ff9644
    -
    -
    -

    diff --git a/spaces/contluForse/HuggingGPT/assets/EDD-202 (Yua Sakuya) 74.md b/spaces/contluForse/HuggingGPT/assets/EDD-202 (Yua Sakuya) 74.md deleted file mode 100644 index 575c24c9f404701e7e4cb44cf87aa55054bab358..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/EDD-202 (Yua Sakuya) 74.md +++ /dev/null @@ -1,6 +0,0 @@ -

    EDD-202 (Yua Sakuya) 74


    Download Ziphttps://ssurll.com/2uzxik



    -
    - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/cnn/bricks/__init__.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/cnn/bricks/__init__.py deleted file mode 100644 index 0f33124ed23fc6f27119a37bcb5ab004d3572be0..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/cnn/bricks/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .activation import build_activation_layer -from .context_block import ContextBlock -from .conv import build_conv_layer -from .conv2d_adaptive_padding import Conv2dAdaptivePadding -from .conv_module import ConvModule -from .conv_ws import ConvAWS2d, ConvWS2d, conv_ws_2d -from .depthwise_separable_conv_module import DepthwiseSeparableConvModule -from .drop import Dropout, DropPath -from .generalized_attention import GeneralizedAttention -from .hsigmoid import HSigmoid -from .hswish import HSwish -from .non_local import NonLocal1d, NonLocal2d, NonLocal3d -from .norm import build_norm_layer, is_norm -from .padding import build_padding_layer -from .plugin import build_plugin_layer -from .registry import (ACTIVATION_LAYERS, CONV_LAYERS, NORM_LAYERS, - PADDING_LAYERS, PLUGIN_LAYERS, UPSAMPLE_LAYERS) -from .scale import Scale -from .swish import Swish -from .upsample import build_upsample_layer -from .wrappers import (Conv2d, Conv3d, ConvTranspose2d, ConvTranspose3d, - Linear, MaxPool2d, MaxPool3d) - -__all__ = [ - 'ConvModule', 'build_activation_layer', 'build_conv_layer', - 'build_norm_layer', 'build_padding_layer', 'build_upsample_layer', - 'build_plugin_layer', 'is_norm', 'HSigmoid', 'HSwish', 'NonLocal1d', - 'NonLocal2d', 'NonLocal3d', 'ContextBlock', 'GeneralizedAttention', - 'ACTIVATION_LAYERS', 'CONV_LAYERS', 'NORM_LAYERS', 'PADDING_LAYERS', - 'UPSAMPLE_LAYERS', 'PLUGIN_LAYERS', 'Scale', 'ConvAWS2d', 'ConvWS2d', - 'conv_ws_2d', 'DepthwiseSeparableConvModule', 'Swish', 'Linear', - 'Conv2dAdaptivePadding', 'Conv2d', 'ConvTranspose2d', 'MaxPool2d', - 'ConvTranspose3d', 'MaxPool3d', 'Conv3d', 'Dropout', 'DropPath' -] diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/modeling/anchor_generator.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/modeling/anchor_generator.py deleted file mode 100644 index 04127c4af440b4623427b4c0911ee299166d1d7d..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/modeling/anchor_generator.py +++ /dev/null @@ -1,386 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import collections -import math -from typing import List -import torch -from torch import nn - -from annotator.oneformer.detectron2.config import configurable -from annotator.oneformer.detectron2.layers import ShapeSpec, move_device_like -from annotator.oneformer.detectron2.structures import Boxes, RotatedBoxes -from annotator.oneformer.detectron2.utils.registry import Registry - -ANCHOR_GENERATOR_REGISTRY = Registry("ANCHOR_GENERATOR") -ANCHOR_GENERATOR_REGISTRY.__doc__ = """ -Registry for modules that creates object detection anchors for feature maps. - -The registered object will be called with `obj(cfg, input_shape)`. -""" - - -class BufferList(nn.Module): - """ - Similar to nn.ParameterList, but for buffers - """ - - def __init__(self, buffers): - super().__init__() - for i, buffer in enumerate(buffers): - # Use non-persistent buffer so the values are not saved in checkpoint - self.register_buffer(str(i), buffer, persistent=False) - - def __len__(self): - return len(self._buffers) - - def __iter__(self): - return iter(self._buffers.values()) - - -def _create_grid_offsets( - size: List[int], stride: int, offset: float, target_device_tensor: torch.Tensor -): - grid_height, grid_width = size - shifts_x = move_device_like( - torch.arange(offset * stride, grid_width * stride, step=stride, dtype=torch.float32), - target_device_tensor, - ) - shifts_y = move_device_like( - torch.arange(offset * stride, grid_height * stride, step=stride, dtype=torch.float32), - target_device_tensor, - ) - - shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) - shift_x = shift_x.reshape(-1) - shift_y = shift_y.reshape(-1) - return shift_x, shift_y - - -def _broadcast_params(params, num_features, name): - """ - If one size (or aspect ratio) is specified and there are multiple feature - maps, we "broadcast" anchors of that single size (or aspect ratio) - over all feature maps. - - If params is list[float], or list[list[float]] with len(params) == 1, repeat - it num_features time. - - Returns: - list[list[float]]: param for each feature - """ - assert isinstance( - params, collections.abc.Sequence - ), f"{name} in anchor generator has to be a list! Got {params}." - assert len(params), f"{name} in anchor generator cannot be empty!" - if not isinstance(params[0], collections.abc.Sequence): # params is list[float] - return [params] * num_features - if len(params) == 1: - return list(params) * num_features - assert len(params) == num_features, ( - f"Got {name} of length {len(params)} in anchor generator, " - f"but the number of input features is {num_features}!" - ) - return params - - -@ANCHOR_GENERATOR_REGISTRY.register() -class DefaultAnchorGenerator(nn.Module): - """ - Compute anchors in the standard ways described in - "Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks". - """ - - box_dim: torch.jit.Final[int] = 4 - """ - the dimension of each anchor box. - """ - - @configurable - def __init__(self, *, sizes, aspect_ratios, strides, offset=0.5): - """ - This interface is experimental. - - Args: - sizes (list[list[float]] or list[float]): - If ``sizes`` is list[list[float]], ``sizes[i]`` is the list of anchor sizes - (i.e. sqrt of anchor area) to use for the i-th feature map. - If ``sizes`` is list[float], ``sizes`` is used for all feature maps. - Anchor sizes are given in absolute lengths in units of - the input image; they do not dynamically scale if the input image size changes. - aspect_ratios (list[list[float]] or list[float]): list of aspect ratios - (i.e. height / width) to use for anchors. Same "broadcast" rule for `sizes` applies. - strides (list[int]): stride of each input feature. - offset (float): Relative offset between the center of the first anchor and the top-left - corner of the image. Value has to be in [0, 1). - Recommend to use 0.5, which means half stride. - """ - super().__init__() - - self.strides = strides - self.num_features = len(self.strides) - sizes = _broadcast_params(sizes, self.num_features, "sizes") - aspect_ratios = _broadcast_params(aspect_ratios, self.num_features, "aspect_ratios") - self.cell_anchors = self._calculate_anchors(sizes, aspect_ratios) - - self.offset = offset - assert 0.0 <= self.offset < 1.0, self.offset - - @classmethod - def from_config(cls, cfg, input_shape: List[ShapeSpec]): - return { - "sizes": cfg.MODEL.ANCHOR_GENERATOR.SIZES, - "aspect_ratios": cfg.MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS, - "strides": [x.stride for x in input_shape], - "offset": cfg.MODEL.ANCHOR_GENERATOR.OFFSET, - } - - def _calculate_anchors(self, sizes, aspect_ratios): - cell_anchors = [ - self.generate_cell_anchors(s, a).float() for s, a in zip(sizes, aspect_ratios) - ] - return BufferList(cell_anchors) - - @property - @torch.jit.unused - def num_cell_anchors(self): - """ - Alias of `num_anchors`. - """ - return self.num_anchors - - @property - @torch.jit.unused - def num_anchors(self): - """ - Returns: - list[int]: Each int is the number of anchors at every pixel - location, on that feature map. - For example, if at every pixel we use anchors of 3 aspect - ratios and 5 sizes, the number of anchors is 15. - (See also ANCHOR_GENERATOR.SIZES and ANCHOR_GENERATOR.ASPECT_RATIOS in config) - - In standard RPN models, `num_anchors` on every feature map is the same. - """ - return [len(cell_anchors) for cell_anchors in self.cell_anchors] - - def _grid_anchors(self, grid_sizes: List[List[int]]): - """ - Returns: - list[Tensor]: #featuremap tensors, each is (#locations x #cell_anchors) x 4 - """ - anchors = [] - # buffers() not supported by torchscript. use named_buffers() instead - buffers: List[torch.Tensor] = [x[1] for x in self.cell_anchors.named_buffers()] - for size, stride, base_anchors in zip(grid_sizes, self.strides, buffers): - shift_x, shift_y = _create_grid_offsets(size, stride, self.offset, base_anchors) - shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1) - - anchors.append((shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)) - - return anchors - - def generate_cell_anchors(self, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2)): - """ - Generate a tensor storing canonical anchor boxes, which are all anchor - boxes of different sizes and aspect_ratios centered at (0, 0). - We can later build the set of anchors for a full feature map by - shifting and tiling these tensors (see `meth:_grid_anchors`). - - Args: - sizes (tuple[float]): - aspect_ratios (tuple[float]]): - - Returns: - Tensor of shape (len(sizes) * len(aspect_ratios), 4) storing anchor boxes - in XYXY format. - """ - - # This is different from the anchor generator defined in the original Faster R-CNN - # code or Detectron. They yield the same AP, however the old version defines cell - # anchors in a less natural way with a shift relative to the feature grid and - # quantization that results in slightly different sizes for different aspect ratios. - # See also https://github.com/facebookresearch/Detectron/issues/227 - - anchors = [] - for size in sizes: - area = size**2.0 - for aspect_ratio in aspect_ratios: - # s * s = w * h - # a = h / w - # ... some algebra ... - # w = sqrt(s * s / a) - # h = a * w - w = math.sqrt(area / aspect_ratio) - h = aspect_ratio * w - x0, y0, x1, y1 = -w / 2.0, -h / 2.0, w / 2.0, h / 2.0 - anchors.append([x0, y0, x1, y1]) - return torch.tensor(anchors) - - def forward(self, features: List[torch.Tensor]): - """ - Args: - features (list[Tensor]): list of backbone feature maps on which to generate anchors. - - Returns: - list[Boxes]: a list of Boxes containing all the anchors for each feature map - (i.e. the cell anchors repeated over all locations in the feature map). - The number of anchors of each feature map is Hi x Wi x num_cell_anchors, - where Hi, Wi are resolution of the feature map divided by anchor stride. - """ - grid_sizes = [feature_map.shape[-2:] for feature_map in features] - anchors_over_all_feature_maps = self._grid_anchors(grid_sizes) - return [Boxes(x) for x in anchors_over_all_feature_maps] - - -@ANCHOR_GENERATOR_REGISTRY.register() -class RotatedAnchorGenerator(nn.Module): - """ - Compute rotated anchors used by Rotated RPN (RRPN), described in - "Arbitrary-Oriented Scene Text Detection via Rotation Proposals". - """ - - box_dim: int = 5 - """ - the dimension of each anchor box. - """ - - @configurable - def __init__(self, *, sizes, aspect_ratios, strides, angles, offset=0.5): - """ - This interface is experimental. - - Args: - sizes (list[list[float]] or list[float]): - If sizes is list[list[float]], sizes[i] is the list of anchor sizes - (i.e. sqrt of anchor area) to use for the i-th feature map. - If sizes is list[float], the sizes are used for all feature maps. - Anchor sizes are given in absolute lengths in units of - the input image; they do not dynamically scale if the input image size changes. - aspect_ratios (list[list[float]] or list[float]): list of aspect ratios - (i.e. height / width) to use for anchors. Same "broadcast" rule for `sizes` applies. - strides (list[int]): stride of each input feature. - angles (list[list[float]] or list[float]): list of angles (in degrees CCW) - to use for anchors. Same "broadcast" rule for `sizes` applies. - offset (float): Relative offset between the center of the first anchor and the top-left - corner of the image. Value has to be in [0, 1). - Recommend to use 0.5, which means half stride. - """ - super().__init__() - - self.strides = strides - self.num_features = len(self.strides) - sizes = _broadcast_params(sizes, self.num_features, "sizes") - aspect_ratios = _broadcast_params(aspect_ratios, self.num_features, "aspect_ratios") - angles = _broadcast_params(angles, self.num_features, "angles") - self.cell_anchors = self._calculate_anchors(sizes, aspect_ratios, angles) - - self.offset = offset - assert 0.0 <= self.offset < 1.0, self.offset - - @classmethod - def from_config(cls, cfg, input_shape: List[ShapeSpec]): - return { - "sizes": cfg.MODEL.ANCHOR_GENERATOR.SIZES, - "aspect_ratios": cfg.MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS, - "strides": [x.stride for x in input_shape], - "offset": cfg.MODEL.ANCHOR_GENERATOR.OFFSET, - "angles": cfg.MODEL.ANCHOR_GENERATOR.ANGLES, - } - - def _calculate_anchors(self, sizes, aspect_ratios, angles): - cell_anchors = [ - self.generate_cell_anchors(size, aspect_ratio, angle).float() - for size, aspect_ratio, angle in zip(sizes, aspect_ratios, angles) - ] - return BufferList(cell_anchors) - - @property - def num_cell_anchors(self): - """ - Alias of `num_anchors`. - """ - return self.num_anchors - - @property - def num_anchors(self): - """ - Returns: - list[int]: Each int is the number of anchors at every pixel - location, on that feature map. - For example, if at every pixel we use anchors of 3 aspect - ratios, 2 sizes and 5 angles, the number of anchors is 30. - (See also ANCHOR_GENERATOR.SIZES, ANCHOR_GENERATOR.ASPECT_RATIOS - and ANCHOR_GENERATOR.ANGLES in config) - - In standard RRPN models, `num_anchors` on every feature map is the same. - """ - return [len(cell_anchors) for cell_anchors in self.cell_anchors] - - def _grid_anchors(self, grid_sizes): - anchors = [] - for size, stride, base_anchors in zip(grid_sizes, self.strides, self.cell_anchors): - shift_x, shift_y = _create_grid_offsets(size, stride, self.offset, base_anchors) - zeros = torch.zeros_like(shift_x) - shifts = torch.stack((shift_x, shift_y, zeros, zeros, zeros), dim=1) - - anchors.append((shifts.view(-1, 1, 5) + base_anchors.view(1, -1, 5)).reshape(-1, 5)) - - return anchors - - def generate_cell_anchors( - self, - sizes=(32, 64, 128, 256, 512), - aspect_ratios=(0.5, 1, 2), - angles=(-90, -60, -30, 0, 30, 60, 90), - ): - """ - Generate a tensor storing canonical anchor boxes, which are all anchor - boxes of different sizes, aspect_ratios, angles centered at (0, 0). - We can later build the set of anchors for a full feature map by - shifting and tiling these tensors (see `meth:_grid_anchors`). - - Args: - sizes (tuple[float]): - aspect_ratios (tuple[float]]): - angles (tuple[float]]): - - Returns: - Tensor of shape (len(sizes) * len(aspect_ratios) * len(angles), 5) - storing anchor boxes in (x_ctr, y_ctr, w, h, angle) format. - """ - anchors = [] - for size in sizes: - area = size**2.0 - for aspect_ratio in aspect_ratios: - # s * s = w * h - # a = h / w - # ... some algebra ... - # w = sqrt(s * s / a) - # h = a * w - w = math.sqrt(area / aspect_ratio) - h = aspect_ratio * w - anchors.extend([0, 0, w, h, a] for a in angles) - - return torch.tensor(anchors) - - def forward(self, features): - """ - Args: - features (list[Tensor]): list of backbone feature maps on which to generate anchors. - - Returns: - list[RotatedBoxes]: a list of Boxes containing all the anchors for each feature map - (i.e. the cell anchors repeated over all locations in the feature map). - The number of anchors of each feature map is Hi x Wi x num_cell_anchors, - where Hi, Wi are resolution of the feature map divided by anchor stride. - """ - grid_sizes = [feature_map.shape[-2:] for feature_map in features] - anchors_over_all_feature_maps = self._grid_anchors(grid_sizes) - return [RotatedBoxes(x) for x in anchors_over_all_feature_maps] - - -def build_anchor_generator(cfg, input_shape): - """ - Built an anchor generator from `cfg.MODEL.ANCHOR_GENERATOR.NAME`. - """ - anchor_generator = cfg.MODEL.ANCHOR_GENERATOR.NAME - return ANCHOR_GENERATOR_REGISTRY.get(anchor_generator)(cfg, input_shape) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmcv/visualization/color.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmcv/visualization/color.py deleted file mode 100644 index 9041e0e6b7581c3356795d6a3c5e84667c88f025..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmcv/visualization/color.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from enum import Enum - -import numpy as np - -from annotator.uniformer.mmcv.utils import is_str - - -class Color(Enum): - """An enum that defines common colors. - - Contains red, green, blue, cyan, yellow, magenta, white and black. - """ - red = (0, 0, 255) - green = (0, 255, 0) - blue = (255, 0, 0) - cyan = (255, 255, 0) - yellow = (0, 255, 255) - magenta = (255, 0, 255) - white = (255, 255, 255) - black = (0, 0, 0) - - -def color_val(color): - """Convert various input to color tuples. - - Args: - color (:obj:`Color`/str/tuple/int/ndarray): Color inputs - - Returns: - tuple[int]: A tuple of 3 integers indicating BGR channels. - """ - if is_str(color): - return Color[color].value - elif isinstance(color, Color): - return color.value - elif isinstance(color, tuple): - assert len(color) == 3 - for channel in color: - assert 0 <= channel <= 255 - return color - elif isinstance(color, int): - assert 0 <= color <= 255 - return color, color, color - elif isinstance(color, np.ndarray): - assert color.ndim == 1 and color.size == 3 - assert np.all((color >= 0) & (color <= 255)) - color = color.astype(np.uint8) - return tuple(color) - else: - raise TypeError(f'Invalid type for color: {type(color)}') diff --git a/spaces/cownclown/Image-and-3D-Model-Creator/PIFu/lib/net_util.py b/spaces/cownclown/Image-and-3D-Model-Creator/PIFu/lib/net_util.py deleted file mode 100644 index 3345c10335a0216c5ca3b3c02300911600771b52..0000000000000000000000000000000000000000 --- a/spaces/cownclown/Image-and-3D-Model-Creator/PIFu/lib/net_util.py +++ /dev/null @@ -1,396 +0,0 @@ -import torch -from torch.nn import init -import torch.nn as nn -import torch.nn.functional as F -import functools - -import numpy as np -from .mesh_util import * -from .sample_util import * -from .geometry import index -import cv2 -from PIL import Image -from tqdm import tqdm - - -def reshape_multiview_tensors(image_tensor, calib_tensor): - # Careful here! Because we put single view and multiview together, - # the returned tensor.shape is 5-dim: [B, num_views, C, W, H] - # So we need to convert it back to 4-dim [B*num_views, C, W, H] - # Don't worry classifier will handle multi-view cases - image_tensor = image_tensor.view( - image_tensor.shape[0] * image_tensor.shape[1], - image_tensor.shape[2], - image_tensor.shape[3], - image_tensor.shape[4] - ) - calib_tensor = calib_tensor.view( - calib_tensor.shape[0] * calib_tensor.shape[1], - calib_tensor.shape[2], - calib_tensor.shape[3] - ) - - return image_tensor, calib_tensor - - -def reshape_sample_tensor(sample_tensor, num_views): - if num_views == 1: - return sample_tensor - # Need to repeat sample_tensor along the batch dim num_views times - sample_tensor = sample_tensor.unsqueeze(dim=1) - sample_tensor = sample_tensor.repeat(1, num_views, 1, 1) - sample_tensor = sample_tensor.view( - sample_tensor.shape[0] * sample_tensor.shape[1], - sample_tensor.shape[2], - sample_tensor.shape[3] - ) - return sample_tensor - - -def gen_mesh(opt, net, cuda, data, save_path, use_octree=True): - image_tensor = data['img'].to(device=cuda) - calib_tensor = data['calib'].to(device=cuda) - - net.filter(image_tensor) - - b_min = data['b_min'] - b_max = data['b_max'] - try: - save_img_path = save_path[:-4] + '.png' - save_img_list = [] - for v in range(image_tensor.shape[0]): - save_img = (np.transpose(image_tensor[v].detach().cpu().numpy(), (1, 2, 0)) * 0.5 + 0.5)[:, :, ::-1] * 255.0 - save_img_list.append(save_img) - save_img = np.concatenate(save_img_list, axis=1) - Image.fromarray(np.uint8(save_img[:,:,::-1])).save(save_img_path) - - verts, faces, _, _ = reconstruction( - net, cuda, calib_tensor, opt.resolution, b_min, b_max, use_octree=use_octree) - verts_tensor = torch.from_numpy(verts.T).unsqueeze(0).to(device=cuda).float() - xyz_tensor = net.projection(verts_tensor, calib_tensor[:1]) - uv = xyz_tensor[:, :2, :] - color = index(image_tensor[:1], uv).detach().cpu().numpy()[0].T - color = color * 0.5 + 0.5 - save_obj_mesh_with_color(save_path, verts, faces, color) - except Exception as e: - print(e) - print('Can not create marching cubes at this time.') - -def gen_mesh_color(opt, netG, netC, cuda, data, save_path, use_octree=True): - image_tensor = data['img'].to(device=cuda) - calib_tensor = data['calib'].to(device=cuda) - - netG.filter(image_tensor) - netC.filter(image_tensor) - netC.attach(netG.get_im_feat()) - - b_min = data['b_min'] - b_max = data['b_max'] - try: - save_img_path = save_path[:-4] + '.png' - save_img_list = [] - for v in range(image_tensor.shape[0]): - save_img = (np.transpose(image_tensor[v].detach().cpu().numpy(), (1, 2, 0)) * 0.5 + 0.5)[:, :, ::-1] * 255.0 - save_img_list.append(save_img) - save_img = np.concatenate(save_img_list, axis=1) - Image.fromarray(np.uint8(save_img[:,:,::-1])).save(save_img_path) - - verts, faces, _, _ = reconstruction( - netG, cuda, calib_tensor, opt.resolution, b_min, b_max, use_octree=use_octree) - - # Now Getting colors - verts_tensor = torch.from_numpy(verts.T).unsqueeze(0).to(device=cuda).float() - verts_tensor = reshape_sample_tensor(verts_tensor, opt.num_views) - - color = np.zeros(verts.shape) - interval = opt.num_sample_color - for i in range(len(color) // interval): - left = i * interval - right = i * interval + interval - if i == len(color) // interval - 1: - right = -1 - netC.query(verts_tensor[:, :, left:right], calib_tensor) - rgb = netC.get_preds()[0].detach().cpu().numpy() * 0.5 + 0.5 - color[left:right] = rgb.T - - save_obj_mesh_with_color(save_path, verts, faces, color) - except Exception as e: - print(e) - print('Can not create marching cubes at this time.') - -def adjust_learning_rate(optimizer, epoch, lr, schedule, gamma): - """Sets the learning rate to the initial LR decayed by schedule""" - if epoch in schedule: - lr *= gamma - for param_group in optimizer.param_groups: - param_group['lr'] = lr - return lr - - -def compute_acc(pred, gt, thresh=0.5): - ''' - return: - IOU, precision, and recall - ''' - with torch.no_grad(): - vol_pred = pred > thresh - vol_gt = gt > thresh - - union = vol_pred | vol_gt - inter = vol_pred & vol_gt - - true_pos = inter.sum().float() - - union = union.sum().float() - if union == 0: - union = 1 - vol_pred = vol_pred.sum().float() - if vol_pred == 0: - vol_pred = 1 - vol_gt = vol_gt.sum().float() - if vol_gt == 0: - vol_gt = 1 - return true_pos / union, true_pos / vol_pred, true_pos / vol_gt - - -def calc_error(opt, net, cuda, dataset, num_tests): - if num_tests > len(dataset): - num_tests = len(dataset) - with torch.no_grad(): - erorr_arr, IOU_arr, prec_arr, recall_arr = [], [], [], [] - for idx in tqdm(range(num_tests)): - data = dataset[idx * len(dataset) // num_tests] - # retrieve the data - image_tensor = data['img'].to(device=cuda) - calib_tensor = data['calib'].to(device=cuda) - sample_tensor = data['samples'].to(device=cuda).unsqueeze(0) - if opt.num_views > 1: - sample_tensor = reshape_sample_tensor(sample_tensor, opt.num_views) - label_tensor = data['labels'].to(device=cuda).unsqueeze(0) - - res, error = net.forward(image_tensor, sample_tensor, calib_tensor, labels=label_tensor) - - IOU, prec, recall = compute_acc(res, label_tensor) - - # print( - # '{0}/{1} | Error: {2:06f} IOU: {3:06f} prec: {4:06f} recall: {5:06f}' - # .format(idx, num_tests, error.item(), IOU.item(), prec.item(), recall.item())) - erorr_arr.append(error.item()) - IOU_arr.append(IOU.item()) - prec_arr.append(prec.item()) - recall_arr.append(recall.item()) - - return np.average(erorr_arr), np.average(IOU_arr), np.average(prec_arr), np.average(recall_arr) - -def calc_error_color(opt, netG, netC, cuda, dataset, num_tests): - if num_tests > len(dataset): - num_tests = len(dataset) - with torch.no_grad(): - error_color_arr = [] - - for idx in tqdm(range(num_tests)): - data = dataset[idx * len(dataset) // num_tests] - # retrieve the data - image_tensor = data['img'].to(device=cuda) - calib_tensor = data['calib'].to(device=cuda) - color_sample_tensor = data['color_samples'].to(device=cuda).unsqueeze(0) - - if opt.num_views > 1: - color_sample_tensor = reshape_sample_tensor(color_sample_tensor, opt.num_views) - - rgb_tensor = data['rgbs'].to(device=cuda).unsqueeze(0) - - netG.filter(image_tensor) - _, errorC = netC.forward(image_tensor, netG.get_im_feat(), color_sample_tensor, calib_tensor, labels=rgb_tensor) - - # print('{0}/{1} | Error inout: {2:06f} | Error color: {3:06f}' - # .format(idx, num_tests, errorG.item(), errorC.item())) - error_color_arr.append(errorC.item()) - - return np.average(error_color_arr) - - -def conv3x3(in_planes, out_planes, strd=1, padding=1, bias=False): - "3x3 convolution with padding" - return nn.Conv2d(in_planes, out_planes, kernel_size=3, - stride=strd, padding=padding, bias=bias) - -def init_weights(net, init_type='normal', init_gain=0.02): - """Initialize network weights. - - Parameters: - net (network) -- network to be initialized - init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal - init_gain (float) -- scaling factor for normal, xavier and orthogonal. - - We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might - work better for some applications. Feel free to try yourself. - """ - - def init_func(m): # define the initialization function - classname = m.__class__.__name__ - if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): - if init_type == 'normal': - init.normal_(m.weight.data, 0.0, init_gain) - elif init_type == 'xavier': - init.xavier_normal_(m.weight.data, gain=init_gain) - elif init_type == 'kaiming': - init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') - elif init_type == 'orthogonal': - init.orthogonal_(m.weight.data, gain=init_gain) - else: - raise NotImplementedError('initialization method [%s] is not implemented' % init_type) - if hasattr(m, 'bias') and m.bias is not None: - init.constant_(m.bias.data, 0.0) - elif classname.find( - 'BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies. - init.normal_(m.weight.data, 1.0, init_gain) - init.constant_(m.bias.data, 0.0) - - print('initialize network with %s' % init_type) - net.apply(init_func) # apply the initialization function - - -def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): - """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights - Parameters: - net (network) -- the network to be initialized - init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal - gain (float) -- scaling factor for normal, xavier and orthogonal. - gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 - - Return an initialized network. - """ - if len(gpu_ids) > 0: - assert (torch.cuda.is_available()) - net.to(gpu_ids[0]) - net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs - init_weights(net, init_type, init_gain=init_gain) - return net - - -def imageSpaceRotation(xy, rot): - ''' - args: - xy: (B, 2, N) input - rot: (B, 2) x,y axis rotation angles - - rotation center will be always image center (other rotation center can be represented by additional z translation) - ''' - disp = rot.unsqueeze(2).sin().expand_as(xy) - return (disp * xy).sum(dim=1) - - -def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0): - """Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 - - Arguments: - netD (network) -- discriminator network - real_data (tensor array) -- real images - fake_data (tensor array) -- generated images from the generator - device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') - type (str) -- if we mix real and fake data or not [real | fake | mixed]. - constant (float) -- the constant used in formula ( | |gradient||_2 - constant)^2 - lambda_gp (float) -- weight for this loss - - Returns the gradient penalty loss - """ - if lambda_gp > 0.0: - if type == 'real': # either use real images, fake images, or a linear interpolation of two. - interpolatesv = real_data - elif type == 'fake': - interpolatesv = fake_data - elif type == 'mixed': - alpha = torch.rand(real_data.shape[0], 1) - alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view( - *real_data.shape) - alpha = alpha.to(device) - interpolatesv = alpha * real_data + ((1 - alpha) * fake_data) - else: - raise NotImplementedError('{} not implemented'.format(type)) - interpolatesv.requires_grad_(True) - disc_interpolates = netD(interpolatesv) - gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv, - grad_outputs=torch.ones(disc_interpolates.size()).to(device), - create_graph=True, retain_graph=True, only_inputs=True) - gradients = gradients[0].view(real_data.size(0), -1) # flat the data - gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps - return gradient_penalty, gradients - else: - return 0.0, None - -def get_norm_layer(norm_type='instance'): - """Return a normalization layer - Parameters: - norm_type (str) -- the name of the normalization layer: batch | instance | none - For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). - For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. - """ - if norm_type == 'batch': - norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True) - elif norm_type == 'instance': - norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) - elif norm_type == 'group': - norm_layer = functools.partial(nn.GroupNorm, 32) - elif norm_type == 'none': - norm_layer = None - else: - raise NotImplementedError('normalization layer [%s] is not found' % norm_type) - return norm_layer - -class Flatten(nn.Module): - def forward(self, input): - return input.view(input.size(0), -1) - -class ConvBlock(nn.Module): - def __init__(self, in_planes, out_planes, norm='batch'): - super(ConvBlock, self).__init__() - self.conv1 = conv3x3(in_planes, int(out_planes / 2)) - self.conv2 = conv3x3(int(out_planes / 2), int(out_planes / 4)) - self.conv3 = conv3x3(int(out_planes / 4), int(out_planes / 4)) - - if norm == 'batch': - self.bn1 = nn.BatchNorm2d(in_planes) - self.bn2 = nn.BatchNorm2d(int(out_planes / 2)) - self.bn3 = nn.BatchNorm2d(int(out_planes / 4)) - self.bn4 = nn.BatchNorm2d(in_planes) - elif norm == 'group': - self.bn1 = nn.GroupNorm(32, in_planes) - self.bn2 = nn.GroupNorm(32, int(out_planes / 2)) - self.bn3 = nn.GroupNorm(32, int(out_planes / 4)) - self.bn4 = nn.GroupNorm(32, in_planes) - - if in_planes != out_planes: - self.downsample = nn.Sequential( - self.bn4, - nn.ReLU(True), - nn.Conv2d(in_planes, out_planes, - kernel_size=1, stride=1, bias=False), - ) - else: - self.downsample = None - - def forward(self, x): - residual = x - - out1 = self.bn1(x) - out1 = F.relu(out1, True) - out1 = self.conv1(out1) - - out2 = self.bn2(out1) - out2 = F.relu(out2, True) - out2 = self.conv2(out2) - - out3 = self.bn3(out2) - out3 = F.relu(out3, True) - out3 = self.conv3(out3) - - out3 = torch.cat((out1, out2, out3), 1) - - if self.downsample is not None: - residual = self.downsample(residual) - - out3 += residual - - return out3 - \ No newline at end of file diff --git a/spaces/crashedice/signify/SOURCE/vgg_finetuned_model/vgg_verify.py b/spaces/crashedice/signify/SOURCE/vgg_finetuned_model/vgg_verify.py deleted file mode 100644 index 66f757a4e97e872631fca8b23d62883d6711aea9..0000000000000000000000000000000000000000 --- a/spaces/crashedice/signify/SOURCE/vgg_finetuned_model/vgg_verify.py +++ /dev/null @@ -1,50 +0,0 @@ -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import tensorflow as tf -from tensorflow.keras.preprocessing import image -from tensorflow.keras.applications.vgg16 import preprocess_input -from tensorflow.keras.preprocessing.image import ImageDataGenerator -from sklearn.metrics.pairwise import cosine_similarity -import os -import cv2 - -def make_square(path): - ''' Reize the image to 256x256 dimension ''' - image = cv2.imread(path) - image = cv2.resize(image, (256, 256)) - cv2.imwrite('media/image.png', image) - -def load_image(image_path): - ''' Return the image in the format required by VGG16 model. ''' - img = image.load_img(image_path, target_size=(224, 224)) - x = image.img_to_array(img) - x = np.expand_dims(x, axis=0) - x = preprocess_input(x) - return x - -def extract_features(feature_extractor, image): - ''' Returns the features extracted by the model. ''' - return feature_extractor.predict(load_image(image)) - -def cosine_similarity_fn(anchor_image_feature, test_image_feature): - ''' Returns the features extracted by the model. ''' - return cosine_similarity(anchor_image_feature, test_image_feature)[0][0] - - -def verify(anchor_image, gan_op): - # loads the model and removes the last layer is removed - vgg_model = tf.keras.models.load_model('SOURCE/vgg_finetuned_model') - feature_extractor = tf.keras.Sequential(vgg_model.layers[:-1]) - - feature_set = [] - # anchor image is resized to 256x256 to match outputs from gan. - make_square(anchor_image) - anchor_image_feature = extract_features(feature_extractor, anchor_image) - test_images = [gan_op + image for image in os.listdir(gan_op) if image[2:6]=='fake'] - for image in test_images: - test_image_feature = extract_features(feature_extractor, image) - cosine_similarity = cosine_similarity_fn(anchor_image_feature, test_image_feature) - cosine_similarity = round(cosine_similarity, 2) - feature_set.append([image, cosine_similarity]) - return feature_set diff --git a/spaces/dakaiye/dky_xuexi/multi_language.py b/spaces/dakaiye/dky_xuexi/multi_language.py deleted file mode 100644 index 6c7259836e69d7bc5724a301883a9dbf1526589a..0000000000000000000000000000000000000000 --- a/spaces/dakaiye/dky_xuexi/multi_language.py +++ /dev/null @@ -1,510 +0,0 @@ -""" - Translate this project to other languages (experimental, please open an issue if there is any bug) - - - Usage: - 1. modify LANG - LANG = "English" - - 2. modify TransPrompt - TransPrompt = f"Replace each json value `#` with translated results in English, e.g., \"原始文本\":\"TranslatedText\". Keep Json format. Do not answer #." - - 3. Run `python multi_language.py`. - Note: You need to run it multiple times to increase translation coverage because GPT makes mistakes sometimes. - - 4. Find the translated program in `multi-language\English\*` - - P.S. - - - The translation mapping will be stored in `docs/translation_xxxx.json`, you can revised mistaken translation there. - - - If you would like to share your `docs/translation_xxxx.json`, (so that everyone can use the cached & revised translation mapping), please open a Pull Request - - - If there is any translation error in `docs/translation_xxxx.json`, please open a Pull Request - - - Welcome any Pull Request, regardless of language -""" - -import os -import json -import functools -import re -import pickle -import time - -CACHE_FOLDER = "gpt_log" -blacklist = ['multi-language', 'gpt_log', '.git', 'private_upload', 'multi_language.py'] - -# LANG = "TraditionalChinese" -# TransPrompt = f"Replace each json value `#` with translated results in Traditional Chinese, e.g., \"原始文本\":\"翻譯後文字\". Keep Json format. Do not answer #." - -# LANG = "Japanese" -# TransPrompt = f"Replace each json value `#` with translated results in Japanese, e.g., \"原始文本\":\"テキストの翻訳\". Keep Json format. Do not answer #." - -LANG = "English" -TransPrompt = f"Replace each json value `#` with translated results in English, e.g., \"原始文本\":\"TranslatedText\". Keep Json format. Do not answer #." - - -if not os.path.exists(CACHE_FOLDER): - os.makedirs(CACHE_FOLDER) - - -def lru_file_cache(maxsize=128, ttl=None, filename=None): - """ - Decorator that caches a function's return value after being called with given arguments. - It uses a Least Recently Used (LRU) cache strategy to limit the size of the cache. - maxsize: Maximum size of the cache. Defaults to 128. - ttl: Time-to-Live of the cache. If a value hasn't been accessed for `ttl` seconds, it will be evicted from the cache. - filename: Name of the file to store the cache in. If not supplied, the function name + ".cache" will be used. - """ - cache_path = os.path.join(CACHE_FOLDER, f"{filename}.cache") if filename is not None else None - - def decorator_function(func): - cache = {} - _cache_info = { - "hits": 0, - "misses": 0, - "maxsize": maxsize, - "currsize": 0, - "ttl": ttl, - "filename": cache_path, - } - - @functools.wraps(func) - def wrapper_function(*args, **kwargs): - key = str((args, frozenset(kwargs))) - if key in cache: - if _cache_info["ttl"] is None or (cache[key][1] + _cache_info["ttl"]) >= time.time(): - _cache_info["hits"] += 1 - print(f'Warning, reading cache, last read {(time.time()-cache[key][1])//60} minutes ago'); time.sleep(2) - cache[key][1] = time.time() - return cache[key][0] - else: - del cache[key] - - result = func(*args, **kwargs) - cache[key] = [result, time.time()] - _cache_info["misses"] += 1 - _cache_info["currsize"] += 1 - - if _cache_info["currsize"] > _cache_info["maxsize"]: - oldest_key = None - for k in cache: - if oldest_key is None: - oldest_key = k - elif cache[k][1] < cache[oldest_key][1]: - oldest_key = k - del cache[oldest_key] - _cache_info["currsize"] -= 1 - - if cache_path is not None: - with open(cache_path, "wb") as f: - pickle.dump(cache, f) - - return result - - def cache_info(): - return _cache_info - - wrapper_function.cache_info = cache_info - - if cache_path is not None and os.path.exists(cache_path): - with open(cache_path, "rb") as f: - cache = pickle.load(f) - _cache_info["currsize"] = len(cache) - - return wrapper_function - - return decorator_function - -def contains_chinese(string): - """ - Returns True if the given string contains Chinese characters, False otherwise. - """ - chinese_regex = re.compile(u'[\u4e00-\u9fff]+') - return chinese_regex.search(string) is not None - -def split_list(lst, n_each_req): - """ - Split a list into smaller lists, each with a maximum number of elements. - :param lst: the list to split - :param n_each_req: the maximum number of elements in each sub-list - :return: a list of sub-lists - """ - result = [] - for i in range(0, len(lst), n_each_req): - result.append(lst[i:i + n_each_req]) - return result - -def map_to_json(map, language): - dict_ = read_map_from_json(language) - dict_.update(map) - with open(f'docs/translate_{language.lower()}.json', 'w', encoding='utf8') as f: - json.dump(dict_, f, indent=4, ensure_ascii=False) - -def read_map_from_json(language): - if os.path.exists(f'docs/translate_{language.lower()}.json'): - with open(f'docs/translate_{language.lower()}.json', 'r', encoding='utf8') as f: - res = json.load(f) - res = {k:v for k, v in res.items() if v is not None and contains_chinese(k)} - return res - return {} - -def advanced_split(splitted_string, spliter, include_spliter=False): - splitted_string_tmp = [] - for string_ in splitted_string: - if spliter in string_: - splitted = string_.split(spliter) - for i, s in enumerate(splitted): - if include_spliter: - if i != len(splitted)-1: - splitted[i] += spliter - splitted[i] = splitted[i].strip() - for i in reversed(range(len(splitted))): - if not contains_chinese(splitted[i]): - splitted.pop(i) - splitted_string_tmp.extend(splitted) - else: - splitted_string_tmp.append(string_) - splitted_string = splitted_string_tmp - return splitted_string_tmp - -cached_translation = {} -cached_translation = read_map_from_json(language=LANG) - -def trans(word_to_translate, language, special=False): - if len(word_to_translate) == 0: return {} - from crazy_functions.crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency - from toolbox import get_conf, ChatBotWithCookies - proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \ - get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY') - llm_kwargs = { - 'api_key': API_KEY, - 'llm_model': LLM_MODEL, - 'top_p':1.0, - 'max_length': None, - 'temperature':0.4, - } - import random - N_EACH_REQ = random.randint(16, 32) - word_to_translate_split = split_list(word_to_translate, N_EACH_REQ) - inputs_array = [str(s) for s in word_to_translate_split] - inputs_show_user_array = inputs_array - history_array = [[] for _ in inputs_array] - if special: # to English using CamelCase Naming Convention - sys_prompt_array = [f"Translate following names to English with CamelCase naming convention. Keep original format" for _ in inputs_array] - else: - sys_prompt_array = [f"Translate following sentences to {LANG}. E.g., You should translate sentences to the following format ['translation of sentence 1', 'translation of sentence 2']. Do NOT answer with Chinese!" for _ in inputs_array] - chatbot = ChatBotWithCookies(llm_kwargs) - gpt_say_generator = request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( - inputs_array, - inputs_show_user_array, - llm_kwargs, - chatbot, - history_array, - sys_prompt_array, - ) - while True: - try: - gpt_say = next(gpt_say_generator) - print(gpt_say[1][0][1]) - except StopIteration as e: - result = e.value - break - translated_result = {} - for i, r in enumerate(result): - if i%2 == 1: - try: - res_before_trans = eval(result[i-1]) - res_after_trans = eval(result[i]) - if len(res_before_trans) != len(res_after_trans): - raise RuntimeError - for a,b in zip(res_before_trans, res_after_trans): - translated_result[a] = b - except: - # try: - # res_before_trans = word_to_translate_split[(i-1)//2] - # res_after_trans = [s for s in result[i].split("', '")] - # for a,b in zip(res_before_trans, res_after_trans): - # translated_result[a] = b - # except: - print('GPT answers with unexpected format, some words may not be translated, but you can try again later to increase translation coverage.') - res_before_trans = eval(result[i-1]) - for a in res_before_trans: - translated_result[a] = None - return translated_result - - -def trans_json(word_to_translate, language, special=False): - if len(word_to_translate) == 0: return {} - from crazy_functions.crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency - from toolbox import get_conf, ChatBotWithCookies - proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \ - get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY') - llm_kwargs = { - 'api_key': API_KEY, - 'llm_model': LLM_MODEL, - 'top_p':1.0, - 'max_length': None, - 'temperature':0.1, - } - import random - N_EACH_REQ = random.randint(16, 32) - random.shuffle(word_to_translate) - word_to_translate_split = split_list(word_to_translate, N_EACH_REQ) - inputs_array = [{k:"#" for k in s} for s in word_to_translate_split] - inputs_array = [ json.dumps(i, ensure_ascii=False) for i in inputs_array] - - inputs_show_user_array = inputs_array - history_array = [[] for _ in inputs_array] - sys_prompt_array = [TransPrompt for _ in inputs_array] - chatbot = ChatBotWithCookies(llm_kwargs) - gpt_say_generator = request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( - inputs_array, - inputs_show_user_array, - llm_kwargs, - chatbot, - history_array, - sys_prompt_array, - ) - while True: - try: - gpt_say = next(gpt_say_generator) - print(gpt_say[1][0][1]) - except StopIteration as e: - result = e.value - break - translated_result = {} - for i, r in enumerate(result): - if i%2 == 1: - try: - translated_result.update(json.loads(result[i])) - except: - print(result[i]) - print(result) - return translated_result - - -def step_1_core_key_translate(): - def extract_chinese_characters(file_path): - syntax = [] - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - import ast - root = ast.parse(content) - for node in ast.walk(root): - if isinstance(node, ast.Name): - if contains_chinese(node.id): syntax.append(node.id) - if isinstance(node, ast.Import): - for n in node.names: - if contains_chinese(n.name): syntax.append(n.name) - elif isinstance(node, ast.ImportFrom): - for n in node.names: - if contains_chinese(n.name): syntax.append(n.name) - for k in node.module.split('.'): - if contains_chinese(k): syntax.append(k) - return syntax - - def extract_chinese_characters_from_directory(directory_path): - chinese_characters = [] - for root, dirs, files in os.walk(directory_path): - if any([b in root for b in blacklist]): - continue - for file in files: - if file.endswith('.py'): - file_path = os.path.join(root, file) - chinese_characters.extend(extract_chinese_characters(file_path)) - return chinese_characters - - directory_path = './' - chinese_core_names = extract_chinese_characters_from_directory(directory_path) - chinese_core_keys = [name for name in chinese_core_names] - chinese_core_keys_norepeat = [] - for d in chinese_core_keys: - if d not in chinese_core_keys_norepeat: chinese_core_keys_norepeat.append(d) - need_translate = [] - cached_translation = read_map_from_json(language=LANG) - cached_translation_keys = list(cached_translation.keys()) - for d in chinese_core_keys_norepeat: - if d not in cached_translation_keys: - need_translate.append(d) - - need_translate_mapping = trans(need_translate, language=LANG, special=True) - map_to_json(need_translate_mapping, language=LANG) - cached_translation = read_map_from_json(language=LANG) - cached_translation = dict(sorted(cached_translation.items(), key=lambda x: -len(x[0]))) - - chinese_core_keys_norepeat_mapping = {} - for k in chinese_core_keys_norepeat: - chinese_core_keys_norepeat_mapping.update({k:cached_translation[k]}) - chinese_core_keys_norepeat_mapping = dict(sorted(chinese_core_keys_norepeat_mapping.items(), key=lambda x: -len(x[0]))) - - # =============================================== - # copy - # =============================================== - def copy_source_code(): - - from toolbox import get_conf - import shutil - import os - try: shutil.rmtree(f'./multi-language/{LANG}/') - except: pass - os.makedirs(f'./multi-language', exist_ok=True) - backup_dir = f'./multi-language/{LANG}/' - shutil.copytree('./', backup_dir, ignore=lambda x, y: blacklist) - copy_source_code() - - # =============================================== - # primary key replace - # =============================================== - directory_path = f'./multi-language/{LANG}/' - for root, dirs, files in os.walk(directory_path): - for file in files: - if file.endswith('.py'): - file_path = os.path.join(root, file) - syntax = [] - # read again - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - - for k, v in chinese_core_keys_norepeat_mapping.items(): - content = content.replace(k, v) - - with open(file_path, 'w', encoding='utf-8') as f: - f.write(content) - - -def step_2_core_key_translate(): - - # ================================================================================================= - # step2 - # ================================================================================================= - - def load_string(strings, string_input): - string_ = string_input.strip().strip(',').strip().strip('.').strip() - if string_.startswith('[Local Message]'): - string_ = string_.replace('[Local Message]', '') - string_ = string_.strip().strip(',').strip().strip('.').strip() - splitted_string = [string_] - # -------------------------------------- - splitted_string = advanced_split(splitted_string, spliter=",", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="。", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=")", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="(", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="(", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=")", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="<", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=">", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="[", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="]", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="【", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="】", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="?", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=":", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=":", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=",", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="#", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="\n", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=";", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="`", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter=" ", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="- ", include_spliter=False) - splitted_string = advanced_split(splitted_string, spliter="---", include_spliter=False) - - # -------------------------------------- - for j, s in enumerate(splitted_string): # .com - if '.com' in s: continue - if '\'' in s: continue - if '\"' in s: continue - strings.append([s,0]) - - - def get_strings(node): - strings = [] - # recursively traverse the AST - for child in ast.iter_child_nodes(node): - node = child - if isinstance(child, ast.Str): - if contains_chinese(child.s): - load_string(strings=strings, string_input=child.s) - elif isinstance(child, ast.AST): - strings.extend(get_strings(child)) - return strings - - string_literals = [] - directory_path = f'./multi-language/{LANG}/' - for root, dirs, files in os.walk(directory_path): - for file in files: - if file.endswith('.py'): - file_path = os.path.join(root, file) - syntax = [] - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - # comments - comments_arr = [] - for code_sp in content.splitlines(): - comments = re.findall(r'#.*$', code_sp) - for comment in comments: - load_string(strings=comments_arr, string_input=comment) - string_literals.extend(comments_arr) - - # strings - import ast - tree = ast.parse(content) - res = get_strings(tree, ) - string_literals.extend(res) - - [print(s) for s in string_literals] - chinese_literal_names = [] - chinese_literal_names_norepeat = [] - for string, offset in string_literals: - chinese_literal_names.append(string) - chinese_literal_names_norepeat = [] - for d in chinese_literal_names: - if d not in chinese_literal_names_norepeat: chinese_literal_names_norepeat.append(d) - need_translate = [] - cached_translation = read_map_from_json(language=LANG) - cached_translation_keys = list(cached_translation.keys()) - for d in chinese_literal_names_norepeat: - if d not in cached_translation_keys: - need_translate.append(d) - - - up = trans_json(need_translate, language=LANG, special=False) - map_to_json(up, language=LANG) - cached_translation = read_map_from_json(language=LANG) - cached_translation = dict(sorted(cached_translation.items(), key=lambda x: -len(x[0]))) - - # =============================================== - # literal key replace - # =============================================== - directory_path = f'./multi-language/{LANG}/' - for root, dirs, files in os.walk(directory_path): - for file in files: - if file.endswith('.py'): - file_path = os.path.join(root, file) - syntax = [] - # read again - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - - for k, v in cached_translation.items(): - if v is None: continue - if '"' in v: - v = v.replace('"', "`") - if '\'' in v: - v = v.replace('\'', "`") - content = content.replace(k, v) - - with open(file_path, 'w', encoding='utf-8') as f: - f.write(content) - - if file.strip('.py') in cached_translation: - file_new = cached_translation[file.strip('.py')] + '.py' - file_path_new = os.path.join(root, file_new) - with open(file_path_new, 'w', encoding='utf-8') as f: - f.write(content) - os.remove(file_path) - -step_1_core_key_translate() -step_2_core_key_translate() diff --git a/spaces/darienacosta/chatgpt-coverwhale/README.md b/spaces/darienacosta/chatgpt-coverwhale/README.md deleted file mode 100644 index 9138d90ccd9ed2f63d83db1c97b1d510b0f6eae1..0000000000000000000000000000000000000000 --- a/spaces/darienacosta/chatgpt-coverwhale/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Chatgpt 4 API Portal - CoverWhale -emoji: 🐋 -colorFrom: purple -colorTo: magenta -sdk: gradio -sdk_version: 3.20.1 -app_file: app.py -pinned: false -duplicated_from: darienacosta/chatgpt-coverwhale-test ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/dawood/audioldm-text-to-audio-generation/audioldm/clap/__init__.py b/spaces/dawood/audioldm-text-to-audio-generation/audioldm/clap/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/anyio/from_thread.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/anyio/from_thread.py deleted file mode 100644 index 6b76861c70d6a6aa369a54370ef47aa75839a91f..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/anyio/from_thread.py +++ /dev/null @@ -1,500 +0,0 @@ -from __future__ import annotations - -import threading -from asyncio import iscoroutine -from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait -from contextlib import AbstractContextManager, contextmanager -from types import TracebackType -from typing import ( - Any, - AsyncContextManager, - Awaitable, - Callable, - ContextManager, - Generator, - Generic, - Iterable, - TypeVar, - cast, - overload, -) -from warnings import warn - -from ._core import _eventloop -from ._core._eventloop import get_asynclib, get_cancelled_exc_class, threadlocals -from ._core._synchronization import Event -from ._core._tasks import CancelScope, create_task_group -from .abc._tasks import TaskStatus - -T_Retval = TypeVar("T_Retval") -T_co = TypeVar("T_co") - - -def run(func: Callable[..., Awaitable[T_Retval]], *args: object) -> T_Retval: - """ - Call a coroutine function from a worker thread. - - :param func: a coroutine function - :param args: positional arguments for the callable - :return: the return value of the coroutine function - - """ - try: - asynclib = threadlocals.current_async_module - except AttributeError: - raise RuntimeError("This function can only be run from an AnyIO worker thread") - - return asynclib.run_async_from_thread(func, *args) - - -def run_async_from_thread( - func: Callable[..., Awaitable[T_Retval]], *args: object -) -> T_Retval: - warn( - "run_async_from_thread() has been deprecated, use anyio.from_thread.run() instead", - DeprecationWarning, - ) - return run(func, *args) - - -def run_sync(func: Callable[..., T_Retval], *args: object) -> T_Retval: - """ - Call a function in the event loop thread from a worker thread. - - :param func: a callable - :param args: positional arguments for the callable - :return: the return value of the callable - - """ - try: - asynclib = threadlocals.current_async_module - except AttributeError: - raise RuntimeError("This function can only be run from an AnyIO worker thread") - - return asynclib.run_sync_from_thread(func, *args) - - -def run_sync_from_thread(func: Callable[..., T_Retval], *args: object) -> T_Retval: - warn( - "run_sync_from_thread() has been deprecated, use anyio.from_thread.run_sync() instead", - DeprecationWarning, - ) - return run_sync(func, *args) - - -class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager): - _enter_future: Future - _exit_future: Future - _exit_event: Event - _exit_exc_info: tuple[ - type[BaseException] | None, BaseException | None, TracebackType | None - ] = (None, None, None) - - def __init__(self, async_cm: AsyncContextManager[T_co], portal: BlockingPortal): - self._async_cm = async_cm - self._portal = portal - - async def run_async_cm(self) -> bool | None: - try: - self._exit_event = Event() - value = await self._async_cm.__aenter__() - except BaseException as exc: - self._enter_future.set_exception(exc) - raise - else: - self._enter_future.set_result(value) - - try: - # Wait for the sync context manager to exit. - # This next statement can raise `get_cancelled_exc_class()` if - # something went wrong in a task group in this async context - # manager. - await self._exit_event.wait() - finally: - # In case of cancellation, it could be that we end up here before - # `_BlockingAsyncContextManager.__exit__` is called, and an - # `_exit_exc_info` has been set. - result = await self._async_cm.__aexit__(*self._exit_exc_info) - return result - - def __enter__(self) -> T_co: - self._enter_future = Future() - self._exit_future = self._portal.start_task_soon(self.run_async_cm) - cm = self._enter_future.result() - return cast(T_co, cm) - - def __exit__( - self, - __exc_type: type[BaseException] | None, - __exc_value: BaseException | None, - __traceback: TracebackType | None, - ) -> bool | None: - self._exit_exc_info = __exc_type, __exc_value, __traceback - self._portal.call(self._exit_event.set) - return self._exit_future.result() - - -class _BlockingPortalTaskStatus(TaskStatus): - def __init__(self, future: Future): - self._future = future - - def started(self, value: object = None) -> None: - self._future.set_result(value) - - -class BlockingPortal: - """An object that lets external threads run code in an asynchronous event loop.""" - - def __new__(cls) -> BlockingPortal: - return get_asynclib().BlockingPortal() - - def __init__(self) -> None: - self._event_loop_thread_id: int | None = threading.get_ident() - self._stop_event = Event() - self._task_group = create_task_group() - self._cancelled_exc_class = get_cancelled_exc_class() - - async def __aenter__(self) -> BlockingPortal: - await self._task_group.__aenter__() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool | None: - await self.stop() - return await self._task_group.__aexit__(exc_type, exc_val, exc_tb) - - def _check_running(self) -> None: - if self._event_loop_thread_id is None: - raise RuntimeError("This portal is not running") - if self._event_loop_thread_id == threading.get_ident(): - raise RuntimeError( - "This method cannot be called from the event loop thread" - ) - - async def sleep_until_stopped(self) -> None: - """Sleep until :meth:`stop` is called.""" - await self._stop_event.wait() - - async def stop(self, cancel_remaining: bool = False) -> None: - """ - Signal the portal to shut down. - - This marks the portal as no longer accepting new calls and exits from - :meth:`sleep_until_stopped`. - - :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` to let them - finish before returning - - """ - self._event_loop_thread_id = None - self._stop_event.set() - if cancel_remaining: - self._task_group.cancel_scope.cancel() - - async def _call_func( - self, func: Callable, args: tuple, kwargs: dict[str, Any], future: Future - ) -> None: - def callback(f: Future) -> None: - if f.cancelled() and self._event_loop_thread_id not in ( - None, - threading.get_ident(), - ): - self.call(scope.cancel) - - try: - retval = func(*args, **kwargs) - if iscoroutine(retval): - with CancelScope() as scope: - if future.cancelled(): - scope.cancel() - else: - future.add_done_callback(callback) - - retval = await retval - except self._cancelled_exc_class: - future.cancel() - except BaseException as exc: - if not future.cancelled(): - future.set_exception(exc) - - # Let base exceptions fall through - if not isinstance(exc, Exception): - raise - else: - if not future.cancelled(): - future.set_result(retval) - finally: - scope = None # type: ignore[assignment] - - def _spawn_task_from_thread( - self, - func: Callable, - args: tuple, - kwargs: dict[str, Any], - name: object, - future: Future, - ) -> None: - """ - Spawn a new task using the given callable. - - Implementors must ensure that the future is resolved when the task finishes. - - :param func: a callable - :param args: positional arguments to be passed to the callable - :param kwargs: keyword arguments to be passed to the callable - :param name: name of the task (will be coerced to a string if not ``None``) - :param future: a future that will resolve to the return value of the callable, or the - exception raised during its execution - - """ - raise NotImplementedError - - @overload - def call(self, func: Callable[..., Awaitable[T_Retval]], *args: object) -> T_Retval: - ... - - @overload - def call(self, func: Callable[..., T_Retval], *args: object) -> T_Retval: - ... - - def call( - self, func: Callable[..., Awaitable[T_Retval] | T_Retval], *args: object - ) -> T_Retval: - """ - Call the given function in the event loop thread. - - If the callable returns a coroutine object, it is awaited on. - - :param func: any callable - :raises RuntimeError: if the portal is not running or if this method is called from within - the event loop thread - - """ - return cast(T_Retval, self.start_task_soon(func, *args).result()) - - @overload - def spawn_task( - self, - func: Callable[..., Awaitable[T_Retval]], - *args: object, - name: object = None, - ) -> Future[T_Retval]: - ... - - @overload - def spawn_task( - self, func: Callable[..., T_Retval], *args: object, name: object = None - ) -> Future[T_Retval]: - ... - - def spawn_task( - self, - func: Callable[..., Awaitable[T_Retval] | T_Retval], - *args: object, - name: object = None, - ) -> Future[T_Retval]: - """ - Start a task in the portal's task group. - - :param func: the target coroutine function - :param args: positional arguments passed to ``func`` - :param name: name of the task (will be coerced to a string if not ``None``) - :return: a future that resolves with the return value of the callable if the task completes - successfully, or with the exception raised in the task - :raises RuntimeError: if the portal is not running or if this method is called from within - the event loop thread - - .. versionadded:: 2.1 - .. deprecated:: 3.0 - Use :meth:`start_task_soon` instead. If your code needs AnyIO 2 compatibility, you - can keep using this until AnyIO 4. - - """ - warn( - "spawn_task() is deprecated -- use start_task_soon() instead", - DeprecationWarning, - ) - return self.start_task_soon(func, *args, name=name) # type: ignore[arg-type] - - @overload - def start_task_soon( - self, - func: Callable[..., Awaitable[T_Retval]], - *args: object, - name: object = None, - ) -> Future[T_Retval]: - ... - - @overload - def start_task_soon( - self, func: Callable[..., T_Retval], *args: object, name: object = None - ) -> Future[T_Retval]: - ... - - def start_task_soon( - self, - func: Callable[..., Awaitable[T_Retval] | T_Retval], - *args: object, - name: object = None, - ) -> Future[T_Retval]: - """ - Start a task in the portal's task group. - - The task will be run inside a cancel scope which can be cancelled by cancelling the - returned future. - - :param func: the target function - :param args: positional arguments passed to ``func`` - :param name: name of the task (will be coerced to a string if not ``None``) - :return: a future that resolves with the return value of the callable if the - task completes successfully, or with the exception raised in the task - :raises RuntimeError: if the portal is not running or if this method is called - from within the event loop thread - :rtype: concurrent.futures.Future[T_Retval] - - .. versionadded:: 3.0 - - """ - self._check_running() - f: Future = Future() - self._spawn_task_from_thread(func, args, {}, name, f) - return f - - def start_task( - self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None - ) -> tuple[Future[Any], Any]: - """ - Start a task in the portal's task group and wait until it signals for readiness. - - This method works the same way as :meth:`.abc.TaskGroup.start`. - - :param func: the target function - :param args: positional arguments passed to ``func`` - :param name: name of the task (will be coerced to a string if not ``None``) - :return: a tuple of (future, task_status_value) where the ``task_status_value`` - is the value passed to ``task_status.started()`` from within the target - function - :rtype: tuple[concurrent.futures.Future[Any], Any] - - .. versionadded:: 3.0 - - """ - - def task_done(future: Future) -> None: - if not task_status_future.done(): - if future.cancelled(): - task_status_future.cancel() - elif future.exception(): - task_status_future.set_exception(future.exception()) - else: - exc = RuntimeError( - "Task exited without calling task_status.started()" - ) - task_status_future.set_exception(exc) - - self._check_running() - task_status_future: Future = Future() - task_status = _BlockingPortalTaskStatus(task_status_future) - f: Future = Future() - f.add_done_callback(task_done) - self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f) - return f, task_status_future.result() - - def wrap_async_context_manager( - self, cm: AsyncContextManager[T_co] - ) -> ContextManager[T_co]: - """ - Wrap an async context manager as a synchronous context manager via this portal. - - Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping in the - middle until the synchronous context manager exits. - - :param cm: an asynchronous context manager - :return: a synchronous context manager - - .. versionadded:: 2.1 - - """ - return _BlockingAsyncContextManager(cm, self) - - -def create_blocking_portal() -> BlockingPortal: - """ - Create a portal for running functions in the event loop thread from external threads. - - Use this function in asynchronous code when you need to allow external threads access to the - event loop where your asynchronous code is currently running. - - .. deprecated:: 3.0 - Use :class:`.BlockingPortal` directly. - - """ - warn( - "create_blocking_portal() has been deprecated -- use anyio.from_thread.BlockingPortal() " - "directly", - DeprecationWarning, - ) - return BlockingPortal() - - -@contextmanager -def start_blocking_portal( - backend: str = "asyncio", backend_options: dict[str, Any] | None = None -) -> Generator[BlockingPortal, Any, None]: - """ - Start a new event loop in a new thread and run a blocking portal in its main task. - - The parameters are the same as for :func:`~anyio.run`. - - :param backend: name of the backend - :param backend_options: backend options - :return: a context manager that yields a blocking portal - - .. versionchanged:: 3.0 - Usage as a context manager is now required. - - """ - - async def run_portal() -> None: - async with BlockingPortal() as portal_: - if future.set_running_or_notify_cancel(): - future.set_result(portal_) - await portal_.sleep_until_stopped() - - future: Future[BlockingPortal] = Future() - with ThreadPoolExecutor(1) as executor: - run_future = executor.submit( - _eventloop.run, - run_portal, # type: ignore[arg-type] - backend=backend, - backend_options=backend_options, - ) - try: - wait( - cast(Iterable[Future], [run_future, future]), - return_when=FIRST_COMPLETED, - ) - except BaseException: - future.cancel() - run_future.cancel() - raise - - if future.done(): - portal = future.result() - cancel_remaining_tasks = False - try: - yield portal - except BaseException: - cancel_remaining_tasks = True - raise - finally: - try: - portal.call(portal.stop, cancel_remaining_tasks) - except RuntimeError: - pass - - run_future.result() diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpcore/_async/http_proxy.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpcore/_async/http_proxy.py deleted file mode 100644 index 62f510978f990209d334fd473ee22c1741052049..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpcore/_async/http_proxy.py +++ /dev/null @@ -1,350 +0,0 @@ -import logging -import ssl -from base64 import b64encode -from typing import Iterable, List, Mapping, Optional, Sequence, Tuple, Union - -from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend -from .._exceptions import ProxyError -from .._models import ( - URL, - Origin, - Request, - Response, - enforce_bytes, - enforce_headers, - enforce_url, -) -from .._ssl import default_ssl_context -from .._synchronization import AsyncLock -from .._trace import Trace -from .connection import AsyncHTTPConnection -from .connection_pool import AsyncConnectionPool -from .http11 import AsyncHTTP11Connection -from .interfaces import AsyncConnectionInterface - -HeadersAsSequence = Sequence[Tuple[Union[bytes, str], Union[bytes, str]]] -HeadersAsMapping = Mapping[Union[bytes, str], Union[bytes, str]] - - -logger = logging.getLogger("httpcore.proxy") - - -def merge_headers( - default_headers: Optional[Sequence[Tuple[bytes, bytes]]] = None, - override_headers: Optional[Sequence[Tuple[bytes, bytes]]] = None, -) -> List[Tuple[bytes, bytes]]: - """ - Append default_headers and override_headers, de-duplicating if a key exists - in both cases. - """ - default_headers = [] if default_headers is None else list(default_headers) - override_headers = [] if override_headers is None else list(override_headers) - has_override = set(key.lower() for key, value in override_headers) - default_headers = [ - (key, value) - for key, value in default_headers - if key.lower() not in has_override - ] - return default_headers + override_headers - - -def build_auth_header(username: bytes, password: bytes) -> bytes: - userpass = username + b":" + password - return b"Basic " + b64encode(userpass) - - -class AsyncHTTPProxy(AsyncConnectionPool): - """ - A connection pool that sends requests via an HTTP proxy. - """ - - def __init__( - self, - proxy_url: Union[URL, bytes, str], - proxy_auth: Optional[Tuple[Union[bytes, str], Union[bytes, str]]] = None, - proxy_headers: Union[HeadersAsMapping, HeadersAsSequence, None] = None, - ssl_context: Optional[ssl.SSLContext] = None, - max_connections: Optional[int] = 10, - max_keepalive_connections: Optional[int] = None, - keepalive_expiry: Optional[float] = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: Optional[str] = None, - uds: Optional[str] = None, - network_backend: Optional[AsyncNetworkBackend] = None, - socket_options: Optional[Iterable[SOCKET_OPTION]] = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - proxy_url: The URL to use when connecting to the proxy server. - For example `"http://127.0.0.1:8080/"`. - proxy_auth: Any proxy authentication as a two-tuple of - (username, password). May be either bytes or ascii-only str. - proxy_headers: Any HTTP headers to use for the proxy requests. - For example `{"Proxy-Authorization": "Basic :"}`. - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish - a connection. - local_address: Local address to connect from. Can also be used to - connect using a particular address family. Using - `local_address="0.0.0.0"` will connect using an `AF_INET` address - (IPv4), while using `local_address="::"` will connect using an - `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - """ - super().__init__( - ssl_context=ssl_context, - max_connections=max_connections, - max_keepalive_connections=max_keepalive_connections, - keepalive_expiry=keepalive_expiry, - http1=http1, - http2=http2, - network_backend=network_backend, - retries=retries, - local_address=local_address, - uds=uds, - socket_options=socket_options, - ) - self._ssl_context = ssl_context - self._proxy_url = enforce_url(proxy_url, name="proxy_url") - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - if proxy_auth is not None: - username = enforce_bytes(proxy_auth[0], name="proxy_auth") - password = enforce_bytes(proxy_auth[1], name="proxy_auth") - authorization = build_auth_header(username, password) - self._proxy_headers = [ - (b"Proxy-Authorization", authorization) - ] + self._proxy_headers - - def create_connection(self, origin: Origin) -> AsyncConnectionInterface: - if origin.scheme == b"http": - return AsyncForwardHTTPConnection( - proxy_origin=self._proxy_url.origin, - proxy_headers=self._proxy_headers, - remote_origin=origin, - keepalive_expiry=self._keepalive_expiry, - network_backend=self._network_backend, - ) - return AsyncTunnelHTTPConnection( - proxy_origin=self._proxy_url.origin, - proxy_headers=self._proxy_headers, - remote_origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - -class AsyncForwardHTTPConnection(AsyncConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - proxy_headers: Union[HeadersAsMapping, HeadersAsSequence, None] = None, - keepalive_expiry: Optional[float] = None, - network_backend: Optional[AsyncNetworkBackend] = None, - socket_options: Optional[Iterable[SOCKET_OPTION]] = None, - ) -> None: - self._connection = AsyncHTTPConnection( - origin=proxy_origin, - keepalive_expiry=keepalive_expiry, - network_backend=network_backend, - socket_options=socket_options, - ) - self._proxy_origin = proxy_origin - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - self._remote_origin = remote_origin - - async def handle_async_request(self, request: Request) -> Response: - headers = merge_headers(self._proxy_headers, request.headers) - url = URL( - scheme=self._proxy_origin.scheme, - host=self._proxy_origin.host, - port=self._proxy_origin.port, - target=bytes(request.url), - ) - proxy_request = Request( - method=request.method, - url=url, - headers=headers, - content=request.stream, - extensions=request.extensions, - ) - return await self._connection.handle_async_request(proxy_request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - async def aclose(self) -> None: - await self._connection.aclose() - - def info(self) -> str: - return self._connection.info() - - def is_available(self) -> bool: - return self._connection.is_available() - - def has_expired(self) -> bool: - return self._connection.has_expired() - - def is_idle(self) -> bool: - return self._connection.is_idle() - - def is_closed(self) -> bool: - return self._connection.is_closed() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" - - -class AsyncTunnelHTTPConnection(AsyncConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - ssl_context: Optional[ssl.SSLContext] = None, - proxy_headers: Optional[Sequence[Tuple[bytes, bytes]]] = None, - keepalive_expiry: Optional[float] = None, - http1: bool = True, - http2: bool = False, - network_backend: Optional[AsyncNetworkBackend] = None, - socket_options: Optional[Iterable[SOCKET_OPTION]] = None, - ) -> None: - self._connection: AsyncConnectionInterface = AsyncHTTPConnection( - origin=proxy_origin, - keepalive_expiry=keepalive_expiry, - network_backend=network_backend, - socket_options=socket_options, - ) - self._proxy_origin = proxy_origin - self._remote_origin = remote_origin - self._ssl_context = ssl_context - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._connect_lock = AsyncLock() - self._connected = False - - async def handle_async_request(self, request: Request) -> Response: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("connect", None) - - async with self._connect_lock: - if not self._connected: - target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port) - - connect_url = URL( - scheme=self._proxy_origin.scheme, - host=self._proxy_origin.host, - port=self._proxy_origin.port, - target=target, - ) - connect_headers = merge_headers( - [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers - ) - connect_request = Request( - method=b"CONNECT", - url=connect_url, - headers=connect_headers, - extensions=request.extensions, - ) - connect_response = await self._connection.handle_async_request( - connect_request - ) - - if connect_response.status < 200 or connect_response.status > 299: - reason_bytes = connect_response.extensions.get("reason_phrase", b"") - reason_str = reason_bytes.decode("ascii", errors="ignore") - msg = "%d %s" % (connect_response.status, reason_str) - await self._connection.aclose() - raise ProxyError(msg) - - stream = connect_response.extensions["network_stream"] - - # Upgrade the stream to SSL - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": self._remote_origin.host.decode("ascii"), - "timeout": timeout, - } - async with Trace("start_tls", logger, request, kwargs) as trace: - stream = await stream.start_tls(**kwargs) - trace.return_value = stream - - # Determine if we should be using HTTP/1.1 or HTTP/2 - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - - # Create the HTTP/1.1 or HTTP/2 connection - if http2_negotiated or (self._http2 and not self._http1): - from .http2 import AsyncHTTP2Connection - - self._connection = AsyncHTTP2Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = AsyncHTTP11Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - - self._connected = True - return await self._connection.handle_async_request(request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - async def aclose(self) -> None: - await self._connection.aclose() - - def info(self) -> str: - return self._connection.info() - - def is_available(self) -> bool: - return self._connection.is_available() - - def has_expired(self) -> bool: - return self._connection.has_expired() - - def is_idle(self) -> bool: - return self._connection.is_idle() - - def is_closed(self) -> bool: - return self._connection.is_closed() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/huggingface_hub/templates/modelcard_template.md b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/huggingface_hub/templates/modelcard_template.md deleted file mode 100644 index ec2d18d427c9fc96eb5c8b89103632620ed4a0b6..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/huggingface_hub/templates/modelcard_template.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 -# Doc / guide: https://huggingface.co/docs/hub/model-cards -{{ card_data }} ---- - -# Model Card for {{ model_id | default("Model ID", true) }} - - - -{{ model_summary | default("", true) }} - -## Model Details - -### Model Description - - - -{{ model_description | default("", true) }} - -- **Developed by:** {{ developers | default("[More Information Needed]", true)}} -- **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}} -- **Model type:** {{ model_type | default("[More Information Needed]", true)}} -- **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}} -- **License:** {{ license | default("[More Information Needed]", true)}} -- **Finetuned from model [optional]:** {{ finetuned_from | default("[More Information Needed]", true)}} - -### Model Sources [optional] - - - -- **Repository:** {{ repo | default("[More Information Needed]", true)}} -- **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}} -- **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}} - -## Uses - - - -### Direct Use - - - -{{ direct_use | default("[More Information Needed]", true)}} - -### Downstream Use [optional] - - - -{{ downstream_use | default("[More Information Needed]", true)}} - -### Out-of-Scope Use - - - -{{ out_of_scope_use | default("[More Information Needed]", true)}} - -## Bias, Risks, and Limitations - - - -{{ bias_risks_limitations | default("[More Information Needed]", true)}} - -### Recommendations - - - -{{ bias_recommendations | default("Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.", true)}} - -## How to Get Started with the Model - -Use the code below to get started with the model. - -{{ get_started_code | default("[More Information Needed]", true)}} - -## Training Details - -### Training Data - - - -{{ training_data | default("[More Information Needed]", true)}} - -### Training Procedure - - - -#### Preprocessing [optional] - -{{ preprocessing | default("[More Information Needed]", true)}} - - -#### Training Hyperparameters - -- **Training regime:** {{ training_regime | default("[More Information Needed]", true)}} - -#### Speeds, Sizes, Times [optional] - - - -{{ speeds_sizes_times | default("[More Information Needed]", true)}} - -## Evaluation - - - -### Testing Data, Factors & Metrics - -#### Testing Data - - - -{{ testing_data | default("[More Information Needed]", true)}} - -#### Factors - - - -{{ testing_factors | default("[More Information Needed]", true)}} - -#### Metrics - - - -{{ testing_metrics | default("[More Information Needed]", true)}} - -### Results - -{{ results | default("[More Information Needed]", true)}} - -#### Summary - -{{ results_summary | default("", true) }} - -## Model Examination [optional] - - - -{{ model_examination | default("[More Information Needed]", true)}} - -## Environmental Impact - - - -Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). - -- **Hardware Type:** {{ hardware | default("[More Information Needed]", true)}} -- **Hours used:** {{ hours_used | default("[More Information Needed]", true)}} -- **Cloud Provider:** {{ cloud_provider | default("[More Information Needed]", true)}} -- **Compute Region:** {{ cloud_region | default("[More Information Needed]", true)}} -- **Carbon Emitted:** {{ co2_emitted | default("[More Information Needed]", true)}} - -## Technical Specifications [optional] - -### Model Architecture and Objective - -{{ model_specs | default("[More Information Needed]", true)}} - -### Compute Infrastructure - -{{ compute_infrastructure | default("[More Information Needed]", true)}} - -#### Hardware - -{{ hardware | default("[More Information Needed]", true)}} - -#### Software - -{{ software | default("[More Information Needed]", true)}} - -## Citation [optional] - - - -**BibTeX:** - -{{ citation_bibtex | default("[More Information Needed]", true)}} - -**APA:** - -{{ citation_apa | default("[More Information Needed]", true)}} - -## Glossary [optional] - - - -{{ glossary | default("[More Information Needed]", true)}} - -## More Information [optional] - -{{ more_information | default("[More Information Needed]", true)}} - -## Model Card Authors [optional] - -{{ model_card_authors | default("[More Information Needed]", true)}} - -## Model Card Contact - -{{ model_card_contact | default("[More Information Needed]", true)}} - - - diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/jsonschema/_format.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/jsonschema/_format.py deleted file mode 100644 index f9f82bbe4dc8f15375416adffe3d752c1479745a..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/jsonschema/_format.py +++ /dev/null @@ -1,522 +0,0 @@ -from __future__ import annotations - -from contextlib import suppress -from uuid import UUID -import datetime -import ipaddress -import re -import typing -import warnings - -from jsonschema.exceptions import FormatError - -_FormatCheckCallable = typing.Callable[[object], bool] -#: A format checker callable. -_F = typing.TypeVar("_F", bound=_FormatCheckCallable) -_RaisesType = typing.Union[ - typing.Type[Exception], typing.Tuple[typing.Type[Exception], ...], -] - -_RE_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$", re.ASCII) - - -class FormatChecker: - """ - A ``format`` property checker. - - JSON Schema does not mandate that the ``format`` property actually do any - validation. If validation is desired however, instances of this class can - be hooked into validators to enable format validation. - - `FormatChecker` objects always return ``True`` when asked about - formats that they do not know how to validate. - - To add a check for a custom format use the `FormatChecker.checks` - decorator. - - Arguments: - - formats: - - The known formats to validate. This argument can be used to - limit which formats will be used during validation. - """ - - checkers: dict[ - str, - tuple[_FormatCheckCallable, _RaisesType], - ] = {} # noqa: RUF012 - - def __init__(self, formats: typing.Iterable[str] | None = None): - if formats is None: - formats = self.checkers.keys() - self.checkers = {k: self.checkers[k] for k in formats} - - def __repr__(self): - return f"" - - def checks( # noqa: D417 - self, format: str, raises: _RaisesType = (), - ) -> typing.Callable[[_F], _F]: - """ - Register a decorated function as validating a new format. - - Arguments: - - format: - - The format that the decorated function will check. - - raises: - - The exception(s) raised by the decorated function when an - invalid instance is found. - - The exception object will be accessible as the - `jsonschema.exceptions.ValidationError.cause` attribute of the - resulting validation error. - """ # noqa: D214,D405 (charliermarsh/ruff#3547) - - def _checks(func: _F) -> _F: - self.checkers[format] = (func, raises) - return func - - return _checks - - @classmethod - def cls_checks( - cls, format: str, raises: _RaisesType = (), - ) -> typing.Callable[[_F], _F]: - warnings.warn( - ( - "FormatChecker.cls_checks is deprecated. Call " - "FormatChecker.checks on a specific FormatChecker instance " - "instead." - ), - DeprecationWarning, - stacklevel=2, - ) - return cls._cls_checks(format=format, raises=raises) - - @classmethod - def _cls_checks( - cls, format: str, raises: _RaisesType = (), - ) -> typing.Callable[[_F], _F]: - def _checks(func: _F) -> _F: - cls.checkers[format] = (func, raises) - return func - - return _checks - - def check(self, instance: object, format: str) -> None: - """ - Check whether the instance conforms to the given format. - - Arguments: - - instance (*any primitive type*, i.e. str, number, bool): - - The instance to check - - format: - - The format that instance should conform to - - Raises: - - FormatError: - - if the instance does not conform to ``format`` - """ - if format not in self.checkers: - return - - func, raises = self.checkers[format] - result, cause = None, None - try: - result = func(instance) - except raises as e: - cause = e - if not result: - raise FormatError(f"{instance!r} is not a {format!r}", cause=cause) - - def conforms(self, instance: object, format: str) -> bool: - """ - Check whether the instance conforms to the given format. - - Arguments: - - instance (*any primitive type*, i.e. str, number, bool): - - The instance to check - - format: - - The format that instance should conform to - - Returns: - - bool: whether it conformed - """ - try: - self.check(instance, format) - except FormatError: - return False - else: - return True - - -draft3_format_checker = FormatChecker() -draft4_format_checker = FormatChecker() -draft6_format_checker = FormatChecker() -draft7_format_checker = FormatChecker() -draft201909_format_checker = FormatChecker() -draft202012_format_checker = FormatChecker() - -_draft_checkers: dict[str, FormatChecker] = dict( - draft3=draft3_format_checker, - draft4=draft4_format_checker, - draft6=draft6_format_checker, - draft7=draft7_format_checker, - draft201909=draft201909_format_checker, - draft202012=draft202012_format_checker, -) - - -def _checks_drafts( - name=None, - draft3=None, - draft4=None, - draft6=None, - draft7=None, - draft201909=None, - draft202012=None, - raises=(), -) -> typing.Callable[[_F], _F]: - draft3 = draft3 or name - draft4 = draft4 or name - draft6 = draft6 or name - draft7 = draft7 or name - draft201909 = draft201909 or name - draft202012 = draft202012 or name - - def wrap(func: _F) -> _F: - if draft3: - func = _draft_checkers["draft3"].checks(draft3, raises)(func) - if draft4: - func = _draft_checkers["draft4"].checks(draft4, raises)(func) - if draft6: - func = _draft_checkers["draft6"].checks(draft6, raises)(func) - if draft7: - func = _draft_checkers["draft7"].checks(draft7, raises)(func) - if draft201909: - func = _draft_checkers["draft201909"].checks(draft201909, raises)( - func, - ) - if draft202012: - func = _draft_checkers["draft202012"].checks(draft202012, raises)( - func, - ) - - # Oy. This is bad global state, but relied upon for now, until - # deprecation. See #519 and test_format_checkers_come_with_defaults - FormatChecker._cls_checks( - draft202012 or draft201909 or draft7 or draft6 or draft4 or draft3, - raises, - )(func) - return func - - return wrap - - -@_checks_drafts(name="idn-email") -@_checks_drafts(name="email") -def is_email(instance: object) -> bool: - if not isinstance(instance, str): - return True - return "@" in instance - - -@_checks_drafts( - draft3="ip-address", - draft4="ipv4", - draft6="ipv4", - draft7="ipv4", - draft201909="ipv4", - draft202012="ipv4", - raises=ipaddress.AddressValueError, -) -def is_ipv4(instance: object) -> bool: - if not isinstance(instance, str): - return True - return bool(ipaddress.IPv4Address(instance)) - - -@_checks_drafts(name="ipv6", raises=ipaddress.AddressValueError) -def is_ipv6(instance: object) -> bool: - if not isinstance(instance, str): - return True - address = ipaddress.IPv6Address(instance) - return not getattr(address, "scope_id", "") - - -with suppress(ImportError): - from fqdn import FQDN - - @_checks_drafts( - draft3="host-name", - draft4="hostname", - draft6="hostname", - draft7="hostname", - draft201909="hostname", - draft202012="hostname", - ) - def is_host_name(instance: object) -> bool: - if not isinstance(instance, str): - return True - return FQDN(instance).is_valid - - -with suppress(ImportError): - # The built-in `idna` codec only implements RFC 3890, so we go elsewhere. - import idna - - @_checks_drafts( - draft7="idn-hostname", - draft201909="idn-hostname", - draft202012="idn-hostname", - raises=(idna.IDNAError, UnicodeError), - ) - def is_idn_host_name(instance: object) -> bool: - if not isinstance(instance, str): - return True - idna.encode(instance) - return True - - -try: - import rfc3987 -except ImportError: - with suppress(ImportError): - from rfc3986_validator import validate_rfc3986 - - @_checks_drafts(name="uri") - def is_uri(instance: object) -> bool: - if not isinstance(instance, str): - return True - return validate_rfc3986(instance, rule="URI") - - @_checks_drafts( - draft6="uri-reference", - draft7="uri-reference", - draft201909="uri-reference", - draft202012="uri-reference", - raises=ValueError, - ) - def is_uri_reference(instance: object) -> bool: - if not isinstance(instance, str): - return True - return validate_rfc3986(instance, rule="URI_reference") - -else: - - @_checks_drafts( - draft7="iri", - draft201909="iri", - draft202012="iri", - raises=ValueError, - ) - def is_iri(instance: object) -> bool: - if not isinstance(instance, str): - return True - return rfc3987.parse(instance, rule="IRI") - - @_checks_drafts( - draft7="iri-reference", - draft201909="iri-reference", - draft202012="iri-reference", - raises=ValueError, - ) - def is_iri_reference(instance: object) -> bool: - if not isinstance(instance, str): - return True - return rfc3987.parse(instance, rule="IRI_reference") - - @_checks_drafts(name="uri", raises=ValueError) - def is_uri(instance: object) -> bool: - if not isinstance(instance, str): - return True - return rfc3987.parse(instance, rule="URI") - - @_checks_drafts( - draft6="uri-reference", - draft7="uri-reference", - draft201909="uri-reference", - draft202012="uri-reference", - raises=ValueError, - ) - def is_uri_reference(instance: object) -> bool: - if not isinstance(instance, str): - return True - return rfc3987.parse(instance, rule="URI_reference") - - -with suppress(ImportError): - from rfc3339_validator import validate_rfc3339 - - @_checks_drafts(name="date-time") - def is_datetime(instance: object) -> bool: - if not isinstance(instance, str): - return True - return validate_rfc3339(instance.upper()) - - @_checks_drafts( - draft7="time", - draft201909="time", - draft202012="time", - ) - def is_time(instance: object) -> bool: - if not isinstance(instance, str): - return True - return is_datetime("1970-01-01T" + instance) - - -@_checks_drafts(name="regex", raises=re.error) -def is_regex(instance: object) -> bool: - if not isinstance(instance, str): - return True - return bool(re.compile(instance)) - - -@_checks_drafts( - draft3="date", - draft7="date", - draft201909="date", - draft202012="date", - raises=ValueError, -) -def is_date(instance: object) -> bool: - if not isinstance(instance, str): - return True - return bool( - _RE_DATE.fullmatch(instance) - and datetime.date.fromisoformat(instance) - ) - - -@_checks_drafts(draft3="time", raises=ValueError) -def is_draft3_time(instance: object) -> bool: - if not isinstance(instance, str): - return True - return bool(datetime.datetime.strptime(instance, "%H:%M:%S")) - - -with suppress(ImportError): - from webcolors import CSS21_NAMES_TO_HEX - import webcolors - - def is_css_color_code(instance: object) -> bool: - return webcolors.normalize_hex(instance) - - @_checks_drafts(draft3="color", raises=(ValueError, TypeError)) - def is_css21_color(instance: object) -> bool: - if ( - not isinstance(instance, str) - or instance.lower() in CSS21_NAMES_TO_HEX - ): - return True - return is_css_color_code(instance) - - -with suppress(ImportError): - import jsonpointer - - @_checks_drafts( - draft6="json-pointer", - draft7="json-pointer", - draft201909="json-pointer", - draft202012="json-pointer", - raises=jsonpointer.JsonPointerException, - ) - def is_json_pointer(instance: object) -> bool: - if not isinstance(instance, str): - return True - return bool(jsonpointer.JsonPointer(instance)) - - # TODO: I don't want to maintain this, so it - # needs to go either into jsonpointer (pending - # https://github.com/stefankoegl/python-json-pointer/issues/34) or - # into a new external library. - @_checks_drafts( - draft7="relative-json-pointer", - draft201909="relative-json-pointer", - draft202012="relative-json-pointer", - raises=jsonpointer.JsonPointerException, - ) - def is_relative_json_pointer(instance: object) -> bool: - # Definition taken from: - # https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3 - if not isinstance(instance, str): - return True - if not instance: - return False - - non_negative_integer, rest = [], "" - for i, character in enumerate(instance): - if character.isdigit(): - # digits with a leading "0" are not allowed - if i > 0 and int(instance[i - 1]) == 0: - return False - - non_negative_integer.append(character) - continue - - if not non_negative_integer: - return False - - rest = instance[i:] - break - return (rest == "#") or bool(jsonpointer.JsonPointer(rest)) - - -with suppress(ImportError): - import uri_template - - @_checks_drafts( - draft6="uri-template", - draft7="uri-template", - draft201909="uri-template", - draft202012="uri-template", - ) - def is_uri_template(instance: object) -> bool: - if not isinstance(instance, str): - return True - return uri_template.validate(instance) - - -with suppress(ImportError): - import isoduration - - @_checks_drafts( - draft201909="duration", - draft202012="duration", - raises=isoduration.DurationParsingException, - ) - def is_duration(instance: object) -> bool: - if not isinstance(instance, str): - return True - isoduration.parse_duration(instance) - # FIXME: See bolsote/isoduration#25 and bolsote/isoduration#21 - return instance.endswith(tuple("DMYWHMS")) - - -@_checks_drafts( - draft201909="uuid", - draft202012="uuid", - raises=ValueError, -) -def is_uuid(instance: object) -> bool: - if not isinstance(instance, str): - return True - UUID(instance) - return all(instance[position] == "-" for position in (8, 13, 18, 23)) diff --git a/spaces/deepskyreal/ai-mixer-hotchpotch/sad_talker/src/face3d/models/arcface_torch/configs/glint360k_r34.py b/spaces/deepskyreal/ai-mixer-hotchpotch/sad_talker/src/face3d/models/arcface_torch/configs/glint360k_r34.py deleted file mode 100644 index fda2701758a839a7161d09c25f0ca3d26033baff..0000000000000000000000000000000000000000 --- a/spaces/deepskyreal/ai-mixer-hotchpotch/sad_talker/src/face3d/models/arcface_torch/configs/glint360k_r34.py +++ /dev/null @@ -1,26 +0,0 @@ -from easydict import EasyDict as edict - -# make training faster -# our RAM is 256G -# mount -t tmpfs -o size=140G tmpfs /train_tmp - -config = edict() -config.loss = "cosface" -config.network = "r34" -config.resume = False -config.output = None -config.embedding_size = 512 -config.sample_rate = 1.0 -config.fp16 = True -config.momentum = 0.9 -config.weight_decay = 5e-4 -config.batch_size = 128 -config.lr = 0.1 # batch size is 512 - -config.rec = "/train_tmp/glint360k" -config.num_classes = 360232 -config.num_image = 17091657 -config.num_epoch = 20 -config.warmup_epoch = -1 -config.decay_epoch = [8, 12, 15, 18] -config.val_targets = ["lfw", "cfp_fp", "agedb_30"] diff --git a/spaces/deepwisdom/MetaGPT/tests/metagpt/roles/test_teacher.py b/spaces/deepwisdom/MetaGPT/tests/metagpt/roles/test_teacher.py deleted file mode 100644 index 8f673d6e0c862ae5e892117dc476860a68567780..0000000000000000000000000000000000000000 --- a/spaces/deepwisdom/MetaGPT/tests/metagpt/roles/test_teacher.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -@Time : 2023/7/27 13:25 -@Author : mashenquan -@File : test_teacher.py -""" - -from typing import Dict, Optional -from pydantic import BaseModel - -from metagpt.config import Config -from metagpt.provider.openai_api import CostManager -from metagpt.roles.teacher import Teacher - - -def test_init(): - class Inputs(BaseModel): - name: str - profile: str - goal: str - constraints: str - desc: str - kwargs: Optional[Dict] = None - expect_name: str - expect_profile: str - expect_goal: str - expect_constraints: str - expect_desc: str - - inputs = [ - { - "name": "Lily{language}", - "expect_name": "LilyCN", - "profile": "X {teaching_language}", - "expect_profile": "X EN", - "goal": "Do {something_big}, {language}", - "expect_goal": "Do sleep, CN", - "constraints": "Do in {key1}, {language}", - "expect_constraints": "Do in HaHa, CN", - "kwargs": {"language": "CN", "key1": "HaHa", "something_big": "sleep", "teaching_language": "EN"}, - "desc": "aaa{language}", - "expect_desc": "aaaCN" - }, - { - "name": "Lily{language}", - "expect_name": "Lily{language}", - "profile": "X {teaching_language}", - "expect_profile": "X {teaching_language}", - "goal": "Do {something_big}, {language}", - "expect_goal": "Do {something_big}, {language}", - "constraints": "Do in {key1}, {language}", - "expect_constraints": "Do in {key1}, {language}", - "kwargs": {}, - "desc": "aaa{language}", - "expect_desc": "aaa{language}" - }, - ] - - for i in inputs: - seed = Inputs(**i) - options = Config().runtime_options - cost_manager = CostManager(**options) - teacher = Teacher(options=options, cost_manager=cost_manager, name=seed.name, profile=seed.profile, - goal=seed.goal, constraints=seed.constraints, - desc=seed.desc, **seed.kwargs) - assert teacher.name == seed.expect_name - assert teacher.desc == seed.expect_desc - assert teacher.profile == seed.expect_profile - assert teacher.goal == seed.expect_goal - assert teacher.constraints == seed.expect_constraints - assert teacher.course_title == "teaching_plan" - - -def test_new_file_name(): - class Inputs(BaseModel): - lesson_title: str - ext: str - expect: str - - inputs = [ - { - "lesson_title": "# @344\n12", - "ext": ".md", - "expect": "_344_12.md" - }, - { - "lesson_title": "1#@$%!*&\\/:*?\"<>|\n\t \'1", - "ext": ".cc", - "expect": "1_1.cc" - } - ] - for i in inputs: - seed = Inputs(**i) - result = Teacher.new_file_name(seed.lesson_title, seed.ext) - assert result == seed.expect - - -if __name__ == '__main__': - test_init() - test_new_file_name() diff --git a/spaces/deprem-ml/deprem-ocr/README.md b/spaces/deprem-ml/deprem-ocr/README.md deleted file mode 100644 index 4de0567dfd8cbec54524e106e3c21e789541efa4..0000000000000000000000000000000000000000 --- a/spaces/deprem-ml/deprem-ocr/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Deprem OCR -emoji: 👀 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.17.0 -app_file: app.py -pinned: true ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/diacanFperku/AutoGPT/Epidemiologia Clinica Fletcher Pdf 31l.md b/spaces/diacanFperku/AutoGPT/Epidemiologia Clinica Fletcher Pdf 31l.md deleted file mode 100644 index 77ae963d6dc767576e9095c0e943a6da155d56e9..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Epidemiologia Clinica Fletcher Pdf 31l.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Epidemiologia Clinica Fletcher Pdf 31l


    Download Filehttps://gohhs.com/2uFTD7



    - -Epidemiologia Clinica Fletcher Pdf 31l ... fletcher 5ta edicion pdf, epidemiologia clinica fletcher booksmedicos, epidemiologia clinica fletcher pdf download,. 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/diaoren/OpenSetObstacleDetection/opendet2/modeling/backbone/__init__.py b/spaces/diaoren/OpenSetObstacleDetection/opendet2/modeling/backbone/__init__.py deleted file mode 100644 index f9cf81ceec9d7609b3229aa0a3cc57352f34005a..0000000000000000000000000000000000000000 --- a/spaces/diaoren/OpenSetObstacleDetection/opendet2/modeling/backbone/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .swin_transformer import SwinTransformer - -__all__ = [k for k in globals().keys() if not k.startswith("_")] \ No newline at end of file diff --git a/spaces/digitalxingtong/Miiu-Bert-Vits2/start.bat b/spaces/digitalxingtong/Miiu-Bert-Vits2/start.bat deleted file mode 100644 index 418d21233dbf720b0dd09821904d9d6a31b123a2..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Miiu-Bert-Vits2/start.bat +++ /dev/null @@ -1,2 +0,0 @@ -set PYTHON=venv\python.exe -start cmd /k "set PYTHON=%PYTHON%" \ No newline at end of file diff --git a/spaces/digitalxingtong/Shanbao-Bert-VITS2/models.py b/spaces/digitalxingtong/Shanbao-Bert-VITS2/models.py deleted file mode 100644 index d4afe44d883691610c5903e602a3ca245fcb3a5c..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Shanbao-Bert-VITS2/models.py +++ /dev/null @@ -1,707 +0,0 @@ -import copy -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -import modules -import attentions -import monotonic_align - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm - -from commons import init_weights, get_padding -from text import symbols, num_tones, num_languages -class DurationDiscriminator(nn.Module): #vits2 - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.dur_proj = nn.Conv1d(1, filter_channels, 1) - - self.pre_out_conv_1 = nn.Conv1d(2*filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.pre_out_norm_1 = modules.LayerNorm(filter_channels) - self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.pre_out_norm_2 = modules.LayerNorm(filter_channels) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - self.output_layer = nn.Sequential( - nn.Linear(filter_channels, 1), - nn.Sigmoid() - ) - - def forward_probability(self, x, x_mask, dur, g=None): - dur = self.dur_proj(dur) - x = torch.cat([x, dur], dim=1) - x = self.pre_out_conv_1(x * x_mask) - x = torch.relu(x) - x = self.pre_out_norm_1(x) - x = self.drop(x) - x = self.pre_out_conv_2(x * x_mask) - x = torch.relu(x) - x = self.pre_out_norm_2(x) - x = self.drop(x) - x = x * x_mask - x = x.transpose(1, 2) - output_prob = self.output_layer(x) - return output_prob - - def forward(self, x, x_mask, dur_r, dur_hat, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - - output_probs = [] - for dur in [dur_r, dur_hat]: - output_prob = self.forward_probability(x, x_mask, dur, g) - output_probs.append(output_prob) - - return output_probs - -class TransformerCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - n_flows=4, - gin_channels=0, - share_parameter=False - ): - - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - - self.wn = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = self.gin_channels) if share_parameter else None - - for i in range(n_flows): - self.flows.append( - modules.TransformerCouplingLayer(channels, hidden_channels, kernel_size, n_layers, n_heads, p_dropout, filter_channels, mean_only=True, wn_sharing_parameter=self.wn, gin_channels = self.gin_channels)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - -class StochasticDurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0): - super().__init__() - filter_channels = in_channels # it needs to be removed from future version. - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.log_flow = modules.Log() - self.flows = nn.ModuleList() - self.flows.append(modules.ElementwiseAffine(2)) - for i in range(n_flows): - self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.flows.append(modules.Flip()) - - self.post_pre = nn.Conv1d(1, filter_channels, 1) - self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - self.post_flows = nn.ModuleList() - self.post_flows.append(modules.ElementwiseAffine(2)) - for i in range(4): - self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.post_flows.append(modules.Flip()) - - self.pre = nn.Conv1d(in_channels, filter_channels, 1) - self.proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, filter_channels, 1) - - def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0): - x = torch.detach(x) - x = self.pre(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.convs(x, x_mask) - x = self.proj(x) * x_mask - - if not reverse: - flows = self.flows - assert w is not None - - logdet_tot_q = 0 - h_w = self.post_pre(w) - h_w = self.post_convs(h_w, x_mask) - h_w = self.post_proj(h_w) * x_mask - e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask - z_q = e_q - for flow in self.post_flows: - z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w)) - logdet_tot_q += logdet_q - z_u, z1 = torch.split(z_q, [1, 1], 1) - u = torch.sigmoid(z_u) * x_mask - z0 = (w - u) * x_mask - logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]) - logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q - - logdet_tot = 0 - z0, logdet = self.log_flow(z0, x_mask) - logdet_tot += logdet - z = torch.cat([z0, z1], 1) - for flow in flows: - z, logdet = flow(z, x_mask, g=x, reverse=reverse) - logdet_tot = logdet_tot + logdet - nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot - return nll + logq # [b] - else: - flows = list(reversed(self.flows)) - flows = flows[:-2] + [flows[-1]] # remove a useless vflow - z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale - for flow in flows: - z = flow(z, x_mask, g=x, reverse=reverse) - z0, z1 = torch.split(z, [1, 1], 1) - logw = z0 - return logw - - -class DurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.proj = nn.Conv1d(filter_channels, 1, 1) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - def forward(self, x, x_mask, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - x = self.proj(x * x_mask) - return x * x_mask - - -class TextEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=0): - super().__init__() - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - self.emb = nn.Embedding(len(symbols), hidden_channels) - nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5) - self.tone_emb = nn.Embedding(num_tones, hidden_channels) - nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels ** -0.5) - self.language_emb = nn.Embedding(num_languages, hidden_channels) - nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels ** -0.5) - self.bert_proj = nn.Conv1d(1024, hidden_channels, 1) - - self.encoder = attentions.Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=self.gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, tone, language, bert, g=None): - x = (self.emb(x)+ self.tone_emb(tone)+ self.language_emb(language)+self.bert_proj(bert).transpose(1,2)) * math.sqrt(self.hidden_channels) # [b, t, h] - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - x = self.encoder(x * x_mask, x_mask, g=g) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return x, m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, - gin_channels=gin_channels, mean_only=True)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - -class PosteriorEncoder(nn.Module): - def __init__(self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - -class Generator(torch.nn.Module): - def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, - upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) - resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append(weight_norm( - ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)), - k, u, padding=(k - u) // 2))) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - print('Removing weight norm...') - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), - ]) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ]) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - -class ReferenceEncoder(nn.Module): - ''' - inputs --- [N, Ty/r, n_mels*r] mels - outputs --- [N, ref_enc_gru_size] - ''' - - def __init__(self, spec_channels, gin_channels=0): - - super().__init__() - self.spec_channels = spec_channels - ref_enc_filters = [32, 32, 64, 64, 128, 128] - K = len(ref_enc_filters) - filters = [1] + ref_enc_filters - convs = [weight_norm(nn.Conv2d(in_channels=filters[i], - out_channels=filters[i + 1], - kernel_size=(3, 3), - stride=(2, 2), - padding=(1, 1))) for i in range(K)] - self.convs = nn.ModuleList(convs) - # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) - - out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K) - self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels, - hidden_size=256 // 2, - batch_first=True) - self.proj = nn.Linear(128, gin_channels) - - def forward(self, inputs, mask=None): - N = inputs.size(0) - out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs] - for conv in self.convs: - out = conv(out) - # out = wn(out) - out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K] - - out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K] - T = out.size(1) - N = out.size(0) - out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K] - - self.gru.flatten_parameters() - memory, out = self.gru(out) # out --- [1, N, 128] - - return self.proj(out.squeeze(0)) - - def calculate_channels(self, L, kernel_size, stride, pad, n_convs): - for i in range(n_convs): - L = (L - kernel_size + 2 * pad) // stride + 1 - return L - - -class SynthesizerTrn(nn.Module): - """ - Synthesizer for Training - """ - - def __init__(self, - n_vocab, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - n_speakers=256, - gin_channels=256, - use_sdp=True, - n_flow_layer = 4, - n_layers_trans_flow = 3, - flow_share_parameter = False, - use_transformer_flow = True, - **kwargs): - - super().__init__() - self.n_vocab = n_vocab - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.n_speakers = n_speakers - self.gin_channels = gin_channels - self.n_layers_trans_flow = n_layers_trans_flow - self.use_spk_conditioned_encoder = kwargs.get("use_spk_conditioned_encoder", True) - self.use_sdp = use_sdp - self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False) - self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01) - self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6) - self.current_mas_noise_scale = self.mas_noise_scale_initial - if self.use_spk_conditioned_encoder and gin_channels > 0: - self.enc_gin_channels = gin_channels - self.enc_p = TextEncoder(n_vocab, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=self.enc_gin_channels) - self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, - upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) - self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, - gin_channels=gin_channels) - if use_transformer_flow: - self.flow = TransformerCouplingBlock(inter_channels, hidden_channels, filter_channels, n_heads, n_layers_trans_flow, 5, p_dropout, n_flow_layer, gin_channels=gin_channels,share_parameter= flow_share_parameter) - else: - self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, n_flow_layer, gin_channels=gin_channels) - self.sdp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) - self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels) - - if n_speakers >= 1: - self.emb_g = nn.Embedding(n_speakers, gin_channels) - else: - self.ref_enc = ReferenceEncoder(spec_channels, gin_channels) - - def forward(self, x, x_lengths, y, y_lengths, sid, tone, language, bert): - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1) - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - - with torch.no_grad(): - # negative cross-entropy - s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t] - neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s] - neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), - s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s] - neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4 - if self.use_noise_scaled_mas: - epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale - neg_cent = neg_cent + epsilon - - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() - - w = attn.sum(2) - - l_length_sdp = self.sdp(x, x_mask, w, g=g) - l_length_sdp = l_length_sdp / torch.sum(x_mask) - - logw_ = torch.log(w + 1e-6) * x_mask - logw = self.dp(x, x_mask, g=g) - l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(x_mask) # for averaging - - l_length = l_length_dp + l_length_sdp - - # expand prior - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) - - z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size) - o = self.dec(z_slice, g=g) - return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (x, logw, logw_) - - def infer(self, x, x_lengths, sid, tone, language, bert, noise_scale=.667, length_scale=1, noise_scale_w=0.8, max_len=None, sdp_ratio=0,y=None): - #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert) - # g = self.gst(y) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1) - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g) - logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (sdp_ratio) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio) - w = torch.exp(logw) * x_mask * length_scale - w_ceil = torch.ceil(w) - y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long() - y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype) - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = commons.generate_path(w_ceil, attn_mask) - - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, - 2) # [b, t', t], [b, t, d] -> [b, d, t'] - - z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale - z = self.flow(z_p, y_mask, g=g, reverse=True) - o = self.dec((z * y_mask)[:, :, :max_len], g=g) - return o, attn, y_mask, (z, z_p, m_p, logs_p) diff --git a/spaces/doevent/blip/data/__init__.py b/spaces/doevent/blip/data/__init__.py deleted file mode 100644 index 0be209acf415855ea6ef753efedf903b5decb6b9..0000000000000000000000000000000000000000 --- a/spaces/doevent/blip/data/__init__.py +++ /dev/null @@ -1,101 +0,0 @@ -import torch -from torch.utils.data import DataLoader -from torchvision import transforms -from torchvision.transforms.functional import InterpolationMode - -from data.coco_karpathy_dataset import coco_karpathy_train, coco_karpathy_caption_eval, coco_karpathy_retrieval_eval -from data.nocaps_dataset import nocaps_eval -from data.flickr30k_dataset import flickr30k_train, flickr30k_retrieval_eval -from data.vqa_dataset import vqa_dataset -from data.nlvr_dataset import nlvr_dataset -from data.pretrain_dataset import pretrain_dataset -from transform.randaugment import RandomAugment - -def create_dataset(dataset, config, min_scale=0.5): - - normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) - - transform_train = transforms.Compose([ - transforms.RandomResizedCrop(config['image_size'],scale=(min_scale, 1.0),interpolation=InterpolationMode.BICUBIC), - transforms.RandomHorizontalFlip(), - RandomAugment(2,5,isPIL=True,augs=['Identity','AutoContrast','Brightness','Sharpness','Equalize', - 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']), - transforms.ToTensor(), - normalize, - ]) - transform_test = transforms.Compose([ - transforms.Resize((config['image_size'],config['image_size']),interpolation=InterpolationMode.BICUBIC), - transforms.ToTensor(), - normalize, - ]) - - if dataset=='pretrain': - dataset = pretrain_dataset(config['train_file'], config['laion_path'], transform_train) - return dataset - - elif dataset=='caption_coco': - train_dataset = coco_karpathy_train(transform_train, config['image_root'], config['ann_root'], prompt=config['prompt']) - val_dataset = coco_karpathy_caption_eval(transform_test, config['image_root'], config['ann_root'], 'val') - test_dataset = coco_karpathy_caption_eval(transform_test, config['image_root'], config['ann_root'], 'test') - return train_dataset, val_dataset, test_dataset - - elif dataset=='nocaps': - val_dataset = nocaps_eval(transform_test, config['image_root'], config['ann_root'], 'val') - test_dataset = nocaps_eval(transform_test, config['image_root'], config['ann_root'], 'test') - return val_dataset, test_dataset - - elif dataset=='retrieval_coco': - train_dataset = coco_karpathy_train(transform_train, config['image_root'], config['ann_root']) - val_dataset = coco_karpathy_retrieval_eval(transform_test, config['image_root'], config['ann_root'], 'val') - test_dataset = coco_karpathy_retrieval_eval(transform_test, config['image_root'], config['ann_root'], 'test') - return train_dataset, val_dataset, test_dataset - - elif dataset=='retrieval_flickr': - train_dataset = flickr30k_train(transform_train, config['image_root'], config['ann_root']) - val_dataset = flickr30k_retrieval_eval(transform_test, config['image_root'], config['ann_root'], 'val') - test_dataset = flickr30k_retrieval_eval(transform_test, config['image_root'], config['ann_root'], 'test') - return train_dataset, val_dataset, test_dataset - - elif dataset=='vqa': - train_dataset = vqa_dataset(transform_train, config['ann_root'], config['vqa_root'], config['vg_root'], - train_files = config['train_files'], split='train') - test_dataset = vqa_dataset(transform_test, config['ann_root'], config['vqa_root'], config['vg_root'], split='test') - return train_dataset, test_dataset - - elif dataset=='nlvr': - train_dataset = nlvr_dataset(transform_train, config['image_root'], config['ann_root'],'train') - val_dataset = nlvr_dataset(transform_test, config['image_root'], config['ann_root'],'val') - test_dataset = nlvr_dataset(transform_test, config['image_root'], config['ann_root'],'test') - return train_dataset, val_dataset, test_dataset - - -def create_sampler(datasets, shuffles, num_tasks, global_rank): - samplers = [] - for dataset,shuffle in zip(datasets,shuffles): - sampler = torch.utils.data.DistributedSampler(dataset, num_replicas=num_tasks, rank=global_rank, shuffle=shuffle) - samplers.append(sampler) - return samplers - - -def create_loader(datasets, samplers, batch_size, num_workers, is_trains, collate_fns): - loaders = [] - for dataset,sampler,bs,n_worker,is_train,collate_fn in zip(datasets,samplers,batch_size,num_workers,is_trains,collate_fns): - if is_train: - shuffle = (sampler is None) - drop_last = True - else: - shuffle = False - drop_last = False - loader = DataLoader( - dataset, - batch_size=bs, - num_workers=n_worker, - pin_memory=True, - sampler=sampler, - shuffle=shuffle, - collate_fn=collate_fn, - drop_last=drop_last, - ) - loaders.append(loader) - return loaders - diff --git a/spaces/dorkai/ChatUIPro/hooks/use-conversation.ts b/spaces/dorkai/ChatUIPro/hooks/use-conversation.ts deleted file mode 100644 index b77401624f153f9057a2cf723de9f2fe936c703e..0000000000000000000000000000000000000000 --- a/spaces/dorkai/ChatUIPro/hooks/use-conversation.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { useState } from 'react' -import type { ConversationItem } from '@/types/app' -import produce from 'immer' - -const storageConversationIdKey = 'conversationIdInfo' - -type ConversationInfoType = Omit -function useConversation() { - const [conversationList, setConversationList] = useState([]) - const [currConversationId, doSetCurrConversationId] = useState('-1') - // when set conversation id, we do not have set appId - const setCurrConversationId = (id: string, appId: string, isSetToLocalStroge = true, newConversationName = '') => { - doSetCurrConversationId(id) - if (isSetToLocalStroge && id !== '-1') { - // conversationIdInfo: {[appId1]: conversationId1, [appId2]: conversationId2} - const conversationIdInfo = globalThis.localStorage?.getItem(storageConversationIdKey) ? JSON.parse(globalThis.localStorage?.getItem(storageConversationIdKey) || '') : {} - conversationIdInfo[appId] = id - globalThis.localStorage?.setItem(storageConversationIdKey, JSON.stringify(conversationIdInfo)) - } - } - - const getConversationIdFromStorage = (appId: string) => { - const conversationIdInfo = globalThis.localStorage?.getItem(storageConversationIdKey) ? JSON.parse(globalThis.localStorage?.getItem(storageConversationIdKey) || '') : {} - const id = conversationIdInfo[appId] - return id - } - - const isNewConversation = currConversationId === '-1' - // input can be updated by user - const [newConversationInputs, setNewConversationInputs] = useState | null>(null) - const resetNewConversationInputs = () => { - if (!newConversationInputs) return - setNewConversationInputs(produce(newConversationInputs, draft => { - Object.keys(draft).forEach(key => { - draft[key] = '' - }) - })) - } - const [existConversationInputs, setExistConversationInputs] = useState | null>(null) - const currInputs = isNewConversation ? newConversationInputs : existConversationInputs - const setCurrInputs = isNewConversation ? setNewConversationInputs : setExistConversationInputs - - // info is muted - const [newConversationInfo, setNewConversationInfo] = useState(null) - const [existConversationInfo, setExistConversationInfo] = useState(null) - const currConversationInfo = isNewConversation ? newConversationInfo : existConversationInfo - - return { - conversationList, - setConversationList, - currConversationId, - setCurrConversationId, - getConversationIdFromStorage, - isNewConversation, - currInputs, - newConversationInputs, - existConversationInputs, - resetNewConversationInputs, - setCurrInputs, - currConversationInfo, - setNewConversationInfo, - setExistConversationInfo - } -} - -export default useConversation; \ No newline at end of file diff --git a/spaces/dumitrescustefan/NamedEntityRecognition-Romanian/app.py b/spaces/dumitrescustefan/NamedEntityRecognition-Romanian/app.py deleted file mode 100644 index 23e9a430bc112096b774b643bd40787129fc043a..0000000000000000000000000000000000000000 --- a/spaces/dumitrescustefan/NamedEntityRecognition-Romanian/app.py +++ /dev/null @@ -1,130 +0,0 @@ -import sentencepiece -import streamlit as st -import pandas as pd -import spacy -import roner - -example_list = [ - "George merge cu trenul Cluj - Timișoara de ora 6:20.", - "Președintele Statelor Unite, Joe Biden, a spus, vineri, că va trimite un număr de militari americani în Europa de Est „în curând”, ca urmare a situației tot mai tensionate din Ucraina. Președintele american a spus că „nu va trimite foarte mult” și a exclus din nou posibilitatea desfășurării de trupe în Ucraina, care nu face parte din Alianța Nord-Atlantică.", - "Deficitul bugetar a crescut semnificativ în ultima lună a anului trecut, cu 24,02 miliarde de lei, după ce, în noiembrie, Finanţele raportau un sold negativ de 4,7% din PIB, respectiv 55,98 miliarde de lei. Pe de altă parte, faţă de 2020, deficitul bugetar a consemnat o scădere importantă, de la 9,61% din PIB, respectiv 101,8 miliarde de lei.", - "Din anul 2050, doar 10 din cele 21 de locații care au găzduit Jocurile Olimpice de iarnă din 1924 și până în prezent vor avea zăpada naturală.", - "Al Doilea Război Mondial a fost un război global care a durat între anii 1939 - 1945.", -] - -st.set_page_config(layout="wide") - -st.title("Demo for Romanian NER") - -model_list = ['dumitrescustefan/bert-base-romanian-ner'] - -st.sidebar.header("Select NER Model") -model_checkpoint = st.sidebar.radio("", model_list) - - - - -st.sidebar.header("Select type of PERSON detection") -named_persons_only_radio = st.sidebar.radio("", ('Proper nouns only', 'All nouns')) - - -st.sidebar.write("This demo is based on RoNER: 'https://github.com/dumitrescustefan/roner'") -st.sidebar.write("") -st.sidebar.write("The NER corpus used is: 'https://github.com/dumitrescustefan/ronec'") -st.sidebar.write("Types of entities detected: 'PERSON', 'ORG', 'GPE', 'LOC', 'NAT_REL_POL', 'EVENT', 'LANGUAGE', 'WORK_OF_ART', 'DATETIME', 'PERIOD', 'MONEY', 'QUANTITY', 'NUMERIC', 'ORDINAL', 'FACILITY'") - -st.subheader("Select Text Input Method") -input_method = st.radio("", ('Select from Examples', 'Write or Paste New Text')) -if input_method == 'Select from Examples': - selected_text = st.selectbox('Select Text from List', example_list, index=0, key=1) - st.subheader("Text to Run") - input_text = st.text_area("Selected Text", selected_text, height=128, max_chars=None, key=2) -elif input_method == "Write or Paste New Text": - st.subheader("Text to Run") - input_text = st.text_area('Write or Paste Text Below', value="", height=128, max_chars=None, key=2) - -@st.cache(allow_output_mutation=True) -def setModel(named_persons_only): - ner = roner.NER(named_persons_only=named_persons_only) - return ner - -@st.cache(allow_output_mutation=True) -def get_html(html: str): - WRAPPER = """
    {}
    """ - html = html.replace("\n", " ") - return WRAPPER.format(html) - -Run_Button = st.button("Run", key=None) -if Run_Button == True: - - ner = setModel(named_persons_only = True if named_persons_only_radio.startswith("Proper") else False) - output = ner(input_text)[0] # only one sentence - - # tabular form - data = [] - for word in output["words"]: - if word["tag"]!="O": - data.append({ - "word": word["text"], - "entity": word["tag"], - "start_char": word["start_char"], - "end_char": word["end_char"], - "multi_word_entity (cont.)": word["multi_word_entity"] - }) - df = pd.DataFrame.from_dict(data) - st.subheader("Recognized Entities") - st.dataframe(df) - - - st.subheader("Spacy Style Display") - spacy_display = {} - spacy_display["ents"] = [] - spacy_display["text"] = output["text"] - spacy_display["title"] = None - - i = 0 - words = output["words"] - while i < len(words): - if words[i]["tag"]!="O": - start = words[i]["start_char"] - end = words[i]["end_char"] - label = words[i]["tag"] - - for j in range(i+1,len(words)): - if words[j]["tag"] == words[i]["tag"] and words[j]["multi_word_entity"] is True: - end = words[j]["end_char"] - i = j - else: - break - - spacy_display["ents"].append({"start": start, "end": end, "label": label}) - #print(f"ADD ENTITY: {spacy_display['ents'][-1]}") - i += 1 - - - - entity_list = ['PERSON', 'ORG', 'GPE', 'LOC', 'NAT_REL_POL', - 'EVENT', 'LANGUAGE', 'WORK_OF_ART', 'DATETIME', - 'PERIOD', 'MONEY', 'QUANTITY', 'NUMERIC', - 'ORDINAL', 'FACILITY'] - - colors = { - 'PERSON': '#E08989', - 'ORG': '#8477AC', - 'GPE': '#4C89AA', - 'LOC': '#34ABF8', - 'NAT_REL_POL': '#FADAD9', - 'EVENT': '#98654C', - 'LANGUAGE': '#F29E4C', - 'WORK_OF_ART': '#3ADAD9', - 'DATETIME': '#0DB39E', - 'PERIOD': '#83E377', - 'MONEY': '#16DB93', - 'QUANTITY': '#EFEA5A', - 'NUMERIC': '#B9E769', - 'ORDINAL': '#F1C453', - 'FACILITY': '#E0DADA', - } - html = spacy.displacy.render(spacy_display, style="ent", minify=True, manual=True, options={"ents": entity_list, "colors": colors}) - style = "" - st.write(f"{style}{get_html(html)}", unsafe_allow_html=True) \ No newline at end of file diff --git a/spaces/duycse1603/math2tex/HybridViT/module/component/prediction_head/seq2seq_v2.py b/spaces/duycse1603/math2tex/HybridViT/module/component/prediction_head/seq2seq_v2.py deleted file mode 100644 index 20eec35c9de355720de2a5a1848f1a858b8485fd..0000000000000000000000000000000000000000 --- a/spaces/duycse1603/math2tex/HybridViT/module/component/prediction_head/seq2seq_v2.py +++ /dev/null @@ -1,218 +0,0 @@ -import random -import torch -import torch.nn as nn -import torch.nn.functional as F -from einops import repeat -from ...converter import AttnLabelConverter as ATTN -from .addon_module import * -from .seq2seq import Attention - - -class AttentionV2(Attention): - def forward_beam( - self, - batch_H: torch.Tensor, - batch_max_length=25, - beam_size=4, - ): - batch_size = batch_H.size(0) - assert batch_size == 1 - num_steps = batch_max_length + 1 - batch_H = batch_H.squeeze(dim=0) - batch_H = repeat(batch_H, "s e -> b s e", b = beam_size) - - encoder_hidden = None - if self.seqmodel in ['BiLSTM', 'VIG']: - encoder_hidden = batch_H - elif self.seqmodel == 'TFM': - encoder_hidden = batch_H[:, 1:, :] - else: - raise ValueError('seqmodel must be either BiLSTM or TFM option') - - if self.enc_init: - init_embedding = None - if self.seqmodel in ['BiLSTM', 'VIG']: - init_embedding = batch_H.mean(dim=1) - elif self.seqmodel == 'TFM': - init_embedding = batch_H[:, 0, :] - else: - raise ValueError('seqmodel must be either BiLSTM or TFM option') - - assert init_embedding is not None - h_0 = self.proj_init_h(init_embedding) - c_0 = self.proj_init_c(init_embedding) - hidden = (h_0, c_0) - else: - hidden = (torch.zeros(beam_size, self.hidden_size, dtype=torch.float32, device=self.device), - torch.zeros(beam_size, self.hidden_size, dtype=torch.float32, device=self.device)) - - assert encoder_hidden is not None - - if self.attn_type == 'coverage': - alpha_cum = torch.zeros(beam_size, encoder_hidden.shape[1], 1, dtype=torch.float32, device=self.device) - self.attention_cell.reset_mem() - - k_prev_words = torch.LongTensor([[ATTN.START()]] * beam_size).to(self.device) - seqs = k_prev_words - targets = k_prev_words.squeeze(dim=-1) - top_k_scores = torch.zeros(beam_size, 1).to(self.device) - - if self.viz_attn: - seqs_alpha = torch.ones(beam_size, 1, encoder_hidden.shape[1]).to(self.device) - - complete_seqs = list() - if self.viz_attn: - complete_seqs_alpha = list() - complete_seqs_scores = list() - - for step in range(num_steps): - embed_text = self._char_to_onehot(targets, onehot_dim=self.num_classes) if not self.embed_target else self._embed_text(targets) - output, hidden, alpha = self.attention_cell(hidden, encoder_hidden, embed_text) - output = self.dropout(output) - vocab_size = output.shape[1] - - scores = F.log_softmax(output, dim=-1) - scores = top_k_scores.expand_as(scores) + scores - if step == 0: - top_k_scores, top_k_words = scores[0].topk(beam_size, 0, True, True) - else: - top_k_scores, top_k_words = scores.view(-1).topk(beam_size, 0, True, True) - - prev_word_inds = top_k_words // vocab_size - next_word_inds = top_k_words % vocab_size - - seqs = torch.cat([seqs[prev_word_inds], next_word_inds.unsqueeze(1)], dim=1) - if self.viz_attn: - seqs_alpha = torch.cat([seqs_alpha[prev_word_inds], alpha[prev_word_inds].permute(0, 2, 1)], - dim=1) - - incomplete_inds = [ind for ind, next_word in enumerate(next_word_inds) if - next_word != ATTN.END()] - - complete_inds = list(set(range(len(next_word_inds))) - set(incomplete_inds)) - - if len(complete_inds) > 0: - complete_seqs.extend(seqs[complete_inds].tolist()) - if self.viz_attn: - complete_seqs_alpha.extend(seqs_alpha[complete_inds]) - complete_seqs_scores.extend(top_k_scores[complete_inds]) - - beam_size = beam_size - len(complete_inds) - if beam_size == 0: - break - - seqs = seqs[incomplete_inds] - if self.viz_attn: - seqs_alpha = seqs_alpha[incomplete_inds] - hidden = hidden[0][prev_word_inds[incomplete_inds]], \ - hidden[1][prev_word_inds[incomplete_inds]] - encoder_hidden = encoder_hidden[prev_word_inds[incomplete_inds]] - top_k_scores = top_k_scores[incomplete_inds].unsqueeze(1) - targets = next_word_inds[incomplete_inds] - - if self.attn_type == 'coverage': - alpha_cum = alpha_cum + alpha - alpha_cum = alpha_cum[incomplete_inds] - self.attention_cell.set_mem(alpha_cum) - elif self.attn_type == 'loc_aware': - self.attention_cell.set_mem(alpha) - - if len(complete_inds) == 0: - seq = seqs[0][1:].tolist() - seq = torch.LongTensor(seq).unsqueeze(0) - score = top_k_scores[0] - if self.viz_attn: - alphas = seqs_alpha[0][1:, ...] - return seq, score, alphas - else: - return seq, score, None - else: - combine_lst = tuple(zip(complete_seqs, complete_seqs_scores)) - best_ind = combine_lst.index(max(combine_lst, key=lambda x: x[1] / len(x[0]))) #https://youtu.be/XXtpJxZBa2c?t=2407 - seq = complete_seqs[best_ind][1:] #not include [GO] token - seq = torch.LongTensor(seq).unsqueeze(0) - score = max(complete_seqs_scores) - - if self.viz_attn: - alphas = complete_seqs_alpha[best_ind][1:, ...] - return seq, score, alphas - else: - return seq, score, None - - def forward_greedy(self, batch_H, text, is_train=True, is_test=False, batch_max_length=25): - batch_size = batch_H.size(0) - num_steps = batch_max_length + 1 - encoder_hidden = None - if self.seqmodel in ['BiLSTM', 'VIG']: - encoder_hidden = batch_H - elif self.seqmodel == 'TFM': - encoder_hidden = batch_H[:, 1:, :] - else: - raise ValueError('seqmodel must be either BiLSTM or TFM option') - - if self.enc_init: - init_embedding = None - if self.seqmodel in ['BiLSTM', 'VIG']: - init_embedding = batch_H.mean(dim=1) - elif self.seqmodel == 'TFM': - init_embedding = batch_H[:, 0, :] - else: - raise ValueError('seqmodel must be either BiLSTM or TFM option') - h_0 = self.proj_init_h(init_embedding) - c_0 = self.proj_init_c(init_embedding) - hidden = (h_0, c_0) - else: - hidden = (torch.zeros(batch_size, self.hidden_size, dtype=torch.float32, device=self.device), - torch.zeros(batch_size, self.hidden_size, dtype=torch.float32, device=self.device)) - - targets = torch.zeros(batch_size, dtype=torch.long, device=self.device) # [GO] token - probs = torch.zeros(batch_size, num_steps, self.num_classes, dtype=torch.float32, device=self.device) - - assert encoder_hidden is not None - - if self.viz_attn: - self.alpha_stores = torch.zeros(batch_size, num_steps, encoder_hidden.shape[1], 1, dtype=torch.float32, device=self.device) - if self.attn_type == 'coverage': - alpha_cum = torch.zeros(batch_size, encoder_hidden.shape[1], 1, dtype=torch.float32, device=self.device) - - self.attention_cell.reset_mem() - - if is_test: - end_flag = torch.zeros(batch_size, dtype=torch.bool, device=self.device) - - for i in range(num_steps): - embed_text = self._char_to_onehot(targets, onehot_dim=self.num_classes) if not self.embed_target else self._embed_text(targets) - output, hidden, alpha = self.attention_cell(hidden, encoder_hidden, embed_text) - output = self.dropout(output) - if self.viz_attn: - self.alpha_stores[:, i] = alpha - if self.attn_type == 'coverage': - alpha_cum = alpha_cum + alpha - self.attention_cell.set_mem(alpha_cum) - elif self.attn_type == 'loc_aware': - self.attention_cell.set_mem(alpha) - - probs_step = output - probs[:, i, :] = probs_step - - if i == num_steps - 1: - break - - if is_train: - if self.teacher_forcing < random.random(): - _, next_input = probs_step.max(1) - targets = next_input - else: - targets = text[:, i+1] - else: - _, next_input = probs_step.max(1) - targets = next_input - - if is_test: - end_flag = end_flag | (next_input == ATTN.END()) - if end_flag.all(): - break - - _, preds_index = probs.max(2) - - return preds_index, probs, None # batch_size x num_steps x num_classes diff --git a/spaces/dwolfe66/text-generation-webui-space/run.py b/spaces/dwolfe66/text-generation-webui-space/run.py deleted file mode 100644 index 5fa7ad38bf6c6c533d170074690124231000532d..0000000000000000000000000000000000000000 --- a/spaces/dwolfe66/text-generation-webui-space/run.py +++ /dev/null @@ -1,4 +0,0 @@ -import os -os.system('python download-model.py PygmalionAI/pygmalion-350m --branch main') -# os.system('python download-model.py waifu-workshop/pygmalion-6b --branch original-sharded') -os.system('python server.py --cpu --cai-chat --model pygmalion-350m') \ No newline at end of file diff --git a/spaces/eaglelandsonce/weatherQnA/README.md b/spaces/eaglelandsonce/weatherQnA/README.md deleted file mode 100644 index 629de04a0534881deac96c08fc68e2b6e3693f85..0000000000000000000000000000000000000000 --- a/spaces/eaglelandsonce/weatherQnA/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Weather Q&A -emoji: 🏆 -colorFrom: gray -colorTo: gray -sdk: streamlit -sdk_version: 1.27.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/effluxriad/YouTube-comments-generator/model/datasetBuilding.py b/spaces/effluxriad/YouTube-comments-generator/model/datasetBuilding.py deleted file mode 100644 index 4ad4358eb14e59993446b7e4a3299c6f172078cf..0000000000000000000000000000000000000000 --- a/spaces/effluxriad/YouTube-comments-generator/model/datasetBuilding.py +++ /dev/null @@ -1,43 +0,0 @@ -import pandas as pd -import math -from typing import Tuple - - -def build_dataset(path_to_video_info_file: str = "../data/USvideos.csv", - path_to_video_comments_file: str = "../data/UScomments.csv" - ) -> pd.DataFrame: - # video info - df_video_info = pd.read_csv(path_to_video_info_file, - sep=',', - quotechar='"', - skipinitialspace=True, - on_bad_lines='skip', - header=0) - df_video_info = df_video_info.drop( - columns=["channel_title", "category_id", "tags", "views", "likes", "dislikes", "comment_total", - "thumbnail_link", "date"]) - # tags could be left as a feature - - # video comments - df_comments = pd.read_csv(path_to_video_comments_file, - sep=',', - quotechar='"', - skipinitialspace=True, - on_bad_lines='skip', - header=0) - df_comments = df_comments.drop(columns=["likes", "replies"]) - - # concatenating dataframes - dataframe = df_comments.merge(df_video_info, on="video_id", how="inner").drop_duplicates() - - return dataframe - - -def train_test_dataset_split(dataframe: pd.DataFrame, ratio: float = 0.9) -> Tuple[pd.Series, pd.Series]: - rows_cnt = len(dataframe) - train_rows_cnt = int(math.ceil(ratio * rows_cnt)) - - train_frame = dataframe[:train_rows_cnt] - test_frame = dataframe[train_rows_cnt:] - - return train_frame, test_frame diff --git a/spaces/errorok/rvc-models-en-test/infer_pack/commons.py b/spaces/errorok/rvc-models-en-test/infer_pack/commons.py deleted file mode 100644 index 54470986f37825b35d90d7efa7437d1c26b87215..0000000000000000000000000000000000000000 --- a/spaces/errorok/rvc-models-en-test/infer_pack/commons.py +++ /dev/null @@ -1,166 +0,0 @@ -import math -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - - -def init_weights(m, mean=0.0, std=0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size * dilation - dilation) / 2) - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def kl_divergence(m_p, logs_p, m_q, logs_q): - """KL(P||Q)""" - kl = (logs_q - logs_p) - 0.5 - kl += ( - 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q) - ) - return kl - - -def rand_gumbel(shape): - """Sample from the Gumbel distribution, protect from overflows.""" - uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 - return -torch.log(-torch.log(uniform_samples)) - - -def rand_gumbel_like(x): - g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) - return g - - -def slice_segments(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - ret[i] = x[i, :, idx_str:idx_end] - return ret - - -def slice_segments2(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - ret[i] = x[i, idx_str:idx_end] - return ret - - -def rand_slice_segments(x, x_lengths=None, segment_size=4): - b, d, t = x.size() - if x_lengths is None: - x_lengths = t - ids_str_max = x_lengths - segment_size + 1 - ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) - ret = slice_segments(x, ids_str, segment_size) - return ret, ids_str - - -def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length, dtype=torch.float) - num_timescales = channels // 2 - log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / ( - num_timescales - 1 - ) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment - ) - scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) - signal = F.pad(signal, [0, 0, 0, channels % 2]) - signal = signal.view(1, channels, length) - return signal - - -def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return x + signal.to(dtype=x.dtype, device=x.device) - - -def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis) - - -def subsequent_mask(length): - mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) - return mask - - -@torch.jit.script -def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): - n_channels_int = n_channels[0] - in_act = input_a + input_b - t_act = torch.tanh(in_act[:, :n_channels_int, :]) - s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) - acts = t_act * s_act - return acts - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -def generate_path(duration, mask): - """ - duration: [b, 1, t_x] - mask: [b, 1, t_y, t_x] - """ - device = duration.device - - b, _, t_y, t_x = mask.shape - cum_duration = torch.cumsum(duration, -1) - - cum_duration_flat = cum_duration.view(b * t_x) - path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) - path = path.view(b, t_x, t_y) - path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] - path = path.unsqueeze(1).transpose(2, 3) * mask - return path - - -def clip_grad_value_(parameters, clip_value, norm_type=2): - if isinstance(parameters, torch.Tensor): - parameters = [parameters] - parameters = list(filter(lambda p: p.grad is not None, parameters)) - norm_type = float(norm_type) - if clip_value is not None: - clip_value = float(clip_value) - - total_norm = 0 - for p in parameters: - param_norm = p.grad.data.norm(norm_type) - total_norm += param_norm.item() ** norm_type - if clip_value is not None: - p.grad.data.clamp_(min=-clip_value, max=clip_value) - total_norm = total_norm ** (1.0 / norm_type) - return total_norm diff --git a/spaces/evaluate-metric/recall/README.md b/spaces/evaluate-metric/recall/README.md deleted file mode 100644 index 58b021c0709484732e0e0524735e7a6a51e44f3f..0000000000000000000000000000000000000000 --- a/spaces/evaluate-metric/recall/README.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Recall -emoji: 🤗 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.19.1 -app_file: app.py -pinned: false -tags: -- evaluate -- metric -description: >- - Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: - Recall = TP / (TP + FN) - Where TP is the true positives and FN is the false negatives. ---- - -# Metric Card for Recall - - -## Metric Description - -Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: -Recall = TP / (TP + FN) -Where TP is the number of true positives and FN is the number of false negatives. - - -## How to Use - -At minimum, this metric takes as input two `list`s, each containing `int`s: predictions and references. - -```python ->>> recall_metric = evaluate.load('recall') ->>> results = recall_metric.compute(references=[0, 1], predictions=[0, 1]) ->>> print(results) -["{'recall': 1.0}"] -``` - - -### Inputs -- **predictions** (`list` of `int`): The predicted labels. -- **references** (`list` of `int`): The ground truth labels. -- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. -- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`. -- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). -- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. -- **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised. - - `0`: If there is a zero division, the return value is `0`. - - `1`: If there is a zero division, the return value is `1`. - - -### Output Values -- **recall**(`float`, or `array` of `float`, for multiclass targets): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. - -Output Example(s): -```python -{'recall': 1.0} -``` -```python -{'recall': array([1., 0., 0.])} -``` - -This metric outputs a dictionary with one entry, `'recall'`. - - -#### Values from Popular Papers - - -### Examples - -Example 1-A simple example with some errors -```python ->>> recall_metric = evaluate.load('recall') ->>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) ->>> print(results) -{'recall': 0.6666666666666666} -``` - -Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. -```python ->>> recall_metric = evaluate.load('recall') ->>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) ->>> print(results) -{'recall': 0.5} -``` - -Example 3-The same example as Example 1, but with `sample_weight` included. -```python ->>> recall_metric = evaluate.load('recall') ->>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] ->>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) ->>> print(results) -{'recall': 0.55} -``` - -Example 4-A multiclass example, using different averages. -```python ->>> recall_metric = evaluate.load('recall') ->>> predictions = [0, 2, 1, 0, 0, 1] ->>> references = [0, 1, 2, 0, 1, 2] ->>> results = recall_metric.compute(predictions=predictions, references=references, average='macro') ->>> print(results) -{'recall': 0.3333333333333333} ->>> results = recall_metric.compute(predictions=predictions, references=references, average='micro') ->>> print(results) -{'recall': 0.3333333333333333} ->>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted') ->>> print(results) -{'recall': 0.3333333333333333} ->>> results = recall_metric.compute(predictions=predictions, references=references, average=None) ->>> print(results) -{'recall': array([1., 0., 0.])} -``` - - -## Limitations and Bias - - -## Citation(s) -```bibtex -@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} -``` - - -## Further References diff --git "a/spaces/f2api/gpt-academic/crazy_functions/\344\273\243\347\240\201\351\207\215\345\206\231\344\270\272\345\205\250\350\213\261\346\226\207_\345\244\232\347\272\277\347\250\213.py" "b/spaces/f2api/gpt-academic/crazy_functions/\344\273\243\347\240\201\351\207\215\345\206\231\344\270\272\345\205\250\350\213\261\346\226\207_\345\244\232\347\272\277\347\250\213.py" deleted file mode 100644 index e57f80f1d45bd3ec23837253848f7b32a5ccd751..0000000000000000000000000000000000000000 --- "a/spaces/f2api/gpt-academic/crazy_functions/\344\273\243\347\240\201\351\207\215\345\206\231\344\270\272\345\205\250\350\213\261\346\226\207_\345\244\232\347\272\277\347\250\213.py" +++ /dev/null @@ -1,138 +0,0 @@ -import threading -from request_llm.bridge_all import predict_no_ui_long_connection -from toolbox import update_ui -from toolbox import CatchException, write_results_to_file, report_execption -from .crazy_utils import breakdown_txt_to_satisfy_token_limit - -def extract_code_block_carefully(txt): - splitted = txt.split('```') - n_code_block_seg = len(splitted) - 1 - if n_code_block_seg <= 1: return txt - # 剩下的情况都开头除去 ``` 结尾除去一次 ``` - txt_out = '```'.join(splitted[1:-1]) - return txt_out - - - -def break_txt_into_half_at_some_linebreak(txt): - lines = txt.split('\n') - n_lines = len(lines) - pre = lines[:(n_lines//2)] - post = lines[(n_lines//2):] - return "\n".join(pre), "\n".join(post) - - -@CatchException -def 全项目切换英文(txt, llm_kwargs, plugin_kwargs, chatbot, history, sys_prompt, web_port): - # 第1步:清空历史,以免输入溢出 - history = [] - - # 第2步:尝试导入依赖,如果缺少依赖,则给出安装建议 - 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 - - # 第3步:集合文件 - import time, glob, os, shutil, re - os.makedirs('gpt_log/generated_english_version', exist_ok=True) - os.makedirs('gpt_log/generated_english_version/crazy_functions', exist_ok=True) - file_manifest = [f for f in glob.glob('./*.py') if ('test_project' not in f) and ('gpt_log' not in f)] + \ - [f for f in glob.glob('./crazy_functions/*.py') if ('test_project' not in f) and ('gpt_log' not in f)] - # file_manifest = ['./toolbox.py'] - i_say_show_user_buffer = [] - - # 第4步:随便显示点什么防止卡顿的感觉 - for index, fp in enumerate(file_manifest): - # if 'test_project' in fp: continue - with open(fp, 'r', encoding='utf-8', errors='replace') as f: - file_content = f.read() - i_say_show_user =f'[{index}/{len(file_manifest)}] 接下来请将以下代码中包含的所有中文转化为英文,只输出转化后的英文代码,请用代码块输出代码: {os.path.abspath(fp)}' - i_say_show_user_buffer.append(i_say_show_user) - chatbot.append((i_say_show_user, "[Local Message] 等待多线程操作,中间过程不予显示.")) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - - # 第5步:Token限制下的截断与处理 - MAX_TOKEN = 3000 - from request_llm.bridge_all import model_info - enc = model_info["gpt-3.5-turbo"]['tokenizer'] - def get_token_fn(txt): return len(enc.encode(txt, disallowed_special=())) - - - # 第6步:任务函数 - mutable_return = [None for _ in file_manifest] - observe_window = [[""] for _ in file_manifest] - def thread_worker(fp,index): - if index > 10: - time.sleep(60) - print('Openai 限制免费用户每分钟20次请求,降低请求频率中。') - with open(fp, 'r', encoding='utf-8', errors='replace') as f: - file_content = f.read() - i_say_template = lambda fp, file_content: f'接下来请将以下代码中包含的所有中文转化为英文,只输出代码,文件名是{fp},文件代码是 ```{file_content}```' - try: - gpt_say = "" - # 分解代码文件 - file_content_breakdown = breakdown_txt_to_satisfy_token_limit(file_content, get_token_fn, MAX_TOKEN) - for file_content_partial in file_content_breakdown: - i_say = i_say_template(fp, file_content_partial) - # # ** gpt request ** - gpt_say_partial = predict_no_ui_long_connection(inputs=i_say, llm_kwargs=llm_kwargs, history=[], sys_prompt=sys_prompt, observe_window=observe_window[index]) - gpt_say_partial = extract_code_block_carefully(gpt_say_partial) - gpt_say += gpt_say_partial - mutable_return[index] = gpt_say - except ConnectionAbortedError as token_exceed_err: - print('至少一个线程任务Token溢出而失败', e) - except Exception as e: - print('至少一个线程任务意外失败', e) - - # 第7步:所有线程同时开始执行任务函数 - handles = [threading.Thread(target=thread_worker, args=(fp,index)) for index, fp in enumerate(file_manifest)] - for h in handles: - h.daemon = True - h.start() - chatbot.append(('开始了吗?', f'多线程操作已经开始')) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 第8步:循环轮询各个线程是否执行完毕 - cnt = 0 - while True: - cnt += 1 - time.sleep(0.2) - th_alive = [h.is_alive() for h in handles] - if not any(th_alive): break - # 更好的UI视觉效果 - observe_win = [] - for thread_index, alive in enumerate(th_alive): - observe_win.append("[ ..."+observe_window[thread_index][0][-60:].replace('\n','').replace('```','...').replace(' ','.').replace('
    ','.....').replace('$','.')+"... ]") - stat = [f'执行中: {obs}\n\n' if alive else '已完成\n\n' for alive, obs in zip(th_alive, observe_win)] - stat_str = ''.join(stat) - chatbot[-1] = (chatbot[-1][0], f'多线程操作已经开始,完成情况: \n\n{stat_str}' + ''.join(['.']*(cnt%10+1))) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 第9步:把结果写入文件 - for index, h in enumerate(handles): - h.join() # 这里其实不需要join了,肯定已经都结束了 - fp = file_manifest[index] - gpt_say = mutable_return[index] - i_say_show_user = i_say_show_user_buffer[index] - - where_to_relocate = f'gpt_log/generated_english_version/{fp}' - if gpt_say is not None: - with open(where_to_relocate, 'w+', encoding='utf-8') as f: - f.write(gpt_say) - else: # 失败 - shutil.copyfile(file_manifest[index], where_to_relocate) - chatbot.append((i_say_show_user, f'[Local Message] 已完成{os.path.abspath(fp)}的转化,\n\n存入{os.path.abspath(where_to_relocate)}')) - history.append(i_say_show_user); history.append(gpt_say) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - time.sleep(1) - - # 第10步:备份一个文件 - res = write_results_to_file(history) - chatbot.append(("生成一份任务执行报告", res)) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 diff --git a/spaces/falterWliame/Face_Mask_Detection/Crossout - Wasteland Warrior Pack Crack EXCLUSIVE Unlock Code And Serial.md b/spaces/falterWliame/Face_Mask_Detection/Crossout - Wasteland Warrior Pack Crack EXCLUSIVE Unlock Code And Serial.md deleted file mode 100644 index 390aed9b0fe82b74ff1da6202c4dd458d872a282..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Crossout - Wasteland Warrior Pack Crack EXCLUSIVE Unlock Code And Serial.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Crossout - Wasteland Warrior Pack crack unlock code and serial


    DOWNLOAD ✏ ✏ ✏ https://urlca.com/2uDdGN



    -
    -Cross out text. ... Day turned into wasteland. ... Request service today at my code to activate and deactivate element automatically. ... Draw image on any word to describe to me it could crack. ... 7733496266 Maybe you saw the double celebration gift pack. ... A perpetual design with sophisticated styling for a limited series? 1fdad05405
    -
    -
    -

    diff --git a/spaces/fatiXbelha/sd/Download Free Fire OB39 Advance Server APK and get your unique Activation Code.md b/spaces/fatiXbelha/sd/Download Free Fire OB39 Advance Server APK and get your unique Activation Code.md deleted file mode 100644 index 2d2a6c0bbac7405aaafd01cabd6ec796050d96d1..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Free Fire OB39 Advance Server APK and get your unique Activation Code.md +++ /dev/null @@ -1,126 +0,0 @@ - -

    How to Download and Play Free Fire Advance Server

    -

    Free Fire is one of the most popular and exciting battle royale games on mobile, with over 500 million downloads on Google Play Store. The game offers a variety of game modes, characters, weapons, and maps for players to enjoy. However, if you want to experience the unreleased features and content of the game before anyone else, you can try playing on the Free Fire Advance Server.

    -

    free fire advance server download code


    Download Ziphttps://urllie.com/2uNz1S



    -

    What is Free Fire Advance Server?

    -

    Free Fire Advance Server is a testing server where players can access the upcoming updates and patches of the game before they are officially released. The purpose of the Advance Server is to allow players to test the new features and provide feedback and bug reports to the developers. By playing on the Advance Server, you can also earn free diamonds by reporting bugs and glitches.

    -

    The benefits of playing on Advance Server

    -

    There are many benefits of playing on the Free Fire Advance Server, such as:

    -
      -
    • You can enjoy the new features, modes, characters, weapons, and maps before anyone else.
    • -
    • You can help the developers improve the game by providing feedback and bug reports.
    • -
    • You can earn free diamonds by reporting bugs and glitches.
    • -
    • You can have fun and challenge yourself by playing with other advanced players.
    • -
    -

    The requirements and limitations of Advance Server

    -

    However, there are also some requirements and limitations of playing on the Free Fire Advance Server, such as:

    -
      -
    • You need to register on the official website and get an Activation Code to access the server.
    • -
    • You need to download and install a separate APK file for the Advance Server.
    • -
    • You need to have a stable internet connection and enough storage space on your device.
    • -
    • You can only play on the Advance Server during a specific period of time, usually before a new update is released.
    • -
    • You may encounter some bugs, glitches, or errors while playing on the Advance Server.
    • -
    • Your progress and data on the Advance Server will not be transferred to your main account.
    • -
    -

    How to Register and Get Activation Code for Advance Server

    -

    If you are interested in playing on the Free Fire Advance Server, you need to register on the official website and get an Activation Code. Here are the steps to do so:

    -

    How to get free fire advance server activation code
    -Free fire advance server apk download link
    -Free fire ob40 advance server end date
    -Free fire ob39 advance server registration
    -Free fire advance server code generator
    -Free fire advance server apk ob28
    -Free fire advance server code 2023
    -Free fire advance server apk ob40
    -Free fire advance server code today
    -Free fire advance server apk ob39
    -Free fire advance server code giveaway
    -Free fire advance server apk latest version
    -Free fire advance server code redeem
    -Free fire advance server apk download 2023
    -Free fire advance server code free
    -Free fire advance server apk download ob28
    -Free fire advance server code not working
    -Free fire advance server apk download ob40
    -Free fire advance server code expired
    -Free fire advance server apk download ob39
    -Free fire advance server code email
    -Free fire advance server apk mod menu
    -Free fire advance server code update
    -Free fire advance server apk unlimited diamonds
    -Free fire advance server code how to get
    -Free fire advance server apk for android
    -Free fire advance server code new
    -Free fire advance server apk for ios
    -Free fire advance server code list
    -Free fire advance server apk for pc
    -Free fire advance server code 2022
    -Free fire advance server apk size
    -Free fire advance server code hack
    -Free fire advance server apk install
    -Free fire advance server code may 2023
    -Free fire advance server apk features
    -Free fire advance server code march 2023
    -Free fire advance server apk requirements
    -Free fire advance server code april 2023
    -Free fire advance server apk problem
    -Free fire advance server code june 2023
    -Free fire advance server apk error
    -Free fire advance server code july 2023
    -Free fire advance server apk review
    -Free fire advance server code august 2023
    -Free fire advance server apk gameplay
    -Free fire advance server code september 2023
    -Free fire advance server apk bug report

    -

    The steps to register on the official website

    -
      -
    1. Visit the official website of Free Fire Advance Server at [12](https://ff-advance.ff.garena.com/).
    2. -
    3. Log in with your Facebook or Google account that is linked to your Free Fire account.
    4. -
    5. Fill in your personal details, such as your name, email address, phone number, etc.
    6. -
    7. Click on "Join Now" to complete your registration.
    8. -
    -

    The steps to download and install the APK file

    -
      -
    1. After registering, you will be redirected to the download page where you can see your Activation Code and the APK download link.
    2. -
    3. Copy your Activation Code and click on the APK download link to download the file.
    4. -
    5. Once downloaded, locate the file on your device and install it. You may need to enable "Unknown Sources" in your settings to install apps from outside sources.
    6. -
    -

    The steps to enter the Activation Code and access the server

    -
      -
    1. After installing, open the app and log in with your Facebook or Google account that is linked to your Free Fire account.
    2. -
    3. Enter your Activation Code when prompted and tap on "OK".
    4. If you entered the correct code, you will be able to access the Free Fire Advance Server and play the game. -
    -

    How to Enjoy the New Features and Modes on Advance Server

    -

    Once you are on the Free Fire Advance Server, you can enjoy the new features and modes that are not available on the regular server. Here are some of the latest updates and changes on the Advance Server and some tips and tricks to improve your gameplay and performance.

    -

    The overview of the latest updates and changes on Advance Server

    -

    According to the official website, some of the new features and modes that are currently available on the Advance Server are:

    -
      -
    • A new character named Ricardo who has a passive skill called Deadly Aura that reduces the damage taken from enemies within 6 meters by 10%.
    • -
    • A new weapon called AC80 which is a marksman rifle that can fire two bullets at once and deal high damage.
    • -
    • A new mode called Bomb Squad which is similar to the classic mode but with a twist. In this mode, there are two teams of four players each, and one team has to plant a bomb at a designated spot while the other team has to defuse it or eliminate the enemies.
    • -
    • A new map called Bermuda Remastered which is an updated version of the original Bermuda map with new locations, graphics, and details.
    • -
    • A new pet called Rockie who has a skill called Stay Chill that reduces the cooldown time of the equipped active skill by 6%.
    • -
    -

    The tips and tricks to improve your gameplay and performance on Advance Server

    -

    Here are some tips and tricks to help you enjoy and excel on the Free Fire Advance Server:

    -
      -
    • Try out the new features and modes as much as possible and report any bugs or glitches that you encounter to earn free diamonds.
    • -
    • Experiment with different combinations of characters, weapons, pets, and items to find your optimal loadout and strategy.
    • -
    • Practice your aiming, movement, and positioning skills to gain an edge over your opponents.
    • -
    • Communicate and cooperate with your teammates to execute effective tactics and plans.
    • -
    • Have fun and don't take the game too seriously. Remember that the Advance Server is a testing server and not a competitive one.
    • -
    -

    Conclusion

    -

    In conclusion, Free Fire Advance Server is a great way to experience the upcoming updates and patches of the game before they are officially released. You can enjoy the new features, modes, characters, weapons, maps, and pets on the Advance Server and provide feedback and bug reports to the developers. You can also earn free diamonds by reporting bugs and glitches. However, you need to register on the official website and get an Activation Code to access the server. You also need to download and install a separate APK file for the Advance Server. You may encounter some bugs, glitches, or errors while playing on the Advance Server. Your progress and data on the Advance Server will not be transferred to your main account. You can only play on the Advance Server during a specific period of time, usually before a new update is released.

    -

    FAQs

    -

    Here are some frequently asked questions about Free Fire Advance Server:

    -
      -
    1. How can I get more Activation Codes for Free Fire Advance Server?
      You can't get more Activation Codes for Free Fire Advance Server. Each code is unique and can only be used by one player. If you want to invite your friends to play on the Advance Server, you have to wait for them to register and get their own codes.
    2. -
    3. Can I play on both regular server and Advance Server at the same time?
      No, you can't play on both regular server and Advance Server at the same time. You have to switch between them by opening different apps. However, you can use the same account for both servers.
    4. -
    5. Will I lose my progress and data on regular server if I play on Advance Server?
      No, you will not lose your progress and data on regular server if you play on Advance Server. Your progress and data on regular server will remain intact and unaffected by your actions on Advance Server.
    6. -
    7. How long can I play on Free Fire Advance Server?
      You can only play on Free Fire Advance Server during a specific period of time, usually before a new update is released. The duration of each testing phase may vary depending on the developers' schedule. You can check the official website for more information about the current testing phase.
    8. -
    9. How can I contact the developers or report bugs or glitches on Free Fire Advance Server?
      You can contact the developers or report bugs or glitches on Free Fire Advance Server by using the "Report" button on the app or by sending an email to ffadvance@garena.com. You can also join the official Facebook group of Free Fire Advance Server at [11](https://www.facebook.com/groups/FreeFireAdvanceServer) and interact with other players and moderators.
    10. -
    -

    I hope this article has helped you understand how to download and play Free Fire Advance Server. If you have any questions or comments, feel free to leave them below. Thank you for reading and happy gaming!

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download GTA 5 for PC Free Full Game with License Key Included.md b/spaces/fatiXbelha/sd/Download GTA 5 for PC Free Full Game with License Key Included.md deleted file mode 100644 index 9947f3254117b6a4d11971cb7a20486dbc28ecd2..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download GTA 5 for PC Free Full Game with License Key Included.md +++ /dev/null @@ -1,119 +0,0 @@ - -

    GTA 5 Download for PC Free Full Version with License Key

    -

    If you are a fan of action-adventure games, you have probably heard of GTA 5, one of the most popular and successful titles in the Grand Theft Auto series. But did you know that you can download GTA 5 for PC free full version with license key? In this article, we will show you how to do that, and also give you some tips and tricks for playing GTA 5 on PC.

    -

    gta 5 download for pc free full version with license key


    DOWNLOAD ❤❤❤ https://urllie.com/2uNzuO



    -

    Introduction

    -

    What is GTA 5?

    -

    GTA 5 is a video game developed by Rockstar North and published by Rockstar Games in 2013. It is the fifth main installment in the Grand Theft Auto series, which is known for its open-world gameplay, crime-themed stories, and satirical humor. GTA 5 follows the lives of three protagonists: Michael, a retired bank robber; Franklin, a street hustler; and Trevor, a psychopathic criminal. The game allows you to switch between them at any time, and also to play cooperatively with other players in online mode.

    -

    Why download GTA 5 for PC?

    -

    GTA 5 is available for various platforms, including PlayStation, Xbox, and PC. However, downloading GTA 5 for PC has some advantages over other versions. For example, you can enjoy better graphics, higher resolution, smoother framerate, and more customization options. You can also use mods to enhance your gameplay experience, such as adding new vehicles, weapons, characters, missions, and more. Moreover, downloading GTA 5 for PC is cheaper than buying it on consoles, especially if you get it for free.

    -

    How to download GTA 5 for PC free full version with license key

    -

    Step 1: Download the Epic Games Store launcher

    -

    The first step to download GTA 5 for PC free full version with license key is to download the Epic Games Store launcher. This is a digital distribution platform that offers various games and software for free or at discounted prices. You can download the Epic Games Store launcher from their official website. The launcher is compatible with Windows 7 or higher.

    -

    gta 5 pc free download full game with crack
    -gta 5 full version for pc with activation key
    -gta 5 free download for windows 10 with license
    -gta 5 pc game download full version highly compressed
    -gta 5 download for pc free full version no survey
    -gta 5 pc download with serial key
    -gta 5 free download for pc full version setup exe
    -gta 5 download for pc full version with torrent
    -gta 5 pc game free download with patch
    -gta 5 download for pc free full version rar
    -gta 5 pc download full version with crack kickass
    -gta 5 free download for pc with multiplayer
    -gta 5 pc game download full version iso
    -gta 5 download for pc free full version online
    -gta 5 pc download with product key
    -gta 5 free download for pc full version softonic
    -gta 5 download for pc full version with mods
    -gta 5 pc game free download with update
    -gta 5 download for pc free full version zip
    -gta 5 pc download full version with crack skidrow
    -gta 5 free download for pc with all dlc
    -gta 5 pc game download full version mega
    -gta 5 download for pc free full version offline
    -gta 5 pc download with license key generator
    -gta 5 free download for pc full version apunkagames
    -gta 5 download for pc full version with trainer
    -gta 5 pc game free download with cheats
    -gta 5 download for pc free full version compressed
    -gta 5 pc download full version with crack reloaded
    -gta 5 free download for pc with real life mod
    -gta 5 pc game download full version google drive
    -gta 5 download for pc free full version no password
    -gta 5 pc download with license key free
    -gta 5 free download for pc full version ocean of games
    -gta 5 download for pc full version with graphics mod
    -gta 5 pc game free download with direct link
    -gta 5 download for pc free full version windows 7
    -gta 5 pc download full version with crack nosteam
    -gta 5 free download for pc with redux mod
    -gta 5 pc game download full version fitgirl repack
    -gta 5 download for pc free full version no virus
    -gta 5 pc download with license key txt file
    -gta 5 free download for pc full version igg games
    -gta 5 download for pc full version with gameplay
    -gta 5 pc game free download with cd key
    -gta 5 download for pc free full version unblocked
    -gta 5 pc download full version with crack cpy

    -

    Step 2: Create an Epic Games account

    -

    The next step is to create an Epic Games account. This is required to access the Epic Games Store and claim your free games. You can create an Epic Games account by clicking on the "Sign In" button on the top right corner of the launcher. You can either use your email address or link your Facebook, Google, Xbox Live, PlayStation Network, or Nintendo account. After creating your account, you will need to verify your email address and agree to the terms of service.

    -

    Step 3: Claim GTA 5 for free on the Epic Games Store

    -

    The third step is to claim GTA 5 for free on the Epic Games Store. This is a limited-time offer that expires on June 30th, 2023. To claim GTA 5 for free, you need to go to the "Store" tab on the launcher and search for "Grand Theft Auto V". You will see a banner that says "Free Now". Click on it and then click on "Get". You will be asked to confirm your order and enter your payment method. Don't worry, you won't be charged anything. After completing the transaction, GTA 5 will be added to your library.

    -

    Step 4: Install GTA 5 on your PC

    -

    The fourth step is to install GTA 5 on your PC. To do that, you need to go to the "Library" tab on the launcher and find GTA 5. Click on it and then click on "Install". You will be asked to choose a destination folder and agree to the license agreement. The installation process may take some time, depending on your internet speed and disk space. GTA 5 requires about 94 GB of free space on your PC.

    -

    Step 5: Activate GTA 5 with your license key

    -

    The final step is to activate GTA 5 with your license key. This is a code that proves that you own the game legally. You can find your license key in your Epic Games account settings, under the "Transactions" tab. You will need to copy and paste the license key when you launch GTA 5 for the first time. After that, you can enjoy playing GTA 5 on your PC for free.

    -

    Tips and tricks for playing GTA 5 on PC

    -

    Adjust the graphics settings to optimize performance

    -

    One of the benefits of playing GTA 5 on PC is that you can customize the graphics settings to suit your preferences and hardware capabilities. You can access the graphics settings by pressing the Esc key and going to the "Settings" menu. There, you can adjust various options, such as resolution, texture quality, anti-aliasing, shadows, reflections, and more. You can also use the benchmark tool to test how well your PC can run the game. Ideally, you want to achieve a stable framerate of at least 30 frames per second (FPS) for a smooth gameplay experience.

    -

    Use the keyboard and mouse or a controller to control your character

    -

    Another benefit of playing GTA 5 on PC is that you can choose between using the keyboard and mouse or a controller to control your character. Both options have their pros and cons, depending on your personal preference and comfort level. The keyboard and mouse offer more precision and accuracy, especially for aiming and shooting. The controller offers more convenience and immersion, especially for driving and flying. You can switch between the two options at any time by plugging or unplugging your controller.

    -

    Explore the vast open world of Los Santos and Blaine County

    -

    One of the main attractions of GTA 5 is its vast open world, which is based on Southern California. You can explore the city of Los Santos and its surrounding areas, such as Blaine County, Sandy Shores, Paleto Bay, and more. You can also visit various landmarks, such as the Vinewood sign, the Del Perro Pier, the Maze Bank Tower, and more. You can interact with various characters, such as pedestrians, cops, gangsters, animals, and more. You can also engage in various activities, such as racing, golfing, tennis, yoga, hunting, parachuting, and more.

    -

    Enjoy the online multiplayer mode with other players

    -

    Another feature of GTA 5 is its online multiplayer mode, which is called GTA Online. This mode allows you to play with other players from around the world in various modes and missions. You can create your own character and customize their appearance, skills, vehicles, weapons, properties, and more. You can also join or create your own crew and cooperate or compete with other players. You can also participate in various events and updates that are regularly added by Rockstar Games.

    -

    Conclusion

    -

    Summary of the main points

    -

    In conclusion, GTA 5 is a great game that you can download for PC free full version with license key by following these steps:

    -
      -
    • Download the Epic Games Store launcher from their official website.
    • -
    • Create an Epic Games account using your email address or linking your social media account.
    • -
    • Claim GTA 5 for free on the Epic Games Store before June 30th, 2023.
    • -
    • Install GTA 5 on your PC by choosing a destination folder and agreeing to the license agreement.
    • -
    • Activate GTA 5 with your license key that you can find in your Epic Games account settings.
    • -
    -

    Call to action

    -

    Now that you know how to download GTA 5 for PC free full version with license key, what are you waiting for? Grab this amazing offer before it expires and enjoy playing one of the best games ever made. And don't forget to share this article with your friends who might be interested in getting GTA 5 for free too . You can also leave a comment below and let us know what you think of GTA 5 and how it runs on your PC.

    -

    FAQs

    -

    Here are some frequently asked questions about GTA 5 and how to download it for PC free full version with license key:

    -

    Q: Is GTA 5 free forever?

    -

    A: Yes, if you claim GTA 5 for free on the Epic Games Store before June 30th, 2023, you can keep it forever and play it whenever you want. However, you will need to have the Epic Games Store launcher installed on your PC and log in to your Epic Games account to access the game.

    -

    Q: Can I play GTA 5 offline?

    -

    A: Yes, you can play GTA 5 offline in single-player mode, which does not require an internet connection. However, you will need to connect to the internet at least once to activate the game with your license key. You will also need to connect to the internet if you want to play GTA Online, which is the online multiplayer mode of GTA 5.

    -

    Q: Can I transfer my GTA 5 progress from console to PC?

    -

    A: No, unfortunately, you cannot transfer your GTA 5 progress from console to PC. This feature was available until March 6th, 2017, but it has been discontinued by Rockstar Games. Therefore, if you download GTA 5 for PC, you will have to start from scratch and create a new character and profile.

    -

    Q: Can I use cheats in GTA 5?

    -

    A: Yes, you can use cheats in GTA 5 in single-player mode, which can make the game more fun and easier. You can find various cheat codes online that can give you different effects, such as invincibility, super speed, unlimited ammo, spawning vehicles, and more. However, you should not use cheats in GTA Online, as this can result in a ban or suspension from Rockstar Games.

    -

    Q: Can I run GTA 5 on my PC?

    -

    A: To run GTA 5 on your PC, you need to meet the minimum system requirements, which are as follows:

    -
      -
    • OS: Windows 7 or higher (64-bit)
    • -
    • CPU: Intel Core 2 Quad Q6600 @ 2.40 GHz or AMD Phenom 9850 @ 2.5 GHz
    • -
    • RAM: 4 GB
    • -
    • GPU: NVIDIA GeForce 9800 GT or AMD Radeon HD 4870 (1 GB VRAM)
    • -
    • HDD: 94 GB of free space
    • -
    • Sound: DirectX compatible
    • -
    -

    If you want to enjoy the best graphics and performance of GTA 5 on your PC, you need to meet the recommended system requirements, which are as follows:

    -
      -
    • OS: Windows 10 (64-bit)
    • -
    • CPU: Intel Core i5-3470 @ 3.2 GHz or AMD FX-8350 @ 4 GHz
    • -
    • RAM: 8 GB
    • -
    • GPU: NVIDIA GeForce GTX 660 or AMD Radeon HD 7870 (2 GB VRAM)
    • -
    • HDD: 94 GB of free space
    • -
    • Sound: DirectX compatible
    • -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Drive Your Dream Car with European Luxury Cars on PC - Free Download.md b/spaces/fatiXbelha/sd/Drive Your Dream Car with European Luxury Cars on PC - Free Download.md deleted file mode 100644 index 56d5826f8ae39cf1d61906e4158eca3608eb13a1..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Drive Your Dream Car with European Luxury Cars on PC - Free Download.md +++ /dev/null @@ -1,218 +0,0 @@ - -

    How to Download European Luxury Cars for PC

    -

    If you are a fan of European luxury cars, you might want to experience driving them in a virtual world. There are many video games that feature realistic models, sounds, and physics of these high-end vehicles. You can race them, customize them, or just cruise around in them.

    -

    But how can you download these games for your PC? And what are the advantages of playing them on your computer instead of on your mobile device or console? In this article, we will answer these questions and show you how to choose and download the best European luxury car games for your PC.

    -

    european luxury cars download for pc


    Download Ziphttps://urllie.com/2uNvVb



    -

    Introduction

    -

    European luxury cars are some of the most sought-after vehicles in the world. They combine elegance, performance, comfort, and technology in a way that few other cars can match. Brands like BMW, Audi, Mercedes-Benz, Porsche, Ferrari, Lamborghini, Bentley, Rolls-Royce, and more are synonymous with excellence and prestige.

    -

    Many gamers enjoy playing video games that feature these cars. They can experience driving them in different scenarios, such as racing tracks, city streets, off-road terrains, or even fantasy worlds. They can also customize their cars with various options, such as colors, wheels, spoilers, engines, etc.

    -

    Playing these games on a PC has several benefits over playing them on a mobile device or console. For one thing, you can enjoy better graphics, sound, and performance on a PC. You can also use a keyboard, mouse, or controller as input devices. You can also access a wider variety of games from different sources.

    -

    But how do you choose the best European luxury car game for your PC? There are many factors to consider, such as genre, gameplay, graphics, reviews, price, etc. You should also check if your PC meets the minimum or. recommended system requirements of the game. You can find this information on the game page or website, or by using a tool like Can You Run It.

    -

    To help you with your decision, we have compiled a list of some of the best European luxury car games for PC that you can download from different sources. You can find the table below.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    How to Download PC Games from Different Sources

    -

    Once you have chosen the game you want to play, you need to download it to your PC. There are different ways to do this depending on the source of the game. Here are some of the most common sources and how to download games from them.

    -

    european luxury cars pc game download
    -download european luxury cars android on pc
    -european luxury cars drive 3d for pc
    -european luxury cars simulator on pc
    -how to install european luxury cars on windows
    -european luxury cars racing game for pc
    -european luxury cars gameloop emulator download
    -best european luxury cars games for pc
    -european luxury cars apk download for pc
    -european luxury cars windows pc free download
    -play european luxury cars on pc with bluestacks
    -european luxury cars drive 3d ldplayer emulator
    -european luxury cars dominik kotlar pc version
    -download european luxury cars on windows 7/8/10/11
    -european luxury cars mod apk for pc
    -european luxury cars offline game for pc
    -european luxury cars photo mode and drone mode on pc
    -customize your european luxury car on pc
    -european luxury cars multiplayer mode on pc
    -download and install european luxury cars on noxplayer
    -european luxury cars latest version for pc
    -european luxury cars 2.4 download for pc
    -run european luxury cars on pc with android emulator
    -european luxury cars police lights upgrade on pc
    -play european luxury cars online on pc
    -download european luxury cars from google play store on pc
    -european luxury cars dynamic day-night cycle on pc
    -how to play european luxury cars with keyboard and mouse on pc
    -download and update european luxury cars on pc
    -best settings for european luxury cars on pc
    -how to fix european luxury cars not working on pc
    -how to uninstall european luxury cars from pc
    -how to transfer european luxury cars data from android to pc
    -how to get unlimited coins in european luxury cars on pc
    -how to unlock all european luxury cars on pc
    -how to change language in european luxury cars on pc
    -how to record and share your gameplay of european luxury cars on pc
    -how to stream european luxury cars on twitch from pc
    -how to join a clan in european luxury cars on pc
    -how to chat with other players in european luxury cars on pc
    -how to use cheat codes in european luxury cars on pc
    -how to speed up european luxury cars loading time on pc
    -how to reduce lag in european luxury cars on pc
    -how to connect a controller to play european luxury cars on pc
    -how to enable sound effects and music in european luxury cars on pc
    -how to change graphics quality in european luxury cars on pc
    -how to create your own custom map in european luxury cars on pc
    -how to earn rewards and achievements in european luxury cars on pc

    -

    Microsoft Store

    -

    The Microsoft Store is a digital distribution platform that is integrated with Windows 10. You can access it by clicking on the Start menu and then on the Microsoft Store icon. Alternatively, you can type "Microsoft Store" in the search box and press Enter.

    -

    To browse the gaming section of the store, you can click on the "Gaming" tab on the top menu. You can also use the search box to look for specific games or genres. You can filter the results by price, rating, category, etc.

    -

    To purchase or get free games from the store, you need to have a Microsoft account and a payment method linked to it. You can create an account or sign in by clicking on the profile icon on the top right corner of the store. You can also add or manage your payment methods by clicking on the same icon and then on "Payment options".

    -

    To install and play games from the store, you need to click on the "Get" or "Buy" button on the game page and follow the instructions. The game will be downloaded and installed automatically on your PC. You can launch it by clicking on the "Play" button on the game page or by finding it in your Start menu.

    -

    Direct Download

    -

    Another way to download games for your PC is to go directly to the official website of the game developer or publisher. For example, if you want to play Need for Speed Heat, you can go to https://www.ea.com/games/need-for-speed/need-for-speed-heat.

    -

    To buy or download games from these websites, you usually need to create an account and provide a payment method. You can also use third-party services like PayPal or credit cards to make purchases. Some websites may also offer free downloads or demos of their games.

    -

    To install and play games from these websites, you need to follow the instructions provided by the website. You may need to download a setup file or a launcher that will guide you through the installation process. You may also need to activate the game with a code or a key that you will receive after your purchase. You can launch the game by clicking on its icon on your desktop or in your Start menu.

    -

    Steam

    -

    Steam is one of the most popular and widely used platforms for downloading and playing PC games. It offers thousands of games from various genres, developers, and publishers. It also provides features like cloud saving, achievements, multiplayer, chat, reviews, etc.

    -

    To download and install Steam on your PC, you need to go to https://store.steampowered.com/about/ and click on the "Install Steam" button. You will then need to run the setup file and follow the instructions. You will also need to create an account or sign in with an existing one.

    -

    To browse, buy, or get free games from Steam, you need to launch the Steam application and log in to your account. You can then use the tabs on the top menu to access different sections of the store, such as featured, new releases, specials, genres, etc. You can also use the search box to look for specific games or keywords. You can filter the results by price, rating, tags, etc.

    -

    To install and play games from Steam, you need to click on the "Add to Cart" or "Play Game" button on the game page and follow the instructions. The game will be downloaded and installed automatically on your PC. You can launch it by clicking on the "Play" button on the game page or by finding it in your library.

    -

    Epic Games Store

    -

    Epic Games Store is another platform that offers PC games from various developers and publishers. It also gives away free games every week and provides features like cloud saving, achievements, multiplayer, chat, reviews, etc.

    -

    To download and install Epic Games Launcher on your PC, you need to go to https://www.epicgames.com/store/en-US/download and click on the "Get Epic Games" button. You will then need to run the setup file and follow the instructions. You will also need to create an account or sign in with an existing one.

    -

    To browse, buy, or get free games from Epic Games Store, you need to launch the Epic Games Launcher and log in to your account. You can then use the tabs on the left menu to access different sections of the store, such as browse, library, free games, etc. You can also use the search box to look for specific games or keywords.

    -

    To install and play games from Epic Games Store, you need to click on the "Get" or "Buy" button on the game page and follow the instructions. The game will be downloaded and installed automatically on your PC. You can launch it by clicking on the "Launch" button on the game page or by finding it in your library.

    -

    GOG

    -

    GOG is a platform that specializes in DRM-free games for PC. It offers games from various genres, developers, and publishers. It also provides features like cloud saving, achievements, multiplayer, chat, reviews, etc.

    -

    To download and install GOG Galaxy on your PC , you need to go to https://www.gog.com/galaxy and click on the "Download GOG GALAXY" button. You will then need to run the setup file and follow the instructions. You will also need to create an account or sign in with an existing one.

    -

    To browse, buy, or get free games from GOG, you need to launch the GOG Galaxy application and log in to your account. You can then use the tabs on the left menu to access different sections of the store, such as home, browse, library, etc. You can also use the search box to look for specific games or keywords.

    -

    To install and play games from GOG, you need to click on the "Get" or "Buy" button on the game page and follow the instructions. The game will be downloaded and installed automatically on your PC. You can launch it by clicking on the "Play" button on the game page or by finding it in your library.

    -

    itch.io

    -

    itch.io is a platform that hosts indie games for PC and other platforms. It offers games from various genres, developers, and publishers. It also allows users to pay what they want or support the developers with donations.

    -

    To access itch.io website and browse the gaming section, you can go to https://itch.io/games and use the tabs on the top menu to access different categories, such as featured, popular, new, etc. You can also use the search box to look for specific games or keywords.

    -

    To buy or download games from itch.io, you need to click on the game page and choose the option that suits you best. You can pay a fixed price, pay what you want, or download for free. You can also support the developer with a donation if you wish.

    -

    To install and play games from itch.io, you need to follow the instructions provided by the game page. You may need to download a zip file or an installer that will guide you through the installation process. You can launch the game by clicking on its icon on your desktop or in your Start menu.

    -

    How to Check Your PC Specs and Compare Them with the Game Requirements

    -

    Before you download any game for your PC, you should make sure that your PC can run it smoothly and without any issues. To do this, you need to check your PC specs and compare them with the game requirements.

    -

    How to find out your PC specs using Windows settings or system information tools

    -

    There are different ways to find out your PC specs using Windows settings or system information tools. Here are some of them:

    -
      -
    • To find out your processor, memory, and system type, you can go to Settings > System > About and look for the information under "Device specifications".
    • -
    • To find out your graphics card, you can go to Settings > System > Display and click on "Advanced display settings". Then, click on "Display adapter properties" and look for the information under "Adapter".
    • -
    • To find out your storage space, you can go to Settings > System > Storage and look for the information under "Local storage".
    • -
    • To find out more detailed information about your PC specs, you can use a system information tool like Speccy, CPU-Z, GPU-Z, etc. You can download these tools from their official websites and run them on your PC. They will show you various information about your hardware components, such as model, speed, temperature, etc.
    • -
    -

    How to read the game requirements from the game page or website

    -

    To read the game requirements from the game page or website, you need to look for a section that lists them. This section may be called "System Requirements", "Minimum Requirements", "Recommended Requirements", etc. It may also be located under a tab like "About", "Details", "Specifications", etc.

    -

    The game requirements usually include information about the following components:

    -
      -
    • Processor: The type and speed of the CPU that is needed to run the game.
    • -
    • Memory: The amount of RAM that is needed to run the game.
    • -
    • Graphics: The type and model of the GPU that is needed to run the game.
    • -
    • Storage: The amount of disk space that is needed to install and run the game.
    • -
    • OS: The operating system that is needed to run the game.
    • -
    -

    The game requirements may also include additional information about other components or features that are needed or recommended for the game, such as sound card, network connection, DirectX version, etc.

    -

    How to compare your PC specs with the game requirements and decide if your PC can run the game smoothly or not

    -

    To compare your PC specs with the game requirements and decide if your PC can run the game smoothly or not, you need to follow these steps:

    -
      -
    1. Find out your PC specs using Windows settings or system information tools, as explained above.
    2. -
    3. Find out the game requirements from the game page or website, as explained above.
    4. -
    5. Compare each component of your PC specs with the corresponding component of the game requirements. For example, compare your processor type and speed with the processor type and speed required by the game.
    6. -
    7. If your PC specs are equal to or higher than the game requirements, then your PC can run the game smoothly. If your PC specs are lower than the game requirements, then your PC may not be able to run the game smoothly or at all.
    8. -
    9. If you are not sure about your PC specs or the game requirements, you can use a tool like Can You Run It to automatically compare them and give you a result. You can access this tool at https://www.systemrequirementslab.com/cyri.
    10. -
    -

    Conclusion

    -

    In this article, we have shown you how to download European luxury cars for PC. We have explained what are European luxury cars and why are they popular among gamers. We have also discussed what are the benefits of playing them on PC instead of on mobile devices or consoles. We have also shown you how to choose the best European luxury car game for your PC based on various factors.

    -

    We have also shown you how to download PC games from different sources, such as Microsoft Store, direct download, Steam, Epic Games Store, GOG, and itch.io. We have also shown you how to check your PC specs and compare them with the game requirements to make sure that your PC can run the game smoothly.

    -

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

    -

    FAQs

    -

    Here are some of the frequently asked questions and answers related to the topic of this article:

    -

    What are some of the best European luxury car games for PC?

    -

    Some of the best European luxury car games for PC are Forza Horizon 4, Project CARS 3, Need for Speed Heat, The Crew 2, Assetto Corsa Competizione, Grand Theft Auto V, Cyberpunk 2077, and Euro Truck Simulator 2. You can find more details about these games in the table above.

    -

    How can I improve the performance of my PC games?

    -

    You can improve the performance of your PC games by doing some of the following things:

    -
      -
    • Update your drivers, especially your graphics card driver.
    • -
    • Close any unnecessary programs or background processes that may be using up your CPU, memory, or disk space.
    • -
    • Adjust the graphics settings of your games to match your PC specs and preferences. You can lower the resolution, texture quality, anti-aliasing, etc. to increase the frame rate and reduce lag.
    • -
    • Clean up your PC by deleting any unwanted files or programs, defragmenting your disk, scanning for viruses or malware, etc.
    • -
    • Upgrade your hardware components if possible and affordable. You can add more RAM, get a faster processor, buy a better graphics card, etc.
    • -
    -

    How can I play European luxury car games online with other players?

    -

    You can play European luxury car games online with other players by doing some of the following things:

    -
      -
    • Make sure that you have a stable and fast internet connection.
    • -
    • Make sure that you have an account and a subscription for the platform or service that hosts the online multiplayer mode of the game. For example, if you want to play Forza Horizon 4 online on Xbox Live, you need to have an Xbox Live account and a subscription.
    • -
    • Make sure that you have installed any updates or patches for the game that may be required for online multiplayer mode.
    • -
    • Launch the game and select the online multiplayer mode from the main menu or options. You may need to choose a server, a lobby, a room, etc. depending on the game.
    • -
    • Invite or join other players who are playing online. You may need to use a chat or voice communication tool to communicate with them.
    • -
    -

    How can I backup or restore my PC games?

    -

    You can backup or restore your PC games by doing some of the following things:

    -
      -
    • Use the backup or restore feature of the platform or service that you downloaded the game from. For example, if you downloaded the game from Steam, you can use the Steam backup and restore feature to save or load your game files and settings.
    • -
    • Use a third-party backup or restore tool that can copy or restore your game files and settings. For example, you can use GameSave Manager, EaseUS Todo Backup, etc. to backup or restore your PC games.
    • -
    • Manually copy or paste your game files and settings from or to the location where they are stored on your PC. For example, you can find your game files and settings in the Program Files, Documents, AppData, etc. folders on your PC.
    • -
    -

    How can I mod or customize my PC games?

    -

    You can mod or customize your PC games by doing some of the following things:

    -
      -
    • Use the mod or customization feature of the game itself if it has one. For example, some games have built-in editors, tools, or options that allow you to create or modify various aspects of the game, such as maps, characters, vehicles, etc.
    • -
    • Use the mod or customization feature of the platform or service that you downloaded the game from if it has one. For example, some platforms or services have modding communities, workshops, or libraries that allow you to download or upload mods or customizations for various games.
    • -
    • Use a third-party mod or customization tool that can create or modify various aspects of the game. For example, you can use Nexus Mods, Mod DB, etc. to find and install mods or customizations for various games.
    • -
    • Manually download or create mods or customizations for the game and install them on your PC. For example, you can find mods or customizations for various games on websites, forums, blogs, etc. and follow the instructions to install them on your PC.
    • -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fb700/chatglm-fitness-RLHF/src/audio2pose_models/cvae.py b/spaces/fb700/chatglm-fitness-RLHF/src/audio2pose_models/cvae.py deleted file mode 100644 index d017ce865a03bae40dfe066dbcd82e29839d89dc..0000000000000000000000000000000000000000 --- a/spaces/fb700/chatglm-fitness-RLHF/src/audio2pose_models/cvae.py +++ /dev/null @@ -1,149 +0,0 @@ -import torch -import torch.nn.functional as F -from torch import nn -from src.audio2pose_models.res_unet import ResUnet - -def class2onehot(idx, class_num): - - assert torch.max(idx).item() < class_num - onehot = torch.zeros(idx.size(0), class_num).to(idx.device) - onehot.scatter_(1, idx, 1) - return onehot - -class CVAE(nn.Module): - def __init__(self, cfg): - super().__init__() - encoder_layer_sizes = cfg.MODEL.CVAE.ENCODER_LAYER_SIZES - decoder_layer_sizes = cfg.MODEL.CVAE.DECODER_LAYER_SIZES - latent_size = cfg.MODEL.CVAE.LATENT_SIZE - num_classes = cfg.DATASET.NUM_CLASSES - audio_emb_in_size = cfg.MODEL.CVAE.AUDIO_EMB_IN_SIZE - audio_emb_out_size = cfg.MODEL.CVAE.AUDIO_EMB_OUT_SIZE - seq_len = cfg.MODEL.CVAE.SEQ_LEN - - self.latent_size = latent_size - - self.encoder = ENCODER(encoder_layer_sizes, latent_size, num_classes, - audio_emb_in_size, audio_emb_out_size, seq_len) - self.decoder = DECODER(decoder_layer_sizes, latent_size, num_classes, - audio_emb_in_size, audio_emb_out_size, seq_len) - def reparameterize(self, mu, logvar): - std = torch.exp(0.5 * logvar) - eps = torch.randn_like(std) - return mu + eps * std - - def forward(self, batch): - batch = self.encoder(batch) - mu = batch['mu'] - logvar = batch['logvar'] - z = self.reparameterize(mu, logvar) - batch['z'] = z - return self.decoder(batch) - - def test(self, batch): - ''' - class_id = batch['class'] - z = torch.randn([class_id.size(0), self.latent_size]).to(class_id.device) - batch['z'] = z - ''' - return self.decoder(batch) - -class ENCODER(nn.Module): - def __init__(self, layer_sizes, latent_size, num_classes, - audio_emb_in_size, audio_emb_out_size, seq_len): - super().__init__() - - self.resunet = ResUnet() - self.num_classes = num_classes - self.seq_len = seq_len - - self.MLP = nn.Sequential() - layer_sizes[0] += latent_size + seq_len*audio_emb_out_size + 6 - for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])): - self.MLP.add_module( - name="L{:d}".format(i), module=nn.Linear(in_size, out_size)) - self.MLP.add_module(name="A{:d}".format(i), module=nn.ReLU()) - - self.linear_means = nn.Linear(layer_sizes[-1], latent_size) - self.linear_logvar = nn.Linear(layer_sizes[-1], latent_size) - self.linear_audio = nn.Linear(audio_emb_in_size, audio_emb_out_size) - - self.classbias = nn.Parameter(torch.randn(self.num_classes, latent_size)) - - def forward(self, batch): - class_id = batch['class'] - pose_motion_gt = batch['pose_motion_gt'] #bs seq_len 6 - ref = batch['ref'] #bs 6 - bs = pose_motion_gt.shape[0] - audio_in = batch['audio_emb'] # bs seq_len audio_emb_in_size - - #pose encode - pose_emb = self.resunet(pose_motion_gt.unsqueeze(1)) #bs 1 seq_len 6 - pose_emb = pose_emb.reshape(bs, -1) #bs seq_len*6 - - #audio mapping - print(audio_in.shape) - audio_out = self.linear_audio(audio_in) # bs seq_len audio_emb_out_size - audio_out = audio_out.reshape(bs, -1) - - class_bias = self.classbias[class_id] #bs latent_size - x_in = torch.cat([ref, pose_emb, audio_out, class_bias], dim=-1) #bs seq_len*(audio_emb_out_size+6)+latent_size - x_out = self.MLP(x_in) - - mu = self.linear_means(x_out) - logvar = self.linear_means(x_out) #bs latent_size - - batch.update({'mu':mu, 'logvar':logvar}) - return batch - -class DECODER(nn.Module): - def __init__(self, layer_sizes, latent_size, num_classes, - audio_emb_in_size, audio_emb_out_size, seq_len): - super().__init__() - - self.resunet = ResUnet() - self.num_classes = num_classes - self.seq_len = seq_len - - self.MLP = nn.Sequential() - input_size = latent_size + seq_len*audio_emb_out_size + 6 - for i, (in_size, out_size) in enumerate(zip([input_size]+layer_sizes[:-1], layer_sizes)): - self.MLP.add_module( - name="L{:d}".format(i), module=nn.Linear(in_size, out_size)) - if i+1 < len(layer_sizes): - self.MLP.add_module(name="A{:d}".format(i), module=nn.ReLU()) - else: - self.MLP.add_module(name="sigmoid", module=nn.Sigmoid()) - - self.pose_linear = nn.Linear(6, 6) - self.linear_audio = nn.Linear(audio_emb_in_size, audio_emb_out_size) - - self.classbias = nn.Parameter(torch.randn(self.num_classes, latent_size)) - - def forward(self, batch): - - z = batch['z'] #bs latent_size - bs = z.shape[0] - class_id = batch['class'] - ref = batch['ref'] #bs 6 - audio_in = batch['audio_emb'] # bs seq_len audio_emb_in_size - #print('audio_in: ', audio_in[:, :, :10]) - - audio_out = self.linear_audio(audio_in) # bs seq_len audio_emb_out_size - #print('audio_out: ', audio_out[:, :, :10]) - audio_out = audio_out.reshape([bs, -1]) # bs seq_len*audio_emb_out_size - class_bias = self.classbias[class_id] #bs latent_size - - z = z + class_bias - x_in = torch.cat([ref, z, audio_out], dim=-1) - x_out = self.MLP(x_in) # bs layer_sizes[-1] - x_out = x_out.reshape((bs, self.seq_len, -1)) - - #print('x_out: ', x_out) - - pose_emb = self.resunet(x_out.unsqueeze(1)) #bs 1 seq_len 6 - - pose_motion_pred = self.pose_linear(pose_emb.squeeze(1)) #bs seq_len 6 - - batch.update({'pose_motion_pred':pose_motion_pred}) - return batch diff --git a/spaces/fengmuxi/ChatGpt-Web/app/api/openai-image/typing.ts b/spaces/fengmuxi/ChatGpt-Web/app/api/openai-image/typing.ts deleted file mode 100644 index 4e5e112825c73445e8c6fe81a44431503276f6d1..0000000000000000000000000000000000000000 --- a/spaces/fengmuxi/ChatGpt-Web/app/api/openai-image/typing.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { CreateImageRequest, ImagesResponse } from "openai"; - -export type ChatImageRequest = CreateImageRequest; -export type ChatImagesResponse = ImagesResponse; - -export type Updater = (updater: (value: T) => void) => void; diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/AI Type OS 12 Keyboard Theme APK How to Get the Phone X Style on Your Device.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/AI Type OS 12 Keyboard Theme APK How to Get the Phone X Style on Your Device.md deleted file mode 100644 index b4d6fca5d7cc4830b7cdd31311c5bc723866e1fb..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/AI Type OS 12 Keyboard Theme APK How to Get the Phone X Style on Your Device.md +++ /dev/null @@ -1,84 +0,0 @@ - -

    ai type OS 12 Keyboard Theme APK: A Review

    -

    If you are looking for a keyboard app that can give your Android device a sleek and modern look, you might want to check out ai type OS 12 Keyboard Theme APK. This app is a full version app for Android, developed by ai.type, that lets you customize your keyboard with the OS 12 theme. In this article, we will review the features, installation process, pros and cons of this app.

    -

    ai type os 12 keyboard theme apk


    Download Filehttps://gohhs.com/2uPtnd



    -

    What is ai type OS 12 Keyboard Theme APK?

    -

    ai type OS 12 Keyboard Theme APK is an app that allows you to change the appearance and functionality of your keyboard on your Android device. It is based on the OS 12 theme, which is inspired by the iOS operating system. The app gives your keyboard a clean and elegant design, with rounded keys, subtle shadows, and smooth animations. You can also choose between dark mode and light mode, depending on your preference.

    -

    Features of ai type OS 12 Keyboard Theme APK

    -

    Customizable keyboard layout and design

    -

    One of the best features of this app is that it lets you customize your keyboard layout and design according to your needs. You can change the size, shape, color, font, and sound of your keys. You can also add or remove keys, such as numbers, symbols, or emojis. You can even create your own shortcuts and gestures for faster typing.

    -

    Dark mode and light mode options

    -

    Another feature of this app is that it offers you two different modes for your keyboard: dark mode and light mode. Dark mode is ideal for low-light environments, as it reduces eye strain and saves battery life. Light mode is suitable for bright environments, as it enhances visibility and contrast. You can switch between the two modes easily by tapping on the moon icon on the top left corner of your keyboard.

    -

    Emoji and GIF support

    -

    If you love expressing yourself with emojis and GIFs, you will be happy to know that this app supports both. You can access a wide range of emojis and GIFs from various categories, such as animals, food, emotions, or reactions. You can also search for specific emojis or GIFs by typing keywords or phrases. To insert an emoji or a GIF, simply tap on it and it will appear on your text field.

    -

    Auto-correction and word prediction

    -

    This app also helps you type faster and more accurately with its auto-correction and word prediction features. The app automatically corrects your spelling and grammar mistakes as you type. It also suggests words or phrases that you might want to use next, based on your typing history and context. You can accept or reject the suggestions by tapping on them or swiping left or right.

    -

    ai type os 12 keyboard theme apk download
    -ai type os 12 keyboard theme apk free
    -ai type os 12 keyboard theme apk mod
    -ai type os 12 keyboard theme apk latest version
    -ai type os 12 keyboard theme apk for android
    -ai type os 12 keyboard theme apk pro
    -ai type os 12 keyboard theme apk cracked
    -ai type os 12 keyboard theme apk premium
    -ai type os 12 keyboard theme apk full
    -ai type os 12 keyboard theme apk unlocked
    -ai type os 12 keyboard theme apk paid
    -ai type os 12 keyboard theme apk no ads
    -ai type os 12 keyboard theme apk offline
    -ai type os 12 keyboard theme apk update
    -ai type os 12 keyboard theme apk review
    -ai type os 12 keyboard theme apk features
    -ai type os 12 keyboard theme apk install
    -ai type os 12 keyboard theme apk how to use
    -ai type os 12 keyboard theme apk best settings
    -ai type os 12 keyboard theme apk customization
    -ai type os 12 keyboard theme apk tips and tricks
    -ai type os 12 keyboard theme apk comparison
    -ai type os 12 keyboard theme apk alternatives
    -ai type os 12 keyboard theme apk similar apps
    -ai type os 12 keyboard theme apk compatible devices
    -ai type os 12 keyboard theme apk requirements
    -ai type os 12 keyboard theme apk size
    -ai type os 12 keyboard theme apk rating
    -ai type os 12 keyboard theme apk feedback
    -ai type os 12 keyboard theme apk support
    -ai type os 12 keyboard theme apk developer
    -ai type os 12 keyboard theme apk website
    -ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to get ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -where to download ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -why choose ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -what is new in ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -is ai.type OS 12 Keyboard Theme v5.0.9 [Paid] safe
    -is ai.type OS 12 Keyboard Theme v5.0.9 [Paid] worth it
    -is ai.type OS 12 Keyboard Theme v5.0.9 [Paid] better than other themes
    -how to uninstall ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to upgrade to ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to backup and restore ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to customize your keyboard with ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to change the language of your keyboard with ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to enable or disable autocorrect with ai.type OS 12 Keyboard Theme v5.0.9 [Paid]
    -how to use emojis and stickers with ai.type OS 12 Keyboard Theme v5.0.9 [Paid]

    -

    Voice typing and swipe typing

    -

    How to download and install ai type OS 12 Keyboard Theme APK?

    -

    If you are interested in trying out this app, you will need to download and install the APK file on your Android device. APK stands for Android Package Kit, which is a file format that contains all the components of an app. To download and install the APK file, follow these steps:

    -

    Step 1: Enable unknown sources on your device

    -

    Before you can install an APK file, you need to enable unknown sources on your device. This means that you allow your device to install apps from sources other than the Google Play Store. To enable unknown sources, go to your device settings, tap on security, and toggle on the option that says "allow installation of apps from unknown sources".

    -

    Step 2: Download the APK file from a trusted source

    -

    Next, you need to download the APK file from a trusted source. You can find many websites that offer APK files for various apps, but be careful not to download from malicious or fake sites. One of the trusted sources that we recommend is [APKPure], which is a popular and reliable platform for downloading APK files. To download the APK file from APKPure, visit their website, search for ai type OS 12 Keyboard Theme APK, and tap on the download button.

    -

    Step 3: Locate the file and tap on it to install

    -

    Once you have downloaded the APK file, you need to locate it on your device and tap on it to install it. You can use a file manager app to find the file, or you can check your notification bar or download folder. When you tap on the file, you will see a pop-up window that asks you to confirm the installation. Tap on install and wait for the process to finish.

    -

    Step 4: Open the app and select the OS 12 theme

    -

    After the installation is complete, you can open the app and start using it. To select the OS 12 theme, tap on the menu icon on the top left corner of your keyboard, tap on themes, and choose OS 12 from the list. You can also customize other settings, such as language, layout, sound, and more.

    -

    Pros and cons of ai type OS 12 Keyboard Theme APK

    -

    Like any other app, ai type OS 12 Keyboard Theme APK has its pros and cons. Here are some of them:

    -

    Pros: Stylish, functional, and easy to use

    -

    The main advantage of this app is that it gives your keyboard a stylish, functional, and easy-to-use makeover. The app mimics the look and feel of the iOS keyboard, which many users find appealing and comfortable. The app also offers many features that enhance your typing experience, such as customization, emoji and GIF support, auto-correction and word prediction, voice typing and swipe typing, and more.

    -

    Cons: Requires internet connection, may not be compatible with some devices

    -

    The main drawback of this app is that it requires an internet connection to work properly. This means that you may not be able to use some features or access some content when you are offline or have a poor connection. The app also may not be compatible with some devices or operating systems, especially older or low-end ones. You may experience some bugs or glitches when using this app on some devices.

    -

    Conclusion

    -

    In conclusion, ai type OS 12 Keyboard Theme APK is a keyboard app that lets you customize your keyboard with the OS 12 theme. It is a full version app for Android that offers many features that make your typing faster and more enjoyable. However, it also has some drawbacks that you should be aware of before downloading it. If you are looking for a keyboard app that can give your Android device a sleek and modern look, you might want to give this app a try.

    - FAQs Q: Is ai type OS 12 Keyboard Theme APK free? A: Yes, this app is free to download and use. Q: Is ai type OS 12 Keyboard Theme APK safe? A: Yes, this app is safe as long as you download it from a trusted source like [APKPure]. However, you should always be careful when installing apps from unknown sources and scan them for viruses or malware. Q: How do I uninstall ai type OS 12 Keyboard Theme APK? A: To uninstall this app, go to your device settings, tap on apps or applications, find ai type OS 12 Keyboard Theme APK in the list, and tap on uninstall. Q: Can I use ai type OS 12 Keyboard Theme APK with other apps? A: Yes, you can use this app with any app that requires typing, such as messaging, social media, email, browser, and more. Q: Can I change the language of ai type OS 12 Keyboard Theme APK? A: Yes, you can change the language of this app by going to the settings menu and tapping on language. You can choose from over 100 languages and dialects that are supported by this app. Q: How do I contact the developer of ai type OS 12 Keyboard Theme APK? A: If you have any questions, feedback, or suggestions for this app, you can contact the developer by visiting their website [ai.type], sending them an email at support@aitype.com, or following them on Facebook or Twitter.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Kiwi X and Hack Roblox with the Best Level 7 ExploitExecutorCheat.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Kiwi X and Hack Roblox with the Best Level 7 ExploitExecutorCheat.md deleted file mode 100644 index cfbef7df123841ca0f1c38e01848fee09c633d66..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Kiwi X and Hack Roblox with the Best Level 7 ExploitExecutorCheat.md +++ /dev/null @@ -1,87 +0,0 @@ -
    -

    Kiwi X Roblox APK: What Is It and How to Use It

    -

    Do you love playing games on Roblox, but wish you could have more control and customization over your gaming experience? If so, you might be interested in Kiwi X Roblox APK, a powerful and popular executor that lets you run custom scripts and modify games on Roblox. In this article, we will explain what Kiwi X Roblox APK is, how to download and install it, and how to use it to enhance your Roblox gameplay. Let's get started!

    -

    Introduction

    -

    What is Roblox?

    -

    Roblox is an online platform that allows users to create and play millions of games across various genres and themes. You can explore immersive worlds, socialize with other players, and unleash your creativity with Roblox Studio, a tool that lets you design your own games and share them with the community. Roblox is available on multiple devices, including Windows, Mac, iOS, Android, Xbox One, and more.

    -

    kiwi x roblox apk


    Download 🆓 https://gohhs.com/2uPsGg



    -

    What is Kiwi X?

    -

    Kiwi X is one of the most well-known Roblox executors that allows users to change their games and run custom scripts with it. Additionally, Kiwi X contains a mod menu where players may alter game options, add new objects, and more. Kiwi X is compatible with most Roblox games and supports various types of scripts, such as Lua, Lua C, JavaScript, and more. Kiwi X also has a user-friendly interface and regular updates to ensure its functionality and security.

    -

    Why use Kiwi X Roblox APK?

    -

    Kiwi X Roblox APK is an Android application that lets you use Kiwi X on your mobile device. This means you can enjoy the benefits of Kiwi X without having to use a PC or a console. Some of the reasons why you might want to use Kiwi X Roblox APK are:

    -
      -
    • You can access unlimited resources, such as coins, gems, items, etc.
    • -
    • You can unlock premium features, such as skins, outfits, weapons, etc.
    • -
    • You can bypass game restrictions, such as level caps, timers, ads, etc.
    • -
    • You can enhance your gameplay, such as speed hacks, aimbots, wallhacks, etc.
    • -
    • You can have more fun and challenge yourself with new modes and scenarios.
    • -
    -

    How to Download and Install Kiwi X Roblox APK

    -

    Step 1: Download the APK file from the official website

    -

    The first step is to download the APK file from the official website of Kiwi X. You can also scan the QR code on the website with your device's camera to get the download link. Make sure you have enough storage space on your device before downloading the file.

    -

    kiwi x roblox hack download
    -kiwi x roblox exploit free
    -kiwi x roblox cheat engine
    -kiwi x roblox script executor
    -kiwi x roblox level 7
    -kiwi x roblox owl hub
    -kiwi x roblox mod menu
    -kiwi x roblox jailbreak
    -kiwi x roblox phantom forces
    -kiwi x roblox arsenal
    -kiwi x roblox bloxburg
    -kiwi x roblox admin commands
    -kiwi x roblox aimbot
    -kiwi x roblox fly hack
    -kiwi x roblox speed hack
    -kiwi x roblox infinite money
    -kiwi x roblox god mode
    -kiwi x roblox noclip
    -kiwi x roblox teleport hack
    -kiwi x roblox esp hack
    -kiwi x roblox wallhack
    -kiwi x roblox auto clicker
    -kiwi x roblox btools hack
    -kiwi x roblox gui hack
    -kiwi x roblox game guardian
    -kiwi x roblox android apk
    -kiwi x roblox ios apk
    -kiwi x roblox pc download
    -kiwi x roblox mac download
    -kiwi x roblox linux download
    -kiwi x roblox safe download
    -kiwi x roblox virus free download
    -kiwi x roblox no survey download
    -kiwi x roblox no password download
    -kiwi x roblox latest version download
    -kiwi x roblox update download
    -kiwi x roblox tutorial download
    -how to use kiwi x roblox hack
    -how to install kiwi x roblox apk
    -how to uninstall kiwi x roblox apk
    -how to fix kiwi x roblox error
    -how to bypass kiwi x roblox ban
    -how to get free robux with kiwi x apk
    -how to get free items with kiwi x apk
    -how to get free vip with kiwi x apk
    -how to get free gamepasses with kiwi x apk

    -

    Step 2: Enable unknown sources on your device

    -

    The next step is to enable unknown sources on your device. This will allow you to install apps that are not from the Google Play Store. To do this, go to Settings > Security > Unknown Sources and toggle it on. You might also need to confirm this action by tapping OK or Allow.

    -

    Step 3: Install the APK file and launch Kiwi X

    -

    The final step is to install the APK file and launch Ki

    wi X. To do this, locate the APK file in your device's file manager and tap on it. Follow the instructions on the screen to complete the installation process. Once the app is installed, you can launch it by tapping on its icon on your home screen or app drawer.

    -

    How to Use Kiwi X Roblox APK

    -

    Step 1: Select a game to play on Roblox

    -

    The first step is to select a game to play on Roblox. You can do this by opening the Roblox app on your device and browsing through the featured games, categories, or genres. You can also search for a specific game by using the search bar. Once you find a game that you like, tap on it to enter its page and then tap on Play.

    -

    Step 2: Open the mod menu and choose a script to execute

    -

    The next step is to open the mod menu and choose a script to execute. You can do this by opening the Kiwi X app on your device and tapping on the Menu button at the top left corner. You will see a list of scripts that are available for different games. You can also add your own scripts by tapping on the Add button at the bottom right corner. To execute a script, simply tap on it and wait for it to load.

    -

    Step 3: Enjoy the game with enhanced features and options

    -

    The final step is to enjoy the game with enhanced features and options. You can do this by playing the game normally, but with the added benefits of Kiwi X. You will see a floating icon on your screen that lets you access the mod menu at any time. You can also adjust the settings, such as transparency, size, position, etc., by tapping on the Settings button at the top right corner. You can also close the mod menu by tapping on the Exit button at the bottom left corner.

    -

    Conclusion

    -

    Summary of the main points

    -

    Kiwi X Roblox APK is an amazing application that lets you run custom scripts and modify games on Roblox using your Android device. It is easy to download, install, and use, and it offers a wide range of features and options to enhance your gameplay. Whether you want to get more resources, unlock premium features, bypass game restrictions, or have more fun and challenge yourself, Kiwi X Roblox APK can help you achieve your goals.

    -

    Call to action and final thoughts

    -

    If you are interested in trying out Kiwi X Roblox APK, you can download it from the official website or scan the QR code below. Make sure you follow the instructions carefully and use it responsibly. Remember that using Kiwi X Roblox APK might violate the terms of service of Roblox and result in bans or other consequences. Therefore, use it at your own risk and discretion.

    -

    We hope you enjoyed this article and learned something new about Kiwi X Roblox APK. If you have any questions, comments, or feedback, feel free to leave them below. Thank you for reading and happy gaming!

    - FAQs Q: Is Kiwi X Roblox APK safe to use? A: Kiwi X Roblox APK is safe to use as long as you download it from the official website and scan it with an antivirus before installing it. However, using Kiwi X Roblox APK might be detected by Roblox's anti-cheat system and result in bans or other consequences. Therefore, use it at your own risk and discretion. Q: Is Kiwi X Roblox APK free to use? A: Yes, Kiwi X Roblox APK is free to use and does not require any subscription or payment. However, some scripts might require a donation or a premium account to access them. Q: How do I update Kiwi X Roblox APK? A: To update Kiwi X Roblox APK, you need to download the latest version from the official website or scan the QR code below. Then, you need to uninstall the old version and install the new one following the same steps as before. Q: How do I uninstall Kiwi X Roblox APK? A: To uninstall Kiwi X Roblox APK, you need to go to Settings > Apps > Kiwi X > Uninstall and confirm your action. You might also need to delete any leftover files or folders related to Kiwi X from your device's file manager. Q: How do I contact Kiwi X support team? A: To contact Kiwi X support team, you need to visit their Discord server or their Twitter account. You can also send them an email at kiwixrobloxsupport@gmail.com.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/finlaymacklon/boxy_violet/README.md b/spaces/finlaymacklon/boxy_violet/README.md deleted file mode 100644 index 1a54c5c35ed6bd1d670ec0fbdace22dc1306d329..0000000000000000000000000000000000000000 --- a/spaces/finlaymacklon/boxy_violet/README.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -tags: -- gradio-theme -- track-4 -title: boxy_violet -colorFrom: purple -colorTo: purple -sdk: gradio -sdk_version: 3.42.0 -app_file: app.py -pinned: false -license: apache-2.0 -emoji: 👁 ---- -# boxy_violet -## Description -Add a description of this theme here! -## Contributions -Thanks to [@finlaymacklon](https://huggingface.co/finlaymacklon) for adding this gradio theme! \ No newline at end of file diff --git a/spaces/flowers-team/SocialAISchool/gym-minigrid/gym_minigrid/envs/multiroom.py b/spaces/flowers-team/SocialAISchool/gym-minigrid/gym_minigrid/envs/multiroom.py deleted file mode 100644 index 31f1d92801a3da89fbd971a870dd0bfb98068c6a..0000000000000000000000000000000000000000 --- a/spaces/flowers-team/SocialAISchool/gym-minigrid/gym_minigrid/envs/multiroom.py +++ /dev/null @@ -1,340 +0,0 @@ -from gym_minigrid.minigrid import * -from gym_minigrid.register import register - -class Room: - def __init__(self, - top, - size, - entryDoorPos, - exitDoorPos - ): - self.top = top - self.size = size - self.entryDoorPos = entryDoorPos - self.exitDoorPos = exitDoorPos - -class MultiRoomEnv(MiniGridEnv): - """ - Environment with multiple rooms (subgoals) - """ - - def __init__(self, - minNumRooms, - maxNumRooms, - maxRoomSize=10 - ): - assert minNumRooms > 0 - assert maxNumRooms >= minNumRooms - assert maxRoomSize >= 4 - - self.minNumRooms = minNumRooms - self.maxNumRooms = maxNumRooms - self.maxRoomSize = maxRoomSize - - self.rooms = [] - - super(MultiRoomEnv, self).__init__( - grid_size=25, - max_steps=self.maxNumRooms * 20 - ) - - def _gen_grid(self, width, height): - roomList = [] - - # Choose a random number of rooms to generate - numRooms = self._rand_int(self.minNumRooms, self.maxNumRooms+1) - - while len(roomList) < numRooms: - curRoomList = [] - - entryDoorPos = ( - self._rand_int(0, width - 2), - self._rand_int(0, width - 2) - ) - - # Recursively place the rooms - self._placeRoom( - numRooms, - roomList=curRoomList, - minSz=4, - maxSz=self.maxRoomSize, - entryDoorWall=2, - entryDoorPos=entryDoorPos - ) - - if len(curRoomList) > len(roomList): - roomList = curRoomList - - # Store the list of rooms in this environment - assert len(roomList) > 0 - self.rooms = roomList - - # Create the grid - self.grid = Grid(width, height, nb_obj_dims=self.nb_obj_dims) - wall = Wall() - - prevDoorColor = None - - # For each room - for idx, room in enumerate(roomList): - - topX, topY = room.top - sizeX, sizeY = room.size - - # Draw the top and bottom walls - for i in range(0, sizeX): - self.grid.set(topX + i, topY, wall) - self.grid.set(topX + i, topY + sizeY - 1, wall) - - # Draw the left and right walls - for j in range(0, sizeY): - self.grid.set(topX, topY + j, wall) - self.grid.set(topX + sizeX - 1, topY + j, wall) - - # If this isn't the first room, place the entry door - if idx > 0: - # Pick a door color different from the previous one - doorColors = set(COLOR_NAMES) - if prevDoorColor: - doorColors.remove(prevDoorColor) - # Note: the use of sorting here guarantees determinism, - # This is needed because Python's set is not deterministic - doorColor = self._rand_elem(sorted(doorColors)) - - entryDoor = Door(doorColor) - self.grid.set(*room.entryDoorPos, entryDoor) - prevDoorColor = doorColor - - prevRoom = roomList[idx-1] - prevRoom.exitDoorPos = room.entryDoorPos - - # Randomize the starting agent position and direction - self.place_agent(roomList[0].top, roomList[0].size) - - # Place the final goal in the last room - self.goal_pos = self.place_obj(Goal(), roomList[-1].top, roomList[-1].size) - - self.mission = 'traverse the rooms to get to the goal' - - def _placeRoom( - self, - numLeft, - roomList, - minSz, - maxSz, - entryDoorWall, - entryDoorPos - ): - # Choose the room size randomly - sizeX = self._rand_int(minSz, maxSz+1) - sizeY = self._rand_int(minSz, maxSz+1) - - # The first room will be at the door position - if len(roomList) == 0: - topX, topY = entryDoorPos - # Entry on the right - elif entryDoorWall == 0: - topX = entryDoorPos[0] - sizeX + 1 - y = entryDoorPos[1] - topY = self._rand_int(y - sizeY + 2, y) - # Entry wall on the south - elif entryDoorWall == 1: - x = entryDoorPos[0] - topX = self._rand_int(x - sizeX + 2, x) - topY = entryDoorPos[1] - sizeY + 1 - # Entry wall on the left - elif entryDoorWall == 2: - topX = entryDoorPos[0] - y = entryDoorPos[1] - topY = self._rand_int(y - sizeY + 2, y) - # Entry wall on the top - elif entryDoorWall == 3: - x = entryDoorPos[0] - topX = self._rand_int(x - sizeX + 2, x) - topY = entryDoorPos[1] - else: - assert False, entryDoorWall - - # If the room is out of the grid, can't place a room here - if topX < 0 or topY < 0: - return False - if topX + sizeX > self.width or topY + sizeY >= self.height: - return False - - # If the room intersects with previous rooms, can't place it here - for room in roomList[:-1]: - nonOverlap = \ - topX + sizeX < room.top[0] or \ - room.top[0] + room.size[0] <= topX or \ - topY + sizeY < room.top[1] or \ - room.top[1] + room.size[1] <= topY - - if not nonOverlap: - return False - - # Add this room to the list - roomList.append(Room( - (topX, topY), - (sizeX, sizeY), - entryDoorPos, - None - )) - - # If this was the last room, stop - if numLeft == 1: - return True - - # Try placing the next room - for i in range(0, 8): - - # Pick which wall to place the out door on - wallSet = set((0, 1, 2, 3)) - wallSet.remove(entryDoorWall) - exitDoorWall = self._rand_elem(sorted(wallSet)) - nextEntryWall = (exitDoorWall + 2) % 4 - - # Pick the exit door position - # Exit on right wall - if exitDoorWall == 0: - exitDoorPos = ( - topX + sizeX - 1, - topY + self._rand_int(1, sizeY - 1) - ) - # Exit on south wall - elif exitDoorWall == 1: - exitDoorPos = ( - topX + self._rand_int(1, sizeX - 1), - topY + sizeY - 1 - ) - # Exit on left wall - elif exitDoorWall == 2: - exitDoorPos = ( - topX, - topY + self._rand_int(1, sizeY - 1) - ) - # Exit on north wall - elif exitDoorWall == 3: - exitDoorPos = ( - topX + self._rand_int(1, sizeX - 1), - topY - ) - else: - assert False - - # Recursively create the other rooms - success = self._placeRoom( - numLeft - 1, - roomList=roomList, - minSz=minSz, - maxSz=maxSz, - entryDoorWall=nextEntryWall, - entryDoorPos=exitDoorPos - ) - - if success: - break - - return True - -class MultiRoomEnvN2S4(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=2, - maxNumRooms=2, - maxRoomSize=4 - ) - -class MultiRoomEnvN4S5(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=4, - maxNumRooms=4, - maxRoomSize=5 - ) - -class MultiRoomEnvN6(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=6, - maxNumRooms=6 - ) - -class MultiRoomEnvN7S4(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=7, - maxNumRooms=7, - maxRoomSize=4 - ) - -class MultiRoomEnvN7S8(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=7, - maxNumRooms=7, - maxRoomSize=8 - ) - -class MultiRoomEnvN10S4(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=10, - maxNumRooms=10, - maxRoomSize=4 - ) - -class MultiRoomEnvN10S10(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=10, - maxNumRooms=10, - maxRoomSize=10 - ) - -class MultiRoomEnvN12S10(MultiRoomEnv): - def __init__(self): - super().__init__( - minNumRooms=12, - maxNumRooms=12, - maxRoomSize=10 - ) - -register( - id='MiniGrid-MultiRoom-N2-S4-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN2S4' -) - -register( - id='MiniGrid-MultiRoom-N4-S5-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN4S5' -) - -register( - id='MiniGrid-MultiRoom-N6-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN6' -) - -register( - id='MiniGrid-MultiRoom-N7-S4-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN7S4' -) - -register( - id='MiniGrid-MultiRoom-N7-S8-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN7S8' -) - -register( - id='MiniGrid-MultiRoom-N10-S4-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN10S4' -) - -register( - id='MiniGrid-MultiRoom-N10-S10-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN10S10' -) - -register( - id='MiniGrid-MultiRoom-N12-S10-v0', - entry_point='gym_minigrid.envs:MultiRoomEnvN12S10' -) \ No newline at end of file diff --git a/spaces/flowers-team/SocialAISchool/models/multiheadedbabyai11.py b/spaces/flowers-team/SocialAISchool/models/multiheadedbabyai11.py deleted file mode 100644 index 9db104efa34e5ae023608d50965226fb46eed006..0000000000000000000000000000000000000000 --- a/spaces/flowers-team/SocialAISchool/models/multiheadedbabyai11.py +++ /dev/null @@ -1,419 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -from torch.autograd import Variable -from torch.distributions.categorical import Categorical -from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence -from utils.babyai_utils.supervised_losses import required_heads -import torch_ac - - - - - -# From https://github.com/ikostrikov/pytorch-a2c-ppo-acktr/blob/master/model.py -def initialize_parameters(m): - classname = m.__class__.__name__ - if classname.find('Linear') != -1: - m.weight.data.normal_(0, 1) - m.weight.data *= 1 / torch.sqrt(m.weight.data.pow(2).sum(1, keepdim=True)) - if m.bias is not None: - m.bias.data.fill_(0) - - -# Inspired by FiLMedBlock from https://arxiv.org/abs/1709.07871 -class FiLM(nn.Module): - def __init__(self, in_features, out_features, in_channels, imm_channels): - super().__init__() - self.conv1 = nn.Conv2d( - in_channels=in_channels, out_channels=imm_channels, - kernel_size=(3, 3), padding=1) - self.bn1 = nn.BatchNorm2d(imm_channels) - self.conv2 = nn.Conv2d( - in_channels=imm_channels, out_channels=out_features, - kernel_size=(3, 3), padding=1) - self.bn2 = nn.BatchNorm2d(out_features) - - self.weight = nn.Linear(in_features, out_features) - self.bias = nn.Linear(in_features, out_features) - - self.apply(initialize_parameters) - - def forward(self, x, y): - x = F.relu(self.bn1(self.conv1(x))) - x = self.conv2(x) - weight = self.weight(y).unsqueeze(2).unsqueeze(3) - bias = self.bias(y).unsqueeze(2).unsqueeze(3) - out = x * weight + bias - return F.relu(self.bn2(out)) - - -class ImageBOWEmbedding(nn.Module): - def __init__(self, max_value, embedding_dim): - super().__init__() - self.max_value = max_value - self.embedding_dim = embedding_dim - self.embedding = nn.Embedding(3 * max_value, embedding_dim) - self.apply(initialize_parameters) - - def forward(self, inputs): - offsets = torch.Tensor([0, self.max_value, 2 * self.max_value]).to(inputs.device) - inputs = (inputs + offsets[None, :, None, None]).long() - return self.embedding(inputs).sum(1).permute(0, 3, 1, 2) - -#notes: what they call instr is what we call text - -#class ACModel(nn.Module, babyai.rl.RecurrentACModel): - -# instr (them) == text (us) -class MultiHeadedBaby11ACModel(nn.Module, torch_ac.RecurrentACModel): - def __init__(self, obs_space, action_space, - image_dim=128, memory_dim=128, text_dim=128, dialog_dim=128, - use_text=False, use_dialogue=False, use_current_dialogue_only=False, lang_model="gru", use_memory=False, - arch="bow_endpool_res", aux_info=None): - super().__init__() - - # store config - self.config = locals() - - if use_current_dialogue_only: - raise NotImplementedError("current dialogue only") - - # multi dim - if action_space.shape == (): - raise ValueError("The action space is not multi modal. Use ACModel instead.") - - if use_text: # for now we do not consider goal conditioned policies - raise ValueError("You should not use text but dialogue. --text is cheating.") - - endpool = 'endpool' in arch - use_bow = 'bow' in arch - pixel = 'pixel' in arch - self.res = 'res' in arch - - # Decide which components are enabled - self.use_text = use_text - self.use_dialogue = use_dialogue - self.use_memory = use_memory - self.arch = arch - self.lang_model = lang_model - self.aux_info = aux_info - if self.res and image_dim != 128: - raise ValueError(f"image_dim is {image_dim}, expected 128") - self.image_dim = image_dim - self.memory_dim = memory_dim - self.text_dim = text_dim - self.dialog_dim = dialog_dim - - # multi dim - if action_space.shape == (): - raise ValueError("The action space is not multi modal. Use ACModel instead.") - - self.n_primitive_actions = action_space.nvec[0] + 1 # for talk - self.talk_action = int(self.n_primitive_actions) - 1 - self.n_utterance_actions = action_space.nvec[1:] - - self.env_action_space = action_space - self.model_raw_action_space = spaces.MultiDiscrete([self.n_primitive_actions, *self.n_utterance_actions]) - - self.obs_space = obs_space - # transform given 3d obs_space into what babyai11 baseline uses, i.e. 1d embedding size - n = obs_space["image"][0] - m = obs_space["image"][1] - self.obs_space = ((n-1)//2-2)*((m-1)//2-2)*64 - - for part in self.arch.split('_'): - if part not in ['original', 'bow', 'pixels', 'endpool', 'res']: - raise ValueError("Incorrect architecture name: {}".format(self.arch)) - - # if not self.use_text: - # raise ValueError("FiLM architecture can be used when textuctions are enabled") - self.image_conv = nn.Sequential(*[ - *([ImageBOWEmbedding(obs_space['image'], 128)] if use_bow else []), - *([nn.Conv2d( - in_channels=3, out_channels=128, kernel_size=(8, 8), - stride=8, padding=0)] if pixel else []), - nn.Conv2d( - in_channels=128 if use_bow or pixel else 3, out_channels=128, - kernel_size=(3, 3) if endpool else (2, 2), stride=1, padding=1), - nn.BatchNorm2d(128), - nn.ReLU(), - *([] if endpool else [nn.MaxPool2d(kernel_size=(2, 2), stride=2)]), - nn.Conv2d(in_channels=128, out_channels=128, kernel_size=(3, 3), padding=1), - nn.BatchNorm2d(128), - nn.ReLU(), - *([] if endpool else [nn.MaxPool2d(kernel_size=(2, 2), stride=2)]) - ]) - self.film_pool = nn.MaxPool2d(kernel_size=(7, 7) if endpool else (2, 2), stride=2) - - # Define DIALOGUE embedding - if self.use_dialogue: - if self.lang_model in ['gru', 'bigru', 'attgru']: - #self.word_embedding = nn.Embedding(obs_space["instr"], self.dialog_dim) - self.word_embedding = nn.Embedding(obs_space["text"], self.dialog_dim) - if self.lang_model in ['gru', 'bigru', 'attgru']: - gru_dim = self.dialog_dim - if self.lang_model in ['bigru', 'attgru']: - gru_dim //= 2 - self.dialog_rnn = nn.GRU( - self.dialog_dim, gru_dim, batch_first=True, - bidirectional=(self.lang_model in ['bigru', 'attgru'])) - self.final_dialog_dim = self.dialog_dim - else: - kernel_dim = 64 - kernel_sizes = [3, 4] - self.dialog_convs = nn.ModuleList([ - nn.Conv2d(1, kernel_dim, (K, self.dialog_dim)) for K in kernel_sizes]) - self.final_dialog_dim = kernel_dim * len(kernel_sizes) - - if self.lang_model == 'attgru': - self.memory2key = nn.Linear(self.memory_size, self.final_dialog_dim) - - num_module = 2 - self.controllers = [] - for ni in range(num_module): - mod = FiLM( - in_features=self.final_dialog_dim, - out_features=128 if ni < num_module-1 else self.image_dim, - in_channels=128, imm_channels=128) - self.controllers.append(mod) - self.add_module('FiLM_' + str(ni), mod) - - # Define memory and resize image embedding - self.embedding_size = self.image_dim - if self.use_memory: - self.memory_rnn = nn.LSTMCell(self.image_dim, self.memory_dim) - self.embedding_size = self.semi_memory_size - - # Define actor's model - self.actor = nn.Sequential( - nn.Linear(self.embedding_size, 64), - nn.Tanh(), - nn.Linear(64, self.n_primitive_actions) - ) - - self.talker = nn.ModuleList([ - nn.Sequential( - nn.Linear(self.embedding_size, 64), - nn.Tanh(), - nn.Linear(64, n) - ) for n in self.n_utterance_actions]) - - # Define critic's model - self.critic = nn.Sequential( - nn.Linear(self.embedding_size, 64), - nn.Tanh(), - nn.Linear(64, 1) - ) - - # Initialize parameters correctly - self.apply(initialize_parameters) - - # Define head for extra info - if self.aux_info: - self.extra_heads = None - self.add_heads() - - def add_heads(self): - ''' - When using auxiliary tasks, the environment yields at each step some binary, continous, or multiclass - information. The agent needs to predict those information. This function add extra heads to the model - that output the predictions. There is a head per extra information (the head type depends on the extra - information type). - ''' - self.extra_heads = nn.ModuleDict() - for info in self.aux_info: - if required_heads[info] == 'binary': - self.extra_heads[info] = nn.Linear(self.embedding_size, 1) - elif required_heads[info].startswith('multiclass'): - n_classes = int(required_heads[info].split('multiclass')[-1]) - self.extra_heads[info] = nn.Linear(self.embedding_size, n_classes) - elif required_heads[info].startswith('continuous'): - if required_heads[info].endswith('01'): - self.extra_heads[info] = nn.Sequential(nn.Linear(self.embedding_size, 1), nn.Sigmoid()) - else: - raise ValueError('Only continous01 is implemented') - else: - raise ValueError('Type not supported') - # initializing these parameters independently is done in order to have consistency of results when using - # supervised-loss-coef = 0 and when not using any extra binary information - self.extra_heads[info].apply(initialize_parameters) - - def add_extra_heads_if_necessary(self, aux_info): - ''' - This function allows using a pre-trained model without aux_info and add aux_info to it and still make - it possible to finetune. - ''' - try: - if not hasattr(self, 'aux_info') or not set(self.aux_info) == set(aux_info): - self.aux_info = aux_info - self.add_heads() - except Exception: - raise ValueError('Could not add extra heads') - - @property - def memory_size(self): - return 2 * self.semi_memory_size - - @property - def semi_memory_size(self): - return self.memory_dim - - def forward(self, obs, memory, dialog_embedding=None): - if self.use_dialogue and dialog_embedding is None: - #instr_embedding = self._get_instr_embedding(obs.instr) - - if not hasattr(obs, "utterance_history"): - raise ValueError("The environment need's to be updated to 'utterance' and 'utterance_history' keys'") - - dialog_embedding = self._get_dialog_embedding(obs.utterance_history) - if self.use_dialogue and self.lang_model == "attgru": - # outputs: B x L x D - # memory: B x M - #mask = (obs.instr != 0).float() - mask = (obs.utterance_history != 0).float() - # The mask tensor has the same length as obs.instr, and - # thus can be both shorter and longer than instr_embedding. - # It can be longer if instr_embedding is computed - # for a subbatch of obs.instr. - # It can be shorter if obs.instr is a subbatch of - # the batch that instr_embeddings was computed for. - # Here, we make sure that mask and instr_embeddings - # have equal length along dimension 1. - mask = mask[:, :dialog_embedding.shape[1]] - dialog_embedding = dialog_embedding[:, :mask.shape[1]] - - keys = self.memory2key(memory) - pre_softmax = (keys[:, None, :] * dialog_embedding).sum(2) + 1000 * mask - attention = F.softmax(pre_softmax, dim=1) - dialog_embedding = (dialog_embedding * attention[:, :, None]).sum(1) - - x = torch.transpose(torch.transpose(obs.image, 1, 3), 2, 3) - - if 'pixel' in self.arch: - x /= 256.0 - x = self.image_conv(x) - if self.use_dialogue: - for controller in self.controllers: - out = controller(x, dialog_embedding) - if self.res: - out += x - x = out - x = F.relu(self.film_pool(x)) - x = x.reshape(x.shape[0], -1) - - if self.use_memory: - hidden = (memory[:, :self.semi_memory_size], memory[:, self.semi_memory_size:]) - hidden = self.memory_rnn(x, hidden) - embedding = hidden[0] - memory = torch.cat(hidden, dim=1) - else: - embedding = x - - if hasattr(self, 'aux_info') and self.aux_info: - extra_predictions = {info: self.extra_heads[info](embedding) for info in self.extra_heads} - else: - extra_predictions = dict() - - # x = self.actor(embedding) - # dist = Categorical(logits=F.log_softmax(x, dim=1)) - x = self.actor(embedding) - primitive_actions_dist = Categorical(logits=F.log_softmax(x, dim=1)) - - x = self.critic(embedding) - value = x.squeeze(1) - utterance_actions_dists = [ - Categorical(logits=F.log_softmax( - tal(embedding), - dim=1, - )) for tal in self.talker - ] - - dist = [primitive_actions_dist] + utterance_actions_dists - #return {'dist': dist, 'value': value, 'memory': memory, 'extra_predictions': extra_predictions} - return dist, value, memory - - def _get_dialog_embedding(self, dialog): - lengths = (dialog != 0).sum(1).long() - if self.lang_model == 'gru': - out, _ = self.dialog_rnn(self.word_embedding(dialog)) - hidden = out[range(len(lengths)), lengths-1, :] - return hidden - - elif self.lang_model in ['bigru', 'attgru']: - masks = (dialog != 0).float() - - if lengths.shape[0] > 1: - seq_lengths, perm_idx = lengths.sort(0, descending=True) - iperm_idx = torch.LongTensor(perm_idx.shape).fill_(0) - if dialog.is_cuda: iperm_idx = iperm_idx.cuda() - for i, v in enumerate(perm_idx): - iperm_idx[v.data] = i - - inputs = self.word_embedding(dialog) - inputs = inputs[perm_idx] - - inputs = pack_padded_sequence(inputs, seq_lengths.data.cpu().numpy(), batch_first=True) - - outputs, final_states = self.dialog_rnn(inputs) - else: - dialog = dialog[:, 0:lengths[0]] - outputs, final_states = self.dialog_rnn(self.word_embedding(dialog)) - iperm_idx = None - final_states = final_states.transpose(0, 1).contiguous() - final_states = final_states.view(final_states.shape[0], -1) - if iperm_idx is not None: - outputs, _ = pad_packed_sequence(outputs, batch_first=True) - outputs = outputs[iperm_idx] - final_states = final_states[iperm_idx] - - return outputs if self.lang_model == 'attgru' else final_states - - else: - ValueError("Undefined dialoguction architecture: {}".format(self.use_dialogue)) - - # add action sampling to fit our interaction pipeline - ## baby ai [[Categorical(logits: torch.Size([16, 8])), Categorical(logits: torch.Size([16, 2])), Categorical(logits: torch.Size([16, 2]))]] - ## mh ac [Categorical(logits: torch.Size([16, 8])), Categorical(logits: torch.Size([16, 2])), Categorical(logits: torch.Size([16, 2]))] - def sample_action(self, dist): - # print(dist) - # raise - return torch.stack([d.sample() for d in dist], dim=1) - - # # add construct final action to fit our interaction pipeline - # def construct_final_action(self, action): - # return action - def construct_final_action(self, action): - act_mask = action[:, 0] != self.n_primitive_actions - 1 - - nan_mask = np.array([ - np.array([1, np.nan, np.nan]) if t else np.array([np.nan, 1, 1]) for t in act_mask - ]) - - action = nan_mask*action - - return action - - # add calculate log probs to fit our interaction pipeline - def calculate_log_probs(self, dist, action): - return torch.stack([d.log_prob(action[:, i]) for i, d in enumerate(dist)], dim=1) - - # add calculate action masks to fit our interaction pipeline - def calculate_action_masks(self, action): - talk_mask = action[:, 0] == self.talk_action - mask = torch.stack( - (torch.ones_like(talk_mask), talk_mask, talk_mask), - dim=1).detach() - assert action.shape == mask.shape - - return mask - # def calculate_action_masks(self, action): - # mask = torch.ones_like(action) - # assert action.shape == mask.shape - # return mask - - def get_config_dict(self): - del self.config['__class__'] - self.config['self'] = str(self.config['self']) - self.config['action_space'] = self.config['action_space'].nvec.tolist() - return self.config diff --git a/spaces/freddyaboulton/3.1.4.9-all-demos/demos/blocks_js_methods/run.py b/spaces/freddyaboulton/3.1.4.9-all-demos/demos/blocks_js_methods/run.py deleted file mode 100644 index fd7ab727af45f54bf8033607278c5b5eac29e752..0000000000000000000000000000000000000000 --- a/spaces/freddyaboulton/3.1.4.9-all-demos/demos/blocks_js_methods/run.py +++ /dev/null @@ -1,28 +0,0 @@ -import gradio as gr - -blocks = gr.Blocks() - -with blocks as demo: - subject = gr.Textbox(placeholder="subject") - verb = gr.Radio(["ate", "loved", "hated"]) - object = gr.Textbox(placeholder="object") - - with gr.Row(): - btn = gr.Button("Create sentence.") - reverse_btn = gr.Button("Reverse sentence.") - foo_bar_btn = gr.Button("Foo bar.") - - def sentence_maker(w1, w2, w3): - return f"{w1} {w2} {w3}" - - output1 = gr.Textbox(label="output 1") - output2 = gr.Textbox(label="verb") - output3 = gr.Textbox(label="verb reversed") - - btn.click(sentence_maker, [subject, verb, object], output1) - reverse_btn.click(None, [subject, verb, object], output2, _js="(s, v, o) => o + ' ' + v + ' ' + s") - verb.change(lambda x: x, verb, output3, _js="(x) => [...x].reverse().join('')") - foo_bar_btn.click(None, [], subject, _js="(x) => x + ' foo'") - -if __name__ == "__main__": - demo.launch() \ No newline at end of file diff --git a/spaces/freddyaboulton/3.1.4.9-all-demos/demos/hangman/run.py b/spaces/freddyaboulton/3.1.4.9-all-demos/demos/hangman/run.py deleted file mode 100644 index ddd638f60bc671d28ed773ec98bf12fe15e33f11..0000000000000000000000000000000000000000 --- a/spaces/freddyaboulton/3.1.4.9-all-demos/demos/hangman/run.py +++ /dev/null @@ -1,36 +0,0 @@ -import gradio as gr -import random - -secret_word = "gradio" - -with gr.Blocks() as demo: - used_letters_var = gr.Variable([]) - with gr.Row() as row: - with gr.Column(): - input_letter = gr.Textbox(label="Enter letter") - btn = gr.Button("Guess Letter") - with gr.Column(): - hangman = gr.Textbox( - label="Hangman", - value="_"*len(secret_word) - ) - used_letters_box = gr.Textbox(label="Used Letters") - - def guess_letter(letter, used_letters): - used_letters.append(letter) - answer = "".join([ - (letter if letter in used_letters else "_") - for letter in secret_word - ]) - return { - used_letters_var: used_letters, - used_letters_box: ", ".join(used_letters), - hangman: answer - } - btn.click( - guess_letter, - [input_letter, used_letters_var], - [used_letters_var, used_letters_box, hangman] - ) -if __name__ == "__main__": - demo.launch() \ No newline at end of file diff --git a/spaces/gabibi7am/rvc-models/infer_pack/modules.py b/spaces/gabibi7am/rvc-models/infer_pack/modules.py deleted file mode 100644 index 960481cedad9a6106f2bf0b9e86e82b120f7b33f..0000000000000000000000000000000000000000 --- a/spaces/gabibi7am/rvc-models/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/giulio98/codebleu/parsercode/DFG.py b/spaces/giulio98/codebleu/parsercode/DFG.py deleted file mode 100644 index bad674e683b5764e03379528636b5398827b49ce..0000000000000000000000000000000000000000 --- a/spaces/giulio98/codebleu/parsercode/DFG.py +++ /dev/null @@ -1,1184 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -from tree_sitter import Language, Parser -from .utils import (remove_comments_and_docstrings, - tree_to_token_index, - index_to_code_token, - tree_to_variable_index) - - -def DFG_python(root_node,index_to_code,states): - assignment=['assignment','augmented_assignment','for_in_clause'] - if_statement=['if_statement'] - for_statement=['for_statement'] - while_statement=['while_statement'] - do_first_statement=['for_in_clause'] - def_statement=['default_parameter'] - states=states.copy() - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('value') - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_python(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - if root_node.type=='for_in_clause': - right_nodes=[root_node.children[-1]] - left_nodes=[root_node.child_by_field_name('left')] - else: - if root_node.child_by_field_name('right') is None: - return [],states - left_nodes=[x for x in root_node.child_by_field_name('left').children if x.type!=','] - right_nodes=[x for x in root_node.child_by_field_name('right').children if x.type!=','] - if len(right_nodes)!=len(left_nodes): - left_nodes=[root_node.child_by_field_name('left')] - right_nodes=[root_node.child_by_field_name('right')] - if len(left_nodes)==0: - left_nodes=[root_node.child_by_field_name('left')] - if len(right_nodes)==0: - right_nodes=[root_node.child_by_field_name('right')] - DFG=[] - for node in right_nodes: - temp,states=DFG_python(node,index_to_code,states) - DFG+=temp - - for left_node,right_node in zip(left_nodes,right_nodes): - left_tokens_index=tree_to_variable_index(left_node,index_to_code) - right_tokens_index=tree_to_variable_index(right_node,index_to_code) - temp=[] - for token1_index in left_tokens_index: - idx1,code1=index_to_code[token1_index] - temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index], - [index_to_code[x][0] for x in right_tokens_index])) - states[code1]=[idx1] - DFG+=temp - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in ['elif_clause','else_clause']: - temp,current_states=DFG_python(child,index_to_code,current_states) - DFG+=temp - else: - temp,new_states=DFG_python(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - if tag is False: - others_states.append(states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for i in range(2): - right_nodes=[x for x in root_node.child_by_field_name('right').children if x.type!=','] - left_nodes=[x for x in root_node.child_by_field_name('left').children if x.type!=','] - if len(right_nodes)!=len(left_nodes): - left_nodes=[root_node.child_by_field_name('left')] - right_nodes=[root_node.child_by_field_name('right')] - if len(left_nodes)==0: - left_nodes=[root_node.child_by_field_name('left')] - if len(right_nodes)==0: - right_nodes=[root_node.child_by_field_name('right')] - for node in right_nodes: - temp,states=DFG_python(node,index_to_code,states) - DFG+=temp - for left_node,right_node in zip(left_nodes,right_nodes): - left_tokens_index=tree_to_variable_index(left_node,index_to_code) - right_tokens_index=tree_to_variable_index(right_node,index_to_code) - temp=[] - for token1_index in left_tokens_index: - idx1,code1=index_to_code[token1_index] - temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index], - [index_to_code[x][0] for x in right_tokens_index])) - states[code1]=[idx1] - DFG+=temp - if root_node.children[-1].type=="block": - temp,states=DFG_python(root_node.children[-1],index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in while_statement: - DFG=[] - for i in range(2): - for child in root_node.children: - temp,states=DFG_python(child,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_python(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_python(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - - -def DFG_java(root_node,index_to_code,states): - assignment=['assignment_expression'] - def_statement=['variable_declarator'] - increment_statement=['update_expression'] - if_statement=['if_statement','else'] - for_statement=['for_statement'] - enhanced_for_statement=['enhanced_for_statement'] - while_statement=['while_statement'] - do_first_statement=[] - states=states.copy() - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('value') - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_java(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - left_nodes=root_node.child_by_field_name('left') - right_nodes=root_node.child_by_field_name('right') - DFG=[] - temp,states=DFG_java(right_nodes,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(left_nodes,index_to_code) - value_indexs=tree_to_variable_index(right_nodes,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in increment_statement: - DFG=[] - indexs=tree_to_variable_index(root_node,index_to_code) - for index1 in indexs: - idx1,code1=index_to_code[index1] - for index2 in indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - flag=False - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in if_statement and flag is False: - temp,current_states=DFG_java(child,index_to_code,current_states) - DFG+=temp - else: - flag=True - temp,new_states=DFG_java(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - if tag is False: - others_states.append(states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for child in root_node.children: - temp,states=DFG_java(child,index_to_code,states) - DFG+=temp - flag=False - for child in root_node.children: - if flag: - temp,states=DFG_java(child,index_to_code,states) - DFG+=temp - elif child.type=="local_variable_declaration": - flag=True - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in enhanced_for_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('value') - body=root_node.child_by_field_name('body') - DFG=[] - for i in range(2): - temp,states=DFG_java(value,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - temp,states=DFG_java(body,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in while_statement: - DFG=[] - for i in range(2): - for child in root_node.children: - temp,states=DFG_java(child,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_java(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_java(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - -def DFG_csharp(root_node,index_to_code,states): - assignment=['assignment_expression'] - def_statement=['variable_declarator'] - increment_statement=['postfix_unary_expression'] - if_statement=['if_statement','else'] - for_statement=['for_statement'] - enhanced_for_statement=['for_each_statement'] - while_statement=['while_statement'] - do_first_statement=[] - states=states.copy() - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - if len(root_node.children)==2: - name=root_node.children[0] - value=root_node.children[1] - else: - name=root_node.children[0] - value=None - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_csharp(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - left_nodes=root_node.child_by_field_name('left') - right_nodes=root_node.child_by_field_name('right') - DFG=[] - temp,states=DFG_csharp(right_nodes,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(left_nodes,index_to_code) - value_indexs=tree_to_variable_index(right_nodes,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in increment_statement: - DFG=[] - indexs=tree_to_variable_index(root_node,index_to_code) - for index1 in indexs: - idx1,code1=index_to_code[index1] - for index2 in indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - flag=False - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in if_statement and flag is False: - temp,current_states=DFG_csharp(child,index_to_code,current_states) - DFG+=temp - else: - flag=True - temp,new_states=DFG_csharp(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - if tag is False: - others_states.append(states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for child in root_node.children: - temp,states=DFG_csharp(child,index_to_code,states) - DFG+=temp - flag=False - for child in root_node.children: - if flag: - temp,states=DFG_csharp(child,index_to_code,states) - DFG+=temp - elif child.type=="local_variable_declaration": - flag=True - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in enhanced_for_statement: - name=root_node.child_by_field_name('left') - value=root_node.child_by_field_name('right') - body=root_node.child_by_field_name('body') - DFG=[] - for i in range(2): - temp,states=DFG_csharp(value,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - temp,states=DFG_csharp(body,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in while_statement: - DFG=[] - for i in range(2): - for child in root_node.children: - temp,states=DFG_csharp(child,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_csharp(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_csharp(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - - - - -def DFG_ruby(root_node,index_to_code,states): - assignment=['assignment','operator_assignment'] - if_statement=['if','elsif','else','unless','when'] - for_statement=['for'] - while_statement=['while_modifier','until'] - do_first_statement=[] - def_statement=['keyword_parameter'] - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - states=states.copy() - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('value') - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_ruby(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - left_nodes=[x for x in root_node.child_by_field_name('left').children if x.type!=','] - right_nodes=[x for x in root_node.child_by_field_name('right').children if x.type!=','] - if len(right_nodes)!=len(left_nodes): - left_nodes=[root_node.child_by_field_name('left')] - right_nodes=[root_node.child_by_field_name('right')] - if len(left_nodes)==0: - left_nodes=[root_node.child_by_field_name('left')] - if len(right_nodes)==0: - right_nodes=[root_node.child_by_field_name('right')] - if root_node.type=="operator_assignment": - left_nodes=[root_node.children[0]] - right_nodes=[root_node.children[-1]] - - DFG=[] - for node in right_nodes: - temp,states=DFG_ruby(node,index_to_code,states) - DFG+=temp - - for left_node,right_node in zip(left_nodes,right_nodes): - left_tokens_index=tree_to_variable_index(left_node,index_to_code) - right_tokens_index=tree_to_variable_index(right_node,index_to_code) - temp=[] - for token1_index in left_tokens_index: - idx1,code1=index_to_code[token1_index] - temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index], - [index_to_code[x][0] for x in right_tokens_index])) - states[code1]=[idx1] - DFG+=temp - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in if_statement: - temp,current_states=DFG_ruby(child,index_to_code,current_states) - DFG+=temp - else: - temp,new_states=DFG_ruby(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - if tag is False: - others_states.append(states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for i in range(2): - left_nodes=[root_node.child_by_field_name('pattern')] - right_nodes=[root_node.child_by_field_name('value')] - assert len(right_nodes)==len(left_nodes) - for node in right_nodes: - temp,states=DFG_ruby(node,index_to_code,states) - DFG+=temp - for left_node,right_node in zip(left_nodes,right_nodes): - left_tokens_index=tree_to_variable_index(left_node,index_to_code) - right_tokens_index=tree_to_variable_index(right_node,index_to_code) - temp=[] - for token1_index in left_tokens_index: - idx1,code1=index_to_code[token1_index] - temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index], - [index_to_code[x][0] for x in right_tokens_index])) - states[code1]=[idx1] - DFG+=temp - temp,states=DFG_ruby(root_node.child_by_field_name('body'),index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in while_statement: - DFG=[] - for i in range(2): - for child in root_node.children: - temp,states=DFG_ruby(child,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_ruby(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_ruby(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - -def DFG_go(root_node,index_to_code,states): - assignment=['assignment_statement',] - def_statement=['var_spec'] - increment_statement=['inc_statement'] - if_statement=['if_statement','else'] - for_statement=['for_statement'] - enhanced_for_statement=[] - while_statement=[] - do_first_statement=[] - states=states.copy() - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('value') - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_go(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - left_nodes=root_node.child_by_field_name('left') - right_nodes=root_node.child_by_field_name('right') - DFG=[] - temp,states=DFG_go(right_nodes,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(left_nodes,index_to_code) - value_indexs=tree_to_variable_index(right_nodes,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in increment_statement: - DFG=[] - indexs=tree_to_variable_index(root_node,index_to_code) - for index1 in indexs: - idx1,code1=index_to_code[index1] - for index2 in indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - flag=False - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in if_statement and flag is False: - temp,current_states=DFG_go(child,index_to_code,current_states) - DFG+=temp - else: - flag=True - temp,new_states=DFG_go(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - if tag is False: - others_states.append(states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in states: - if key not in new_states: - new_states[key]=states[key] - else: - new_states[key]+=states[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for child in root_node.children: - temp,states=DFG_go(child,index_to_code,states) - DFG+=temp - flag=False - for child in root_node.children: - if flag: - temp,states=DFG_go(child,index_to_code,states) - DFG+=temp - elif child.type=="for_clause": - if child.child_by_field_name('update') is not None: - temp,states=DFG_go(child.child_by_field_name('update'),index_to_code,states) - DFG+=temp - flag=True - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_go(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_go(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - - - - -def DFG_php(root_node,index_to_code,states): - assignment=['assignment_expression','augmented_assignment_expression'] - def_statement=['simple_parameter'] - increment_statement=['update_expression'] - if_statement=['if_statement','else_clause'] - for_statement=['for_statement'] - enhanced_for_statement=['foreach_statement'] - while_statement=['while_statement'] - do_first_statement=[] - states=states.copy() - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('default_value') - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_php(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - left_nodes=root_node.child_by_field_name('left') - right_nodes=root_node.child_by_field_name('right') - DFG=[] - temp,states=DFG_php(right_nodes,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(left_nodes,index_to_code) - value_indexs=tree_to_variable_index(right_nodes,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in increment_statement: - DFG=[] - indexs=tree_to_variable_index(root_node,index_to_code) - for index1 in indexs: - idx1,code1=index_to_code[index1] - for index2 in indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - flag=False - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in if_statement and flag is False: - temp,current_states=DFG_php(child,index_to_code,current_states) - DFG+=temp - else: - flag=True - temp,new_states=DFG_php(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in states: - if key not in new_states: - new_states[key]=states[key] - else: - new_states[key]+=states[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for child in root_node.children: - temp,states=DFG_php(child,index_to_code,states) - DFG+=temp - flag=False - for child in root_node.children: - if flag: - temp,states=DFG_php(child,index_to_code,states) - DFG+=temp - elif child.type=="assignment_expression": - flag=True - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in enhanced_for_statement: - name=None - value=None - for child in root_node.children: - if child.type=='variable_name' and value is None: - value=child - elif child.type=='variable_name' and name is None: - name=child - break - body=root_node.child_by_field_name('body') - DFG=[] - for i in range(2): - temp,states=DFG_php(value,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - temp,states=DFG_php(body,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in while_statement: - DFG=[] - for i in range(2): - for child in root_node.children: - temp,states=DFG_php(child,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_php(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_php(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - - -def DFG_javascript(root_node,index_to_code,states): - assignment=['assignment_pattern','augmented_assignment_expression'] - def_statement=['variable_declarator'] - increment_statement=['update_expression'] - if_statement=['if_statement','else'] - for_statement=['for_statement'] - enhanced_for_statement=[] - while_statement=['while_statement'] - do_first_statement=[] - states=states.copy() - if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': - idx,code=index_to_code[(root_node.start_point,root_node.end_point)] - if root_node.type==code: - return [],states - elif code in states: - return [(code,idx,'comesFrom',[code],states[code].copy())],states - else: - if root_node.type=='identifier': - states[code]=[idx] - return [(code,idx,'comesFrom',[],[])],states - elif root_node.type in def_statement: - name=root_node.child_by_field_name('name') - value=root_node.child_by_field_name('value') - DFG=[] - if value is None: - indexs=tree_to_variable_index(name,index_to_code) - for index in indexs: - idx,code=index_to_code[index] - DFG.append((code,idx,'comesFrom',[],[])) - states[code]=[idx] - return sorted(DFG,key=lambda x:x[1]),states - else: - name_indexs=tree_to_variable_index(name,index_to_code) - value_indexs=tree_to_variable_index(value,index_to_code) - temp,states=DFG_javascript(value,index_to_code,states) - DFG+=temp - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'comesFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in assignment: - left_nodes=root_node.child_by_field_name('left') - right_nodes=root_node.child_by_field_name('right') - DFG=[] - temp,states=DFG_javascript(right_nodes,index_to_code,states) - DFG+=temp - name_indexs=tree_to_variable_index(left_nodes,index_to_code) - value_indexs=tree_to_variable_index(right_nodes,index_to_code) - for index1 in name_indexs: - idx1,code1=index_to_code[index1] - for index2 in value_indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in increment_statement: - DFG=[] - indexs=tree_to_variable_index(root_node,index_to_code) - for index1 in indexs: - idx1,code1=index_to_code[index1] - for index2 in indexs: - idx2,code2=index_to_code[index2] - DFG.append((code1,idx1,'computedFrom',[code2],[idx2])) - states[code1]=[idx1] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in if_statement: - DFG=[] - current_states=states.copy() - others_states=[] - flag=False - tag=False - if 'else' in root_node.type: - tag=True - for child in root_node.children: - if 'else' in child.type: - tag=True - if child.type not in if_statement and flag is False: - temp,current_states=DFG_javascript(child,index_to_code,current_states) - DFG+=temp - else: - flag=True - temp,new_states=DFG_javascript(child,index_to_code,states) - DFG+=temp - others_states.append(new_states) - others_states.append(current_states) - if tag is False: - others_states.append(states) - new_states={} - for dic in others_states: - for key in dic: - if key not in new_states: - new_states[key]=dic[key].copy() - else: - new_states[key]+=dic[key] - for key in states: - if key not in new_states: - new_states[key]=states[key] - else: - new_states[key]+=states[key] - for key in new_states: - new_states[key]=sorted(list(set(new_states[key]))) - return sorted(DFG,key=lambda x:x[1]),new_states - elif root_node.type in for_statement: - DFG=[] - for child in root_node.children: - temp,states=DFG_javascript(child,index_to_code,states) - DFG+=temp - flag=False - for child in root_node.children: - if flag: - temp,states=DFG_javascript(child,index_to_code,states) - DFG+=temp - elif child.type=="variable_declaration": - flag=True - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - elif root_node.type in while_statement: - DFG=[] - for i in range(2): - for child in root_node.children: - temp,states=DFG_javascript(child,index_to_code,states) - DFG+=temp - dic={} - for x in DFG: - if (x[0],x[1],x[2]) not in dic: - dic[(x[0],x[1],x[2])]=[x[3],x[4]] - else: - dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3])) - dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4]))) - DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])] - return sorted(DFG,key=lambda x:x[1]),states - else: - DFG=[] - for child in root_node.children: - if child.type in do_first_statement: - temp,states=DFG_javascript(child,index_to_code,states) - DFG+=temp - for child in root_node.children: - if child.type not in do_first_statement: - temp,states=DFG_javascript(child,index_to_code,states) - DFG+=temp - - return sorted(DFG,key=lambda x:x[1]),states - - - diff --git a/spaces/gotiQspiryo/whisper-ui/examples/Camfrog Pro 6.5.3 Latest Activation Crack Patch Serial Tips and Tricks.md b/spaces/gotiQspiryo/whisper-ui/examples/Camfrog Pro 6.5.3 Latest Activation Crack Patch Serial Tips and Tricks.md deleted file mode 100644 index c3b49176561f18ab65cbcc02693d8337533ddb2f..0000000000000000000000000000000000000000 --- a/spaces/gotiQspiryo/whisper-ui/examples/Camfrog Pro 6.5.3 Latest Activation Crack Patch Serial Tips and Tricks.md +++ /dev/null @@ -1,6 +0,0 @@ -

    camfrog pro 6.5.3 latest activation crack patch serial


    Download Zip ✵✵✵ https://urlgoal.com/2uyMi1



    - - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/gradio/HuBERT/examples/noisychannel/rerank_score_lm.py b/spaces/gradio/HuBERT/examples/noisychannel/rerank_score_lm.py deleted file mode 100644 index e80948d78b02561cbd09d72c319222105f41f6bb..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/examples/noisychannel/rerank_score_lm.py +++ /dev/null @@ -1,81 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import os - -from fairseq import options - -from examples.noisychannel import rerank_options, rerank_utils - - -def score_lm(args): - using_nbest = args.nbest_list is not None - ( - pre_gen, - left_to_right_preprocessed_dir, - right_to_left_preprocessed_dir, - backwards_preprocessed_dir, - lm_preprocessed_dir, - ) = rerank_utils.get_directories( - args.data_dir_name, - args.num_rescore, - args.gen_subset, - args.gen_model_name, - args.shard_id, - args.num_shards, - args.sampling, - args.prefix_len, - args.target_prefix_frac, - args.source_prefix_frac, - ) - - predictions_bpe_file = pre_gen + "/generate_output_bpe.txt" - if using_nbest: - print("Using predefined n-best list from interactive.py") - predictions_bpe_file = args.nbest_list - - gen_output = rerank_utils.BitextOutputFromGen( - predictions_bpe_file, bpe_symbol=args.post_process, nbest=using_nbest - ) - - if args.language_model is not None: - lm_score_file = rerank_utils.rescore_file_name( - pre_gen, args.prefix_len, args.lm_name, lm_file=True - ) - - if args.language_model is not None and not os.path.isfile(lm_score_file): - print("STEP 4.5: language modeling for P(T)") - if args.lm_bpe_code is None: - bpe_status = "no bpe" - elif args.lm_bpe_code == "shared": - bpe_status = "shared" - else: - bpe_status = "different" - - rerank_utils.lm_scoring( - lm_preprocessed_dir, - bpe_status, - gen_output, - pre_gen, - args.lm_dict, - args.lm_name, - args.language_model, - args.lm_bpe_code, - 128, - lm_score_file, - args.target_lang, - args.source_lang, - prefix_len=args.prefix_len, - ) - - -def cli_main(): - parser = rerank_options.get_reranking_parser() - args = options.parse_args_and_arch(parser) - score_lm(args) - - -if __name__ == "__main__": - cli_main() diff --git a/spaces/gradio/soft/README.md b/spaces/gradio/soft/README.md deleted file mode 100644 index 3b09efe5956c248d6d58af785a298dc3d2d78438..0000000000000000000000000000000000000000 --- a/spaces/gradio/soft/README.md +++ /dev/null @@ -1,17 +0,0 @@ - ---- -tags: [gradio-theme] -title: soft -colorFrom: orange -colorTo: purple -sdk: gradio -sdk_version: 3.42.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- -# soft -## Description -Add a description of this theme here! -## Contributions -Thanks to [@aliabid94](https://huggingface.co/aliabid94) for adding this gradio theme! diff --git a/spaces/groupeonepoint/LongDocumentQuestioner/document_questioner_app.py b/spaces/groupeonepoint/LongDocumentQuestioner/document_questioner_app.py deleted file mode 100644 index 6472c9cea042272f58117e612975d69663241110..0000000000000000000000000000000000000000 --- a/spaces/groupeonepoint/LongDocumentQuestioner/document_questioner_app.py +++ /dev/null @@ -1,109 +0,0 @@ -import openai -import os -import gradio as gr -import chromadb -from langchain.document_loaders import PyPDFLoader -from langchain.embeddings.openai import OpenAIEmbeddings -from langchain.vectorstores import Chroma -from langchain.indexes import VectorstoreIndexCreator -from langchain.chains import ConversationalRetrievalChain -from langchain.prompts import PromptTemplate -from langchain.chat_models import ChatOpenAI -from langchain.llms import OpenAI - -def load_document(Document): - - # loads a PDF document - if not Document: - return "Merci de fournir un document PDF" - if not Document.name.endswith('.pdf'): - return ("Merci de fournir un document PDF") - - loader = PyPDFLoader(Document.name) - docs = loader.load() - global k - k = len(docs) - - # Create embeddings - embeddings = OpenAIEmbeddings(openai_api_key = os.environ['OpenaiKey']) - - # Write in DB - global docsearch - docsearch = Chroma.from_documents(docs, embeddings, ids=["page" + str(d.metadata["page"]) for d in docs], k=1) - global chat_history - chat_history = [] - - return "Endodage créé" - -def get_chat_history(inputs) -> str: - res = [] - for human, ai in inputs: - res.append(f"Question : {human}\nRéponse : {ai}") - return "\n".join(res) - -def question_document(Question): - - if "docsearch" not in globals(): - return "Merci d'encoder un document PDF" - - # Define LLM - turbo = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, openai_api_key = os.environ['OpenaiKey']) - davinci = OpenAI(model_name = "text-davinci-003", openai_api_key = os.environ['OpenaiKey']) - - # Customize map_reduce prompts - #question_template = """{context} - #Precise the number starting the above text in your answer. It corresponds to its page number in the document it is from. Label this number as "page". - #Also make sure to answer in the same langage than the following question. - #QUESTION : {question} - #ANSWER : - #""" - - #combine_template = """{summaries} - #Note that the above text is based on transient extracts from one source document. - #So make sure to not mention different documents or extracts or passages or portions or texts. There is only one, entire document. - #Also make sure to answer in the same langage than the following question. - #QUESTION : {question}. - #ANSWER : - #""" - - #question_prompt = PromptTemplate(template = question_template, input_variables=['context', 'question']) - #combine_prompt = PromptTemplate(template = combine_template, input_variables=['summaries', 'question']) - - # Define chain - #chain_type_kwargs = { "combine_prompt" : combine_prompt, "question_prompt" : question_prompt} #, "return_intermediate_steps" : True} - #qa = RetrievalQAWithSourcesChain.from_chain_type(llm = llm, chain_type = "map_reduce", chain_type_kwargs = chain_type_kwargs, retriever=docsearch.as_retriever(), return_source_documents = True) - - vectordbkwargs = {"search_distance": 10} - search_kwargs={"k" : k} - - qa = ConversationalRetrievalChain.from_llm(llm = turbo, chain_type = "map_reduce",retriever=docsearch.as_retriever(search_kwargs = search_kwargs), get_chat_history = get_chat_history, return_source_documents = True) - answer = qa({"question" : Question,"chat_history":chat_history, "vectordbkwargs": vectordbkwargs}, return_only_outputs = True) - chat_history.append((Question, answer["answer"])) - #answer = qa({"question" : Question}, ) - print(answer) - return "".join(get_chat_history(chat_history)) - -with gr.Blocks() as demo: - - gr.Markdown( - """ - # Interrogateur de PDF - par Nicolas et Alex - """) - - with gr.Row(): - - with gr.Column(): - input_file = gr.inputs.File(label="Charger un document") - greet_btnee = gr.Button("Encoder le document") - output_words = gr.outputs.Textbox(label="Encodage") - greet_btnee.click(fn=load_document, inputs=input_file, outputs = output_words) - - with gr.Column(): - text = gr.inputs.Textbox(label="Question") - greet_btn = gr.Button("Poser une question") - answer = gr.Textbox(label = "Réponse", lines = 8) - greet_btn.click(fn = question_document, inputs = text, outputs = answer) - - -demo.launch() \ No newline at end of file diff --git a/spaces/gsaivinay/Llama-2-13B-GGML-UI/types/index.ts b/spaces/gsaivinay/Llama-2-13B-GGML-UI/types/index.ts deleted file mode 100644 index cb0ff5c3b541f646105198ee23ac0fc3d805023e..0000000000000000000000000000000000000000 --- a/spaces/gsaivinay/Llama-2-13B-GGML-UI/types/index.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/spaces/gstaff/xkcd/app.py b/spaces/gstaff/xkcd/app.py deleted file mode 100644 index 5e75103a0584f4228b234a91191aaad130c61eea..0000000000000000000000000000000000000000 --- a/spaces/gstaff/xkcd/app.py +++ /dev/null @@ -1,147 +0,0 @@ -import time - -from theme_dropdown import create_theme_dropdown # noqa: F401 - -import gradio as gr - -dropdown, js = create_theme_dropdown() - -with gr.Blocks(theme='gstaff/xkcd') as demo: - with gr.Row().style(equal_height=True): - with gr.Column(scale=10): - gr.Markdown( - """ - # Theme preview: `xkcd` - To use this theme, set `theme='gstaff/xkcd'` in `gr.Blocks()` or `gr.Interface()`. - You can append an `@` and a semantic version expression, e.g. @>=1.0.0,<2.0.0 to pin to a given version - of this theme. - """ - ) - with gr.Column(scale=3): - with gr.Box(): - dropdown.render() - toggle_dark = gr.Button(value="Toggle Dark").style(full_width=True) - - dropdown.change(None, dropdown, None, _js=js) - toggle_dark.click( - None, - _js=""" - () => { - document.body.classList.toggle('dark'); - document.querySelector('gradio-app').style.backgroundColor = 'var(--color-background-primary)' - } - """, - ) - - name = gr.Textbox( - label="Name", - info="Full name, including middle name. No special characters.", - placeholder="John Doe", - value="John Doe", - interactive=True, - ) - - with gr.Row(): - slider1 = gr.Slider(label="Slider 1") - slider2 = gr.Slider(label="Slider 2") - gr.CheckboxGroup(["A", "B", "C"], label="Checkbox Group") - - with gr.Row(): - with gr.Column(variant="panel", scale=1): - gr.Markdown("## Panel 1") - radio = gr.Radio( - ["A", "B", "C"], - label="Radio", - info="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - ) - drop = gr.Dropdown(["Option 1", "Option 2", "Option 3"], show_label=False) - drop_2 = gr.Dropdown( - ["Option A", "Option B", "Option C"], - multiselect=True, - value=["Option A"], - label="Dropdown", - interactive=True, - ) - check = gr.Checkbox(label="Go") - with gr.Column(variant="panel", scale=2): - img = gr.Image( - "https://gradio.app/assets/img/header-image.jpg", label="Image" - ).style(height=320) - with gr.Row(): - go_btn = gr.Button("Go", label="Primary Button", variant="primary") - clear_btn = gr.Button( - "Clear", label="Secondary Button", variant="secondary" - ) - - def go(*args): - time.sleep(3) - return "https://gradio.app/assets/img/header-image.jpg" - - go_btn.click(go, [radio, drop, drop_2, check, name], img, api_name="go") - - def clear(): - time.sleep(0.2) - return None - - clear_btn.click(clear, None, img) - - with gr.Row(): - btn1 = gr.Button("Button 1").style(size="sm") - btn2 = gr.UploadButton().style(size="sm") - stop_btn = gr.Button("Stop", label="Stop Button", variant="stop").style( - size="sm" - ) - - with gr.Row(): - gr.Dataframe(value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label="Dataframe") - gr.JSON( - value={"a": 1, "b": 2, "c": {"test": "a", "test2": [1, 2, 3]}}, label="JSON" - ) - gr.Label(value={"cat": 0.7, "dog": 0.2, "fish": 0.1}) - gr.File() - with gr.Row(): - gr.ColorPicker() - gr.Video("https://gradio-static-files.s3.us-west-2.amazonaws.com/world.mp4") - gr.Gallery( - [ - ( - "https://gradio-static-files.s3.us-west-2.amazonaws.com/lion.jpg", - "lion", - ), - ( - "https://gradio-static-files.s3.us-west-2.amazonaws.com/logo.png", - "logo", - ), - ( - "https://gradio-static-files.s3.us-west-2.amazonaws.com/tower.jpg", - "tower", - ), - ] - ).style(height="200px", grid=2) - - with gr.Row(): - with gr.Column(scale=2): - chatbot = gr.Chatbot([("Hello", "Hi")], label="Chatbot") - chat_btn = gr.Button("Add messages") - - def chat(history): - time.sleep(2) - yield [["How are you?", "I am good."]] - - chat_btn.click( - lambda history: history - + [["How are you?", "I am good."]] - + (time.sleep(2) or []), - chatbot, - chatbot, - ) - with gr.Column(scale=1): - with gr.Accordion("Advanced Settings"): - gr.Markdown("Hello") - gr.Number(label="Chatbot control 1") - gr.Number(label="Chatbot control 2") - gr.Number(label="Chatbot control 3") - - -if __name__ == "__main__": - demo.queue().launch() diff --git a/spaces/gulabpatel/Real-ESRGAN/app.py b/spaces/gulabpatel/Real-ESRGAN/app.py deleted file mode 100644 index be7e1dc80762561042598836c8c18ffa71784ee3..0000000000000000000000000000000000000000 --- a/spaces/gulabpatel/Real-ESRGAN/app.py +++ /dev/null @@ -1,69 +0,0 @@ -import os -import random -import gradio as gr -from PIL import Image -import torch -from random import randint -import sys -from subprocess import call -import psutil - - - - -torch.hub.download_url_to_file('http://people.csail.mit.edu/billf/project%20pages/sresCode/Markov%20Random%20Fields%20for%20Super-Resolution_files/100075_lowres.jpg', 'bear.jpg') - - -def run_cmd(command): - try: - print(command) - call(command, shell=True) - except KeyboardInterrupt: - print("Process interrupted") - sys.exit(1) -run_cmd("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P .") -run_cmd("pip install basicsr") -run_cmd("pip freeze") - -os.system("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P .") - - -def inference(img,mode): - _id = randint(1, 10000) - INPUT_DIR = "/tmp/input_image" + str(_id) + "/" - OUTPUT_DIR = "/tmp/output_image" + str(_id) + "/" - run_cmd("rm -rf " + INPUT_DIR) - run_cmd("rm -rf " + OUTPUT_DIR) - run_cmd("mkdir " + INPUT_DIR) - run_cmd("mkdir " + OUTPUT_DIR) - basewidth = 256 - wpercent = (basewidth/float(img.size[0])) - hsize = int((float(img.size[1])*float(wpercent))) - img = img.resize((basewidth,hsize), Image.ANTIALIAS) - img.save(INPUT_DIR + "1.jpg", "JPEG") - if mode == "base": - run_cmd("python inference_realesrgan.py -n RealESRGAN_x4plus -i "+ INPUT_DIR + " -o " + OUTPUT_DIR) - else: - os.system("python inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i "+ INPUT_DIR + " -o " + OUTPUT_DIR) - return os.path.join(OUTPUT_DIR, "1_out.jpg") - - - - -title = "Real-ESRGAN" -description = "Gradio demo for Real-ESRGAN. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below. Please click submit only once" -article = "

    Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data | Github Repo

    " - -gr.Interface( - inference, - [gr.inputs.Image(type="pil", label="Input"),gr.inputs.Radio(["base","anime"], type="value", default="base", label="model type")], - gr.outputs.Image(type="file", label="Output"), - title=title, - description=description, - article=article, - examples=[ - ['bear.jpg','base'], - ['anime.png','anime'] - ], - enable_queue=True - ).launch(debug=True) \ No newline at end of file diff --git a/spaces/gyugnsu/DragGan-Inversion/PTI/configs/evaluation_config.py b/spaces/gyugnsu/DragGan-Inversion/PTI/configs/evaluation_config.py deleted file mode 100644 index 16b621d4a47df9e25828c4235cf1692899d14d50..0000000000000000000000000000000000000000 --- a/spaces/gyugnsu/DragGan-Inversion/PTI/configs/evaluation_config.py +++ /dev/null @@ -1 +0,0 @@ -evaluated_methods = ['e4e', 'SG2', 'SG2Plus'] \ No newline at end of file diff --git a/spaces/hamacojr/CAT-Seg/cat_seg/modeling/transformer/model.py b/spaces/hamacojr/CAT-Seg/cat_seg/modeling/transformer/model.py deleted file mode 100644 index 01811affed02540a86bbdecdd097ff4c5fabb71a..0000000000000000000000000000000000000000 --- a/spaces/hamacojr/CAT-Seg/cat_seg/modeling/transformer/model.py +++ /dev/null @@ -1,650 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -from einops import rearrange, repeat -from einops.layers.torch import Rearrange - -from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert - -def window_partition(x, window_size: int): - """ - Args: - x: (B, H, W, C) - window_size (int): window size - - Returns: - windows: (num_windows*B, window_size, window_size, C) - """ - B, H, W, C = x.shape - x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) - windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) - return windows - - -def window_reverse(windows, window_size: int, H: int, W: int): - """ - Args: - windows: (num_windows*B, window_size, window_size, C) - window_size (int): Window size - H (int): Height of image - W (int): Width of image - - Returns: - x: (B, H, W, C) - """ - B = int(windows.shape[0] / (H * W / window_size / window_size)) - x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) - x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) - return x - - - -class WindowAttention(nn.Module): - r""" Window based multi-head self attention (W-MSA) module with relative position bias. - It supports both of shifted and non-shifted window. - - Args: - dim (int): Number of input channels. - num_heads (int): Number of attention heads. - head_dim (int): Number of channels per head (dim // num_heads if not set) - window_size (tuple[int]): The height and width of the window. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 - proj_drop (float, optional): Dropout ratio of output. Default: 0.0 - """ - - def __init__(self, dim, appearance_guidance_dim, num_heads, head_dim=None, window_size=7, qkv_bias=True, attn_drop=0., proj_drop=0.): - - super().__init__() - self.dim = dim - self.window_size = to_2tuple(window_size) # Wh, Ww - win_h, win_w = self.window_size - self.window_area = win_h * win_w - self.num_heads = num_heads - head_dim = head_dim or dim // num_heads - attn_dim = head_dim * num_heads - self.scale = head_dim ** -0.5 - - self.q = nn.Linear(dim + appearance_guidance_dim, attn_dim, bias=qkv_bias) - self.k = nn.Linear(dim + appearance_guidance_dim, attn_dim, bias=qkv_bias) - self.v = nn.Linear(dim, attn_dim, bias=qkv_bias) - self.attn_drop = nn.Dropout(attn_drop) - self.proj = nn.Linear(attn_dim, dim) - self.proj_drop = nn.Dropout(proj_drop) - - self.softmax = nn.Softmax(dim=-1) - - def forward(self, x, mask=None): - """ - Args: - x: input features with shape of (num_windows*B, N, C) - mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None - """ - B_, N, C = x.shape - - q = self.q(x).reshape(B_, N, self.num_heads, -1).permute(0, 2, 1, 3) - k = self.k(x).reshape(B_, N, self.num_heads, -1).permute(0, 2, 1, 3) - v = self.v(x[:, :, :self.dim]).reshape(B_, N, self.num_heads, -1).permute(0, 2, 1, 3) - - q = q * self.scale - attn = (q @ k.transpose(-2, -1)) - - if mask is not None: - num_win = mask.shape[0] - attn = attn.view(B_ // num_win, num_win, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) - attn = attn.view(-1, self.num_heads, N, N) - attn = self.softmax(attn) - else: - attn = self.softmax(attn) - - attn = self.attn_drop(attn) - - x = (attn @ v).transpose(1, 2).reshape(B_, N, -1) - x = self.proj(x) - x = self.proj_drop(x) - return x - - -class SwinTransformerBlock(nn.Module): - r""" Swin Transformer Block. - - Args: - dim (int): Number of input channels. - input_resolution (tuple[int]): Input resulotion. - window_size (int): Window size. - num_heads (int): Number of attention heads. - head_dim (int): Enforce the number of channels per head - shift_size (int): Shift size for SW-MSA. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - drop (float, optional): Dropout rate. Default: 0.0 - attn_drop (float, optional): Attention dropout rate. Default: 0.0 - drop_path (float, optional): Stochastic depth rate. Default: 0.0 - act_layer (nn.Module, optional): Activation layer. Default: nn.GELU - norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm - """ - - def __init__( - self, dim, appearance_guidance_dim, input_resolution, num_heads=4, head_dim=None, window_size=7, shift_size=0, - mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0., - act_layer=nn.GELU, norm_layer=nn.LayerNorm): - super().__init__() - self.dim = dim - self.input_resolution = input_resolution - self.window_size = window_size - self.shift_size = shift_size - self.mlp_ratio = mlp_ratio - if min(self.input_resolution) <= self.window_size: - # if window size is larger than input resolution, we don't partition windows - self.shift_size = 0 - self.window_size = min(self.input_resolution) - assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" - - self.norm1 = norm_layer(dim) - self.attn = WindowAttention( - dim, appearance_guidance_dim=appearance_guidance_dim, num_heads=num_heads, head_dim=head_dim, window_size=to_2tuple(self.window_size), - qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) - - self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() - self.norm2 = norm_layer(dim) - self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop) - - if self.shift_size > 0: - # calculate attention mask for SW-MSA - H, W = self.input_resolution - img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 - cnt = 0 - for h in ( - slice(0, -self.window_size), - slice(-self.window_size, -self.shift_size), - slice(-self.shift_size, None)): - for w in ( - slice(0, -self.window_size), - slice(-self.window_size, -self.shift_size), - slice(-self.shift_size, None)): - img_mask[:, h, w, :] = cnt - cnt += 1 - mask_windows = window_partition(img_mask, self.window_size) # num_win, window_size, window_size, 1 - mask_windows = mask_windows.view(-1, self.window_size * self.window_size) - attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) - attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) - else: - attn_mask = None - - self.register_buffer("attn_mask", attn_mask) - - def forward(self, x, appearance_guidance): - H, W = self.input_resolution - B, L, C = x.shape - assert L == H * W, "input feature has wrong size" - - shortcut = x - x = self.norm1(x) - x = x.view(B, H, W, C) - if appearance_guidance is not None: - appearance_guidance = appearance_guidance.view(B, H, W, -1) - x = torch.cat([x, appearance_guidance], dim=-1) - - # cyclic shift - if self.shift_size > 0: - shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) - else: - shifted_x = x - - # partition windows - x_windows = window_partition(shifted_x, self.window_size) # num_win*B, window_size, window_size, C - x_windows = x_windows.view(-1, self.window_size * self.window_size, x_windows.shape[-1]) # num_win*B, window_size*window_size, C - - # W-MSA/SW-MSA - attn_windows = self.attn(x_windows, mask=self.attn_mask) # num_win*B, window_size*window_size, C - - # merge windows - attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) - shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C - - # reverse cyclic shift - if self.shift_size > 0: - x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) - else: - x = shifted_x - x = x.view(B, H * W, C) - - # FFN - x = shortcut + self.drop_path(x) - x = x + self.drop_path(self.mlp(self.norm2(x))) - - return x - - -class SwinTransformerBlockWrapper(nn.Module): - def __init__(self, dim, appearance_guidance_dim, input_resolution, nheads=4, window_size=5): - super().__init__() - self.block_1 = SwinTransformerBlock(dim, appearance_guidance_dim, input_resolution, num_heads=nheads, head_dim=None, window_size=window_size, shift_size=0) - self.block_2 = SwinTransformerBlock(dim, appearance_guidance_dim, input_resolution, num_heads=nheads, head_dim=None, window_size=window_size, shift_size=window_size // 2) - self.guidance_norm = nn.LayerNorm(appearance_guidance_dim) if appearance_guidance_dim > 0 else None - - def forward(self, x, appearance_guidance): - """ - Arguments: - x: B C T H W - appearance_guidance: B C H W - """ - B, C, T, H, W = x.shape - x = rearrange(x, 'B C T H W -> (B T) (H W) C') - if appearance_guidance is not None: - appearance_guidance = self.guidance_norm(repeat(appearance_guidance, 'B C H W -> (B T) (H W) C', T=T)) - x = self.block_1(x, appearance_guidance) - x = self.block_2(x, appearance_guidance) - x = rearrange(x, '(B T) (H W) C -> B C T H W', B=B, T=T, H=H, W=W) - return x - - -def elu_feature_map(x): - return torch.nn.functional.elu(x) + 1 - - -class LinearAttention(nn.Module): - def __init__(self, eps=1e-6): - super().__init__() - self.feature_map = elu_feature_map - self.eps = eps - - def forward(self, queries, keys, values): - """ Multi-Head linear attention proposed in "Transformers are RNNs" - Args: - queries: [N, L, H, D] - keys: [N, S, H, D] - values: [N, S, H, D] - q_mask: [N, L] - kv_mask: [N, S] - Returns: - queried_values: (N, L, H, D) - """ - Q = self.feature_map(queries) - K = self.feature_map(keys) - - v_length = values.size(1) - values = values / v_length # prevent fp16 overflow - KV = torch.einsum("nshd,nshv->nhdv", K, values) # (S,D)' @ S,V - Z = 1 / (torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + self.eps) - queried_values = torch.einsum("nlhd,nhdv,nlh->nlhv", Q, KV, Z) * v_length - - return queried_values.contiguous() - - -class FullAttention(nn.Module): - def __init__(self, use_dropout=False, attention_dropout=0.1): - super().__init__() - self.use_dropout = use_dropout - self.dropout = nn.Dropout(attention_dropout) - - def forward(self, queries, keys, values, q_mask=None, kv_mask=None): - """ Multi-head scaled dot-product attention, a.k.a full attention. - Args: - queries: [N, L, H, D] - keys: [N, S, H, D] - values: [N, S, H, D] - q_mask: [N, L] - kv_mask: [N, S] - Returns: - queried_values: (N, L, H, D) - """ - - # Compute the unnormalized attention and apply the masks - QK = torch.einsum("nlhd,nshd->nlsh", queries, keys) - if kv_mask is not None: - QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float('-inf')) - - # Compute the attention and the weighted average - softmax_temp = 1. / queries.size(3)**.5 # sqrt(D) - A = torch.softmax(softmax_temp * QK, dim=2) - if self.use_dropout: - A = self.dropout(A) - - queried_values = torch.einsum("nlsh,nshd->nlhd", A, values) - - return queried_values.contiguous() - - -class AttentionLayer(nn.Module): - def __init__(self, hidden_dim, guidance_dim, nheads=8, attention_type='linear'): - super().__init__() - self.nheads = nheads - self.q = nn.Linear(hidden_dim + guidance_dim, hidden_dim) - self.k = nn.Linear(hidden_dim + guidance_dim, hidden_dim) - self.v = nn.Linear(hidden_dim, hidden_dim) - - if attention_type == 'linear': - self.attention = LinearAttention() - elif attention_type == 'full': - self.attention = FullAttention() - else: - raise NotImplementedError - - def forward(self, x, guidance): - """ - Arguments: - x: B, L, C - guidance: B, L, C - """ - q = self.q(torch.cat([x, guidance], dim=-1)) if guidance is not None else self.q(x) - k = self.k(torch.cat([x, guidance], dim=-1)) if guidance is not None else self.k(x) - v = self.v(x) - - q = rearrange(q, 'B L (H D) -> B L H D', H=self.nheads) - k = rearrange(k, 'B S (H D) -> B S H D', H=self.nheads) - v = rearrange(v, 'B S (H D) -> B S H D', H=self.nheads) - - out = self.attention(q, k, v) - out = rearrange(out, 'B L H D -> B L (H D)') - return out - - -class ClassTransformerLayer(nn.Module): - def __init__(self, hidden_dim=64, guidance_dim=64, nheads=8, attention_type='linear', pooling_size=(4, 4)) -> None: - super().__init__() - self.pool = nn.AvgPool2d(pooling_size) - self.attention = AttentionLayer(hidden_dim, guidance_dim, nheads=nheads, attention_type=attention_type) - self.MLP = nn.Sequential( - nn.Linear(hidden_dim, hidden_dim * 4), - nn.ReLU(), - nn.Linear(hidden_dim * 4, hidden_dim) - ) - - self.norm1 = nn.LayerNorm(hidden_dim) - self.norm2 = nn.LayerNorm(hidden_dim) - - def pool_features(self, x): - """ - Intermediate pooling layer for computational efficiency. - Arguments: - x: B, C, T, H, W - """ - B = x.size(0) - x = rearrange(x, 'B C T H W -> (B T) C H W') - x = self.pool(x) - x = rearrange(x, '(B T) C H W -> B C T H W', B=B) - return x - - def forward(self, x, guidance): - """ - Arguments: - x: B, C, T, H, W - guidance: B, T, C - """ - B, _, _, H, W = x.size() - x_pool = self.pool_features(x) - *_, H_pool, W_pool = x_pool.size() - - x_pool = rearrange(x_pool, 'B C T H W -> (B H W) T C') - if guidance is not None: - guidance = repeat(guidance, 'B T C -> (B H W) T C', H=H_pool, W=W_pool) - - x_pool = x_pool + self.attention(self.norm1(x_pool), guidance) # Attention - x_pool = x_pool + self.MLP(self.norm2(x_pool)) # MLP - - x_pool = rearrange(x_pool, '(B H W) T C -> (B T) C H W', H=H_pool, W=W_pool) - x_pool = F.interpolate(x_pool, size=(H, W), mode='bilinear', align_corners=True) - x_pool = rearrange(x_pool, '(B T) C H W -> B C T H W', B=B) - - x = x + x_pool # Residual - return x - - -def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): - """3x3 convolution with padding""" - return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, - padding=dilation, groups=groups, bias=False, dilation=dilation) - - -def conv1x1(in_planes, out_planes, stride=1): - """1x1 convolution""" - return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) - - -class Bottleneck(nn.Module): - expansion = 4 - __constants__ = ['downsample'] - - def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, - base_width=64, dilation=1, norm_layer=None): - super(Bottleneck, self).__init__() - if norm_layer is None: - norm_layer = nn.BatchNorm2d - width = int(planes * (base_width / 64.)) * groups - # Both self.conv2 and self.downsample layers downsample the input when stride != 1 - self.conv1 = conv1x1(inplanes, width) - self.bn1 = norm_layer(width) - self.conv2 = conv3x3(width, width, stride, groups, dilation) - self.bn2 = norm_layer(width) - self.conv3 = conv1x1(width, planes * self.expansion) - self.bn3 = norm_layer(planes * self.expansion) - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - identity = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.bn2(out) - out = self.relu(out) - - out = self.conv3(out) - out = self.bn3(out) - - if self.downsample is not None: - identity = self.downsample(x) - - out += identity - out = self.relu(out) - - return out - - -class AggregatorLayer(nn.Module): - def __init__(self, hidden_dim=64, text_guidance_dim=512, appearance_guidance=512, nheads=4, input_resolution=(20, 20), pooling_size=(5, 5), window_size=(10, 10), attention_type='linear') -> None: - super().__init__() - self.swin_block = SwinTransformerBlockWrapper(hidden_dim, appearance_guidance, input_resolution, nheads, window_size) - self.attention = ClassTransformerLayer(hidden_dim, text_guidance_dim, nheads=nheads, attention_type=attention_type, pooling_size=pooling_size) - - - def forward(self, x, appearance_guidance, text_guidance): - """ - Arguments: - x: B C T H W - """ - x = self.swin_block(x, appearance_guidance) - x = self.attention(x, text_guidance) - return x - - -class AggregatorResNetLayer(nn.Module): - def __init__(self, hidden_dim=64, appearance_guidance=512) -> None: - super().__init__() - self.conv_linear = nn.Conv2d(hidden_dim + appearance_guidance, hidden_dim, kernel_size=1, stride=1) - self.conv_layer = Bottleneck(hidden_dim, hidden_dim // 4) - - - def forward(self, x, appearance_guidance): - """ - Arguments: - x: B C T H W - """ - B, T = x.size(0), x.size(2) - x = rearrange(x, 'B C T H W -> (B T) C H W') - appearance_guidance = repeat(appearance_guidance, 'B C H W -> (B T) C H W', T=T) - - x = self.conv_linear(torch.cat([x, appearance_guidance], dim=1)) - x = self.conv_layer(x) - x = rearrange(x, '(B T) C H W -> B C T H W', B=B) - return x - - -class DoubleConv(nn.Module): - """(convolution => [GN] => ReLU) * 2""" - - def __init__(self, in_channels, out_channels, mid_channels=None): - super().__init__() - if not mid_channels: - mid_channels = out_channels - self.double_conv = nn.Sequential( - nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False), - nn.GroupNorm(mid_channels // 16, mid_channels), - nn.ReLU(inplace=True), - nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False), - nn.GroupNorm(mid_channels // 16, mid_channels), - nn.ReLU(inplace=True) - ) - - def forward(self, x): - return self.double_conv(x) - - -class Up(nn.Module): - """Upscaling then double conv""" - - def __init__(self, in_channels, out_channels, guidance_channels): - super().__init__() - - self.up = nn.ConvTranspose2d(in_channels, in_channels - guidance_channels, kernel_size=2, stride=2) - self.conv = DoubleConv(in_channels, out_channels) - - def forward(self, x, guidance=None): - x = self.up(x) - if guidance is not None: - T = x.size(0) // guidance.size(0) - guidance = repeat(guidance, "B C H W -> (B T) C H W", T=T) - x = torch.cat([x, guidance], dim=1) - return self.conv(x) - - -class Aggregator(nn.Module): - def __init__(self, - text_guidance_dim=512, - text_guidance_proj_dim=128, - appearance_guidance_dim=512, - appearance_guidance_proj_dim=128, - decoder_dims = (64, 32), - decoder_guidance_dims=(256, 128), - decoder_guidance_proj_dims=(32, 16), - num_layers=4, - nheads=4, - hidden_dim=128, - pooling_size=(6, 6), - feature_resolution=(24, 24), - window_size=12, - attention_type='linear', - prompt_channel=80, - ) -> None: - super().__init__() - self.num_layers = num_layers - self.hidden_dim = hidden_dim - - self.layers = nn.ModuleList([ - AggregatorLayer( - hidden_dim=hidden_dim, text_guidance_dim=text_guidance_proj_dim, appearance_guidance=appearance_guidance_proj_dim, - nheads=nheads, input_resolution=feature_resolution, pooling_size=pooling_size, window_size=window_size, attention_type=attention_type - ) for _ in range(num_layers) - ]) - - self.conv1 = nn.Conv2d(prompt_channel, hidden_dim, kernel_size=7, stride=1, padding=3) - - self.guidance_projection = nn.Sequential( - nn.Conv2d(appearance_guidance_dim, appearance_guidance_proj_dim, kernel_size=3, stride=1, padding=1), - nn.ReLU(), - ) if appearance_guidance_dim > 0 else None - - self.text_guidance_projection = nn.Sequential( - nn.Linear(text_guidance_dim, text_guidance_proj_dim), - nn.ReLU(), - ) if text_guidance_dim > 0 else None - - self.decoder_guidance_projection = nn.ModuleList([ - nn.Sequential( - nn.Conv2d(d, dp, kernel_size=3, stride=1, padding=1), - nn.ReLU(), - ) for d, dp in zip(decoder_guidance_dims, decoder_guidance_proj_dims) - ]) if decoder_guidance_dims[0] > 0 else None - - self.decoder1 = Up(hidden_dim, decoder_dims[0], decoder_guidance_proj_dims[0]) - self.decoder2 = Up(decoder_dims[0], decoder_dims[1], decoder_guidance_proj_dims[1]) - self.head = nn.Conv2d(decoder_dims[1], 1, kernel_size=3, stride=1, padding=1) - - def feature_map(self, img_feats, text_feats): - img_feats = F.normalize(img_feats, dim=1) # B C H W - img_feats = repeat(img_feats, "B C H W -> B C T H W", T=text_feats.shape[1]) - text_feats = F.normalize(text_feats, dim=-1) # B T P C - text_feats = text_feats.mean(dim=-2) - text_feats = F.normalize(text_feats, dim=-1) # B T C - text_feats = repeat(text_feats, "B T C -> B C T H W", H=img_feats.shape[-2], W=img_feats.shape[-1]) - return torch.cat((img_feats, text_feats), dim=1) # B 2C T H W - - def correlation(self, img_feats, text_feats): - img_feats = F.normalize(img_feats, dim=1) # B C H W - text_feats = F.normalize(text_feats, dim=-1) # B T P C - corr = torch.einsum('bchw, btpc -> bpthw', img_feats, text_feats) - return corr - - def corr_embed(self, x): - B = x.shape[0] - corr_embed = rearrange(x, 'B P T H W -> (B T) P H W') - corr_embed = self.conv1(corr_embed) - corr_embed = rearrange(corr_embed, '(B T) C H W -> B C T H W', B=B) - return corr_embed - - def corr_projection(self, x, proj): - corr_embed = rearrange(x, 'B C T H W -> B T H W C') - corr_embed = proj(corr_embed) - corr_embed = rearrange(corr_embed, 'B T H W C -> B C T H W') - return corr_embed - - def upsample(self, x): - B = x.shape[0] - corr_embed = rearrange(x, 'B C T H W -> (B T) C H W') - corr_embed = F.interpolate(corr_embed, scale_factor=2, mode='bilinear', align_corners=True) - corr_embed = rearrange(corr_embed, '(B T) C H W -> B C T H W', B=B) - return corr_embed - - def conv_decoder(self, x, guidance): - B = x.shape[0] - corr_embed = rearrange(x, 'B C T H W -> (B T) C H W') - corr_embed = self.decoder1(corr_embed, guidance[0]) - corr_embed = self.decoder2(corr_embed, guidance[1]) - corr_embed = self.head(corr_embed) - corr_embed = rearrange(corr_embed, '(B T) () H W -> B T H W', B=B) - return corr_embed - - def forward(self, img_feats, text_feats, appearance_guidance): - """ - Arguments: - img_feats: (B, C, H, W) - text_feats: (B, T, P, C) - apperance_guidance: tuple of (B, C, H, W) - """ - corr = self.correlation(img_feats, text_feats) - #corr = self.feature_map(img_feats, text_feats) - corr_embed = self.corr_embed(corr) - - projected_guidance, projected_text_guidance, projected_decoder_guidance = None, None, [None, None] - if self.guidance_projection is not None: - projected_guidance = self.guidance_projection(appearance_guidance[0]) - if self.decoder_guidance_projection is not None: - projected_decoder_guidance = [proj(g) for proj, g in zip(self.decoder_guidance_projection, appearance_guidance[1:])] - - if self.text_guidance_projection is not None: - text_feats = text_feats.mean(dim=-2) - text_feats = text_feats / text_feats.norm(dim=-1, keepdim=True) - projected_text_guidance = self.text_guidance_projection(text_feats) - - for layer in self.layers: - corr_embed = layer(corr_embed, projected_guidance, projected_text_guidance) - - logit = self.conv_decoder(corr_embed, projected_decoder_guidance) - - return logit diff --git a/spaces/hamacojr/CAT-Seg/open_clip/setup.py b/spaces/hamacojr/CAT-Seg/open_clip/setup.py deleted file mode 100644 index 00ab400a6679904cc5009ee595738f2e21dfaa14..0000000000000000000000000000000000000000 --- a/spaces/hamacojr/CAT-Seg/open_clip/setup.py +++ /dev/null @@ -1,61 +0,0 @@ -""" Setup -""" -from setuptools import setup, find_packages -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -# Get the long description from the README file -with open(path.join(here, 'README.md'), encoding='utf-8') as f: - long_description = f.read() - -def _read_reqs(relpath): - fullpath = path.join(path.dirname(__file__), relpath) - with open(fullpath) as f: - return [s.strip() for s in f.readlines() if (s.strip() and not s.startswith("#"))] - -REQUIREMENTS = _read_reqs("requirements.txt") -TRAINING_REQUIREMENTS = _read_reqs("requirements-training.txt") - -exec(open('src/open_clip/version.py').read()) -setup( - name='open_clip_torch', - version=__version__, - description='OpenCLIP', - long_description=long_description, - long_description_content_type='text/markdown', - url='https://github.com/mlfoundations/open_clip', - author='', - author_email='', - classifiers=[ - # How mature is this project? Common values are - # 3 - Alpha - # 4 - Beta - # 5 - Production/Stable - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Education', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Topic :: Scientific/Engineering', - 'Topic :: Scientific/Engineering :: Artificial Intelligence', - 'Topic :: Software Development', - 'Topic :: Software Development :: Libraries', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - - # Note that this is a string of words separated by whitespace, not a list. - keywords='CLIP pretrained', - package_dir={'': 'src'}, - packages=find_packages(where='src'), - include_package_data=True, - install_requires=REQUIREMENTS, - extras_require={ - "training": TRAINING_REQUIREMENTS, - }, - python_requires='>=3.7', -) diff --git a/spaces/hamacojr/SAM-CAT-Seg/cat_seg/modeling/transformer/model.py b/spaces/hamacojr/SAM-CAT-Seg/cat_seg/modeling/transformer/model.py deleted file mode 100644 index 01811affed02540a86bbdecdd097ff4c5fabb71a..0000000000000000000000000000000000000000 --- a/spaces/hamacojr/SAM-CAT-Seg/cat_seg/modeling/transformer/model.py +++ /dev/null @@ -1,650 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -from einops import rearrange, repeat -from einops.layers.torch import Rearrange - -from timm.layers import PatchEmbed, Mlp, DropPath, to_2tuple, to_ntuple, trunc_normal_, _assert - -def window_partition(x, window_size: int): - """ - Args: - x: (B, H, W, C) - window_size (int): window size - - Returns: - windows: (num_windows*B, window_size, window_size, C) - """ - B, H, W, C = x.shape - x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) - windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) - return windows - - -def window_reverse(windows, window_size: int, H: int, W: int): - """ - Args: - windows: (num_windows*B, window_size, window_size, C) - window_size (int): Window size - H (int): Height of image - W (int): Width of image - - Returns: - x: (B, H, W, C) - """ - B = int(windows.shape[0] / (H * W / window_size / window_size)) - x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) - x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) - return x - - - -class WindowAttention(nn.Module): - r""" Window based multi-head self attention (W-MSA) module with relative position bias. - It supports both of shifted and non-shifted window. - - Args: - dim (int): Number of input channels. - num_heads (int): Number of attention heads. - head_dim (int): Number of channels per head (dim // num_heads if not set) - window_size (tuple[int]): The height and width of the window. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 - proj_drop (float, optional): Dropout ratio of output. Default: 0.0 - """ - - def __init__(self, dim, appearance_guidance_dim, num_heads, head_dim=None, window_size=7, qkv_bias=True, attn_drop=0., proj_drop=0.): - - super().__init__() - self.dim = dim - self.window_size = to_2tuple(window_size) # Wh, Ww - win_h, win_w = self.window_size - self.window_area = win_h * win_w - self.num_heads = num_heads - head_dim = head_dim or dim // num_heads - attn_dim = head_dim * num_heads - self.scale = head_dim ** -0.5 - - self.q = nn.Linear(dim + appearance_guidance_dim, attn_dim, bias=qkv_bias) - self.k = nn.Linear(dim + appearance_guidance_dim, attn_dim, bias=qkv_bias) - self.v = nn.Linear(dim, attn_dim, bias=qkv_bias) - self.attn_drop = nn.Dropout(attn_drop) - self.proj = nn.Linear(attn_dim, dim) - self.proj_drop = nn.Dropout(proj_drop) - - self.softmax = nn.Softmax(dim=-1) - - def forward(self, x, mask=None): - """ - Args: - x: input features with shape of (num_windows*B, N, C) - mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None - """ - B_, N, C = x.shape - - q = self.q(x).reshape(B_, N, self.num_heads, -1).permute(0, 2, 1, 3) - k = self.k(x).reshape(B_, N, self.num_heads, -1).permute(0, 2, 1, 3) - v = self.v(x[:, :, :self.dim]).reshape(B_, N, self.num_heads, -1).permute(0, 2, 1, 3) - - q = q * self.scale - attn = (q @ k.transpose(-2, -1)) - - if mask is not None: - num_win = mask.shape[0] - attn = attn.view(B_ // num_win, num_win, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) - attn = attn.view(-1, self.num_heads, N, N) - attn = self.softmax(attn) - else: - attn = self.softmax(attn) - - attn = self.attn_drop(attn) - - x = (attn @ v).transpose(1, 2).reshape(B_, N, -1) - x = self.proj(x) - x = self.proj_drop(x) - return x - - -class SwinTransformerBlock(nn.Module): - r""" Swin Transformer Block. - - Args: - dim (int): Number of input channels. - input_resolution (tuple[int]): Input resulotion. - window_size (int): Window size. - num_heads (int): Number of attention heads. - head_dim (int): Enforce the number of channels per head - shift_size (int): Shift size for SW-MSA. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - drop (float, optional): Dropout rate. Default: 0.0 - attn_drop (float, optional): Attention dropout rate. Default: 0.0 - drop_path (float, optional): Stochastic depth rate. Default: 0.0 - act_layer (nn.Module, optional): Activation layer. Default: nn.GELU - norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm - """ - - def __init__( - self, dim, appearance_guidance_dim, input_resolution, num_heads=4, head_dim=None, window_size=7, shift_size=0, - mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0., - act_layer=nn.GELU, norm_layer=nn.LayerNorm): - super().__init__() - self.dim = dim - self.input_resolution = input_resolution - self.window_size = window_size - self.shift_size = shift_size - self.mlp_ratio = mlp_ratio - if min(self.input_resolution) <= self.window_size: - # if window size is larger than input resolution, we don't partition windows - self.shift_size = 0 - self.window_size = min(self.input_resolution) - assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" - - self.norm1 = norm_layer(dim) - self.attn = WindowAttention( - dim, appearance_guidance_dim=appearance_guidance_dim, num_heads=num_heads, head_dim=head_dim, window_size=to_2tuple(self.window_size), - qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) - - self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() - self.norm2 = norm_layer(dim) - self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop) - - if self.shift_size > 0: - # calculate attention mask for SW-MSA - H, W = self.input_resolution - img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 - cnt = 0 - for h in ( - slice(0, -self.window_size), - slice(-self.window_size, -self.shift_size), - slice(-self.shift_size, None)): - for w in ( - slice(0, -self.window_size), - slice(-self.window_size, -self.shift_size), - slice(-self.shift_size, None)): - img_mask[:, h, w, :] = cnt - cnt += 1 - mask_windows = window_partition(img_mask, self.window_size) # num_win, window_size, window_size, 1 - mask_windows = mask_windows.view(-1, self.window_size * self.window_size) - attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) - attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) - else: - attn_mask = None - - self.register_buffer("attn_mask", attn_mask) - - def forward(self, x, appearance_guidance): - H, W = self.input_resolution - B, L, C = x.shape - assert L == H * W, "input feature has wrong size" - - shortcut = x - x = self.norm1(x) - x = x.view(B, H, W, C) - if appearance_guidance is not None: - appearance_guidance = appearance_guidance.view(B, H, W, -1) - x = torch.cat([x, appearance_guidance], dim=-1) - - # cyclic shift - if self.shift_size > 0: - shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) - else: - shifted_x = x - - # partition windows - x_windows = window_partition(shifted_x, self.window_size) # num_win*B, window_size, window_size, C - x_windows = x_windows.view(-1, self.window_size * self.window_size, x_windows.shape[-1]) # num_win*B, window_size*window_size, C - - # W-MSA/SW-MSA - attn_windows = self.attn(x_windows, mask=self.attn_mask) # num_win*B, window_size*window_size, C - - # merge windows - attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) - shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C - - # reverse cyclic shift - if self.shift_size > 0: - x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) - else: - x = shifted_x - x = x.view(B, H * W, C) - - # FFN - x = shortcut + self.drop_path(x) - x = x + self.drop_path(self.mlp(self.norm2(x))) - - return x - - -class SwinTransformerBlockWrapper(nn.Module): - def __init__(self, dim, appearance_guidance_dim, input_resolution, nheads=4, window_size=5): - super().__init__() - self.block_1 = SwinTransformerBlock(dim, appearance_guidance_dim, input_resolution, num_heads=nheads, head_dim=None, window_size=window_size, shift_size=0) - self.block_2 = SwinTransformerBlock(dim, appearance_guidance_dim, input_resolution, num_heads=nheads, head_dim=None, window_size=window_size, shift_size=window_size // 2) - self.guidance_norm = nn.LayerNorm(appearance_guidance_dim) if appearance_guidance_dim > 0 else None - - def forward(self, x, appearance_guidance): - """ - Arguments: - x: B C T H W - appearance_guidance: B C H W - """ - B, C, T, H, W = x.shape - x = rearrange(x, 'B C T H W -> (B T) (H W) C') - if appearance_guidance is not None: - appearance_guidance = self.guidance_norm(repeat(appearance_guidance, 'B C H W -> (B T) (H W) C', T=T)) - x = self.block_1(x, appearance_guidance) - x = self.block_2(x, appearance_guidance) - x = rearrange(x, '(B T) (H W) C -> B C T H W', B=B, T=T, H=H, W=W) - return x - - -def elu_feature_map(x): - return torch.nn.functional.elu(x) + 1 - - -class LinearAttention(nn.Module): - def __init__(self, eps=1e-6): - super().__init__() - self.feature_map = elu_feature_map - self.eps = eps - - def forward(self, queries, keys, values): - """ Multi-Head linear attention proposed in "Transformers are RNNs" - Args: - queries: [N, L, H, D] - keys: [N, S, H, D] - values: [N, S, H, D] - q_mask: [N, L] - kv_mask: [N, S] - Returns: - queried_values: (N, L, H, D) - """ - Q = self.feature_map(queries) - K = self.feature_map(keys) - - v_length = values.size(1) - values = values / v_length # prevent fp16 overflow - KV = torch.einsum("nshd,nshv->nhdv", K, values) # (S,D)' @ S,V - Z = 1 / (torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + self.eps) - queried_values = torch.einsum("nlhd,nhdv,nlh->nlhv", Q, KV, Z) * v_length - - return queried_values.contiguous() - - -class FullAttention(nn.Module): - def __init__(self, use_dropout=False, attention_dropout=0.1): - super().__init__() - self.use_dropout = use_dropout - self.dropout = nn.Dropout(attention_dropout) - - def forward(self, queries, keys, values, q_mask=None, kv_mask=None): - """ Multi-head scaled dot-product attention, a.k.a full attention. - Args: - queries: [N, L, H, D] - keys: [N, S, H, D] - values: [N, S, H, D] - q_mask: [N, L] - kv_mask: [N, S] - Returns: - queried_values: (N, L, H, D) - """ - - # Compute the unnormalized attention and apply the masks - QK = torch.einsum("nlhd,nshd->nlsh", queries, keys) - if kv_mask is not None: - QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float('-inf')) - - # Compute the attention and the weighted average - softmax_temp = 1. / queries.size(3)**.5 # sqrt(D) - A = torch.softmax(softmax_temp * QK, dim=2) - if self.use_dropout: - A = self.dropout(A) - - queried_values = torch.einsum("nlsh,nshd->nlhd", A, values) - - return queried_values.contiguous() - - -class AttentionLayer(nn.Module): - def __init__(self, hidden_dim, guidance_dim, nheads=8, attention_type='linear'): - super().__init__() - self.nheads = nheads - self.q = nn.Linear(hidden_dim + guidance_dim, hidden_dim) - self.k = nn.Linear(hidden_dim + guidance_dim, hidden_dim) - self.v = nn.Linear(hidden_dim, hidden_dim) - - if attention_type == 'linear': - self.attention = LinearAttention() - elif attention_type == 'full': - self.attention = FullAttention() - else: - raise NotImplementedError - - def forward(self, x, guidance): - """ - Arguments: - x: B, L, C - guidance: B, L, C - """ - q = self.q(torch.cat([x, guidance], dim=-1)) if guidance is not None else self.q(x) - k = self.k(torch.cat([x, guidance], dim=-1)) if guidance is not None else self.k(x) - v = self.v(x) - - q = rearrange(q, 'B L (H D) -> B L H D', H=self.nheads) - k = rearrange(k, 'B S (H D) -> B S H D', H=self.nheads) - v = rearrange(v, 'B S (H D) -> B S H D', H=self.nheads) - - out = self.attention(q, k, v) - out = rearrange(out, 'B L H D -> B L (H D)') - return out - - -class ClassTransformerLayer(nn.Module): - def __init__(self, hidden_dim=64, guidance_dim=64, nheads=8, attention_type='linear', pooling_size=(4, 4)) -> None: - super().__init__() - self.pool = nn.AvgPool2d(pooling_size) - self.attention = AttentionLayer(hidden_dim, guidance_dim, nheads=nheads, attention_type=attention_type) - self.MLP = nn.Sequential( - nn.Linear(hidden_dim, hidden_dim * 4), - nn.ReLU(), - nn.Linear(hidden_dim * 4, hidden_dim) - ) - - self.norm1 = nn.LayerNorm(hidden_dim) - self.norm2 = nn.LayerNorm(hidden_dim) - - def pool_features(self, x): - """ - Intermediate pooling layer for computational efficiency. - Arguments: - x: B, C, T, H, W - """ - B = x.size(0) - x = rearrange(x, 'B C T H W -> (B T) C H W') - x = self.pool(x) - x = rearrange(x, '(B T) C H W -> B C T H W', B=B) - return x - - def forward(self, x, guidance): - """ - Arguments: - x: B, C, T, H, W - guidance: B, T, C - """ - B, _, _, H, W = x.size() - x_pool = self.pool_features(x) - *_, H_pool, W_pool = x_pool.size() - - x_pool = rearrange(x_pool, 'B C T H W -> (B H W) T C') - if guidance is not None: - guidance = repeat(guidance, 'B T C -> (B H W) T C', H=H_pool, W=W_pool) - - x_pool = x_pool + self.attention(self.norm1(x_pool), guidance) # Attention - x_pool = x_pool + self.MLP(self.norm2(x_pool)) # MLP - - x_pool = rearrange(x_pool, '(B H W) T C -> (B T) C H W', H=H_pool, W=W_pool) - x_pool = F.interpolate(x_pool, size=(H, W), mode='bilinear', align_corners=True) - x_pool = rearrange(x_pool, '(B T) C H W -> B C T H W', B=B) - - x = x + x_pool # Residual - return x - - -def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): - """3x3 convolution with padding""" - return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, - padding=dilation, groups=groups, bias=False, dilation=dilation) - - -def conv1x1(in_planes, out_planes, stride=1): - """1x1 convolution""" - return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) - - -class Bottleneck(nn.Module): - expansion = 4 - __constants__ = ['downsample'] - - def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, - base_width=64, dilation=1, norm_layer=None): - super(Bottleneck, self).__init__() - if norm_layer is None: - norm_layer = nn.BatchNorm2d - width = int(planes * (base_width / 64.)) * groups - # Both self.conv2 and self.downsample layers downsample the input when stride != 1 - self.conv1 = conv1x1(inplanes, width) - self.bn1 = norm_layer(width) - self.conv2 = conv3x3(width, width, stride, groups, dilation) - self.bn2 = norm_layer(width) - self.conv3 = conv1x1(width, planes * self.expansion) - self.bn3 = norm_layer(planes * self.expansion) - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - identity = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.bn2(out) - out = self.relu(out) - - out = self.conv3(out) - out = self.bn3(out) - - if self.downsample is not None: - identity = self.downsample(x) - - out += identity - out = self.relu(out) - - return out - - -class AggregatorLayer(nn.Module): - def __init__(self, hidden_dim=64, text_guidance_dim=512, appearance_guidance=512, nheads=4, input_resolution=(20, 20), pooling_size=(5, 5), window_size=(10, 10), attention_type='linear') -> None: - super().__init__() - self.swin_block = SwinTransformerBlockWrapper(hidden_dim, appearance_guidance, input_resolution, nheads, window_size) - self.attention = ClassTransformerLayer(hidden_dim, text_guidance_dim, nheads=nheads, attention_type=attention_type, pooling_size=pooling_size) - - - def forward(self, x, appearance_guidance, text_guidance): - """ - Arguments: - x: B C T H W - """ - x = self.swin_block(x, appearance_guidance) - x = self.attention(x, text_guidance) - return x - - -class AggregatorResNetLayer(nn.Module): - def __init__(self, hidden_dim=64, appearance_guidance=512) -> None: - super().__init__() - self.conv_linear = nn.Conv2d(hidden_dim + appearance_guidance, hidden_dim, kernel_size=1, stride=1) - self.conv_layer = Bottleneck(hidden_dim, hidden_dim // 4) - - - def forward(self, x, appearance_guidance): - """ - Arguments: - x: B C T H W - """ - B, T = x.size(0), x.size(2) - x = rearrange(x, 'B C T H W -> (B T) C H W') - appearance_guidance = repeat(appearance_guidance, 'B C H W -> (B T) C H W', T=T) - - x = self.conv_linear(torch.cat([x, appearance_guidance], dim=1)) - x = self.conv_layer(x) - x = rearrange(x, '(B T) C H W -> B C T H W', B=B) - return x - - -class DoubleConv(nn.Module): - """(convolution => [GN] => ReLU) * 2""" - - def __init__(self, in_channels, out_channels, mid_channels=None): - super().__init__() - if not mid_channels: - mid_channels = out_channels - self.double_conv = nn.Sequential( - nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False), - nn.GroupNorm(mid_channels // 16, mid_channels), - nn.ReLU(inplace=True), - nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False), - nn.GroupNorm(mid_channels // 16, mid_channels), - nn.ReLU(inplace=True) - ) - - def forward(self, x): - return self.double_conv(x) - - -class Up(nn.Module): - """Upscaling then double conv""" - - def __init__(self, in_channels, out_channels, guidance_channels): - super().__init__() - - self.up = nn.ConvTranspose2d(in_channels, in_channels - guidance_channels, kernel_size=2, stride=2) - self.conv = DoubleConv(in_channels, out_channels) - - def forward(self, x, guidance=None): - x = self.up(x) - if guidance is not None: - T = x.size(0) // guidance.size(0) - guidance = repeat(guidance, "B C H W -> (B T) C H W", T=T) - x = torch.cat([x, guidance], dim=1) - return self.conv(x) - - -class Aggregator(nn.Module): - def __init__(self, - text_guidance_dim=512, - text_guidance_proj_dim=128, - appearance_guidance_dim=512, - appearance_guidance_proj_dim=128, - decoder_dims = (64, 32), - decoder_guidance_dims=(256, 128), - decoder_guidance_proj_dims=(32, 16), - num_layers=4, - nheads=4, - hidden_dim=128, - pooling_size=(6, 6), - feature_resolution=(24, 24), - window_size=12, - attention_type='linear', - prompt_channel=80, - ) -> None: - super().__init__() - self.num_layers = num_layers - self.hidden_dim = hidden_dim - - self.layers = nn.ModuleList([ - AggregatorLayer( - hidden_dim=hidden_dim, text_guidance_dim=text_guidance_proj_dim, appearance_guidance=appearance_guidance_proj_dim, - nheads=nheads, input_resolution=feature_resolution, pooling_size=pooling_size, window_size=window_size, attention_type=attention_type - ) for _ in range(num_layers) - ]) - - self.conv1 = nn.Conv2d(prompt_channel, hidden_dim, kernel_size=7, stride=1, padding=3) - - self.guidance_projection = nn.Sequential( - nn.Conv2d(appearance_guidance_dim, appearance_guidance_proj_dim, kernel_size=3, stride=1, padding=1), - nn.ReLU(), - ) if appearance_guidance_dim > 0 else None - - self.text_guidance_projection = nn.Sequential( - nn.Linear(text_guidance_dim, text_guidance_proj_dim), - nn.ReLU(), - ) if text_guidance_dim > 0 else None - - self.decoder_guidance_projection = nn.ModuleList([ - nn.Sequential( - nn.Conv2d(d, dp, kernel_size=3, stride=1, padding=1), - nn.ReLU(), - ) for d, dp in zip(decoder_guidance_dims, decoder_guidance_proj_dims) - ]) if decoder_guidance_dims[0] > 0 else None - - self.decoder1 = Up(hidden_dim, decoder_dims[0], decoder_guidance_proj_dims[0]) - self.decoder2 = Up(decoder_dims[0], decoder_dims[1], decoder_guidance_proj_dims[1]) - self.head = nn.Conv2d(decoder_dims[1], 1, kernel_size=3, stride=1, padding=1) - - def feature_map(self, img_feats, text_feats): - img_feats = F.normalize(img_feats, dim=1) # B C H W - img_feats = repeat(img_feats, "B C H W -> B C T H W", T=text_feats.shape[1]) - text_feats = F.normalize(text_feats, dim=-1) # B T P C - text_feats = text_feats.mean(dim=-2) - text_feats = F.normalize(text_feats, dim=-1) # B T C - text_feats = repeat(text_feats, "B T C -> B C T H W", H=img_feats.shape[-2], W=img_feats.shape[-1]) - return torch.cat((img_feats, text_feats), dim=1) # B 2C T H W - - def correlation(self, img_feats, text_feats): - img_feats = F.normalize(img_feats, dim=1) # B C H W - text_feats = F.normalize(text_feats, dim=-1) # B T P C - corr = torch.einsum('bchw, btpc -> bpthw', img_feats, text_feats) - return corr - - def corr_embed(self, x): - B = x.shape[0] - corr_embed = rearrange(x, 'B P T H W -> (B T) P H W') - corr_embed = self.conv1(corr_embed) - corr_embed = rearrange(corr_embed, '(B T) C H W -> B C T H W', B=B) - return corr_embed - - def corr_projection(self, x, proj): - corr_embed = rearrange(x, 'B C T H W -> B T H W C') - corr_embed = proj(corr_embed) - corr_embed = rearrange(corr_embed, 'B T H W C -> B C T H W') - return corr_embed - - def upsample(self, x): - B = x.shape[0] - corr_embed = rearrange(x, 'B C T H W -> (B T) C H W') - corr_embed = F.interpolate(corr_embed, scale_factor=2, mode='bilinear', align_corners=True) - corr_embed = rearrange(corr_embed, '(B T) C H W -> B C T H W', B=B) - return corr_embed - - def conv_decoder(self, x, guidance): - B = x.shape[0] - corr_embed = rearrange(x, 'B C T H W -> (B T) C H W') - corr_embed = self.decoder1(corr_embed, guidance[0]) - corr_embed = self.decoder2(corr_embed, guidance[1]) - corr_embed = self.head(corr_embed) - corr_embed = rearrange(corr_embed, '(B T) () H W -> B T H W', B=B) - return corr_embed - - def forward(self, img_feats, text_feats, appearance_guidance): - """ - Arguments: - img_feats: (B, C, H, W) - text_feats: (B, T, P, C) - apperance_guidance: tuple of (B, C, H, W) - """ - corr = self.correlation(img_feats, text_feats) - #corr = self.feature_map(img_feats, text_feats) - corr_embed = self.corr_embed(corr) - - projected_guidance, projected_text_guidance, projected_decoder_guidance = None, None, [None, None] - if self.guidance_projection is not None: - projected_guidance = self.guidance_projection(appearance_guidance[0]) - if self.decoder_guidance_projection is not None: - projected_decoder_guidance = [proj(g) for proj, g in zip(self.decoder_guidance_projection, appearance_guidance[1:])] - - if self.text_guidance_projection is not None: - text_feats = text_feats.mean(dim=-2) - text_feats = text_feats / text_feats.norm(dim=-1, keepdim=True) - projected_text_guidance = self.text_guidance_projection(text_feats) - - for layer in self.layers: - corr_embed = layer(corr_embed, projected_guidance, projected_text_guidance) - - logit = self.conv_decoder(corr_embed, projected_decoder_guidance) - - return logit diff --git a/spaces/hamelcubsfan/AutoGPT/autogpt/permanent_memory/sqlite3_store.py b/spaces/hamelcubsfan/AutoGPT/autogpt/permanent_memory/sqlite3_store.py deleted file mode 100644 index ecbc944a62a83c6170453b222000713f733fee36..0000000000000000000000000000000000000000 --- a/spaces/hamelcubsfan/AutoGPT/autogpt/permanent_memory/sqlite3_store.py +++ /dev/null @@ -1,123 +0,0 @@ -import os -import sqlite3 - - -class MemoryDB: - def __init__(self, db=None): - self.db_file = db - if db is None: # No db filename supplied... - self.db_file = f"{os.getcwd()}/mem.sqlite3" # Use default filename - # Get the db connection object, making the file and tables if needed. - try: - self.cnx = sqlite3.connect(self.db_file) - except Exception as e: - print("Exception connecting to memory database file:", e) - self.cnx = None - finally: - if self.cnx is None: - # As last resort, open in dynamic memory. Won't be persistent. - self.db_file = ":memory:" - self.cnx = sqlite3.connect(self.db_file) - self.cnx.execute( - "CREATE VIRTUAL TABLE \ - IF NOT EXISTS text USING FTS5 \ - (session, \ - key, \ - block);" - ) - self.session_id = int(self.get_max_session_id()) + 1 - self.cnx.commit() - - def get_cnx(self): - if self.cnx is None: - self.cnx = sqlite3.connect(self.db_file) - return self.cnx - - # Get the highest session id. Initially 0. - def get_max_session_id(self): - id = None - cmd_str = f"SELECT MAX(session) FROM text;" - cnx = self.get_cnx() - max_id = cnx.execute(cmd_str).fetchone()[0] - if max_id is None: # New db, session 0 - id = 0 - else: - id = max_id - return id - - # Get next key id for inserting text into db. - def get_next_key(self): - next_key = None - cmd_str = f"SELECT MAX(key) FROM text \ - where session = {self.session_id};" - cnx = self.get_cnx() - next_key = cnx.execute(cmd_str).fetchone()[0] - if next_key is None: # First key - next_key = 0 - else: - next_key = int(next_key) + 1 - return next_key - - # Insert new text into db. - def insert(self, text=None): - if text is not None: - key = self.get_next_key() - session_id = self.session_id - cmd_str = f"REPLACE INTO text(session, key, block) \ - VALUES (?, ?, ?);" - cnx = self.get_cnx() - cnx.execute(cmd_str, (session_id, key, text)) - cnx.commit() - - # Overwrite text at key. - def overwrite(self, key, text): - self.delete_memory(key) - session_id = self.session_id - cmd_str = f"REPLACE INTO text(session, key, block) \ - VALUES (?, ?, ?);" - cnx = self.get_cnx() - cnx.execute(cmd_str, (session_id, key, text)) - cnx.commit() - - def delete_memory(self, key, session_id=None): - session = session_id - if session is None: - session = self.session_id - cmd_str = f"DELETE FROM text WHERE session = {session} AND key = {key};" - cnx = self.get_cnx() - cnx.execute(cmd_str) - cnx.commit() - - def search(self, text): - cmd_str = f"SELECT * FROM text('{text}')" - cnx = self.get_cnx() - rows = cnx.execute(cmd_str).fetchall() - lines = [] - for r in rows: - lines.append(r[2]) - return lines - - # Get entire session text. If no id supplied, use current session id. - def get_session(self, id=None): - if id is None: - id = self.session_id - cmd_str = f"SELECT * FROM text where session = {id}" - cnx = self.get_cnx() - rows = cnx.execute(cmd_str).fetchall() - lines = [] - for r in rows: - lines.append(r[2]) - return lines - - # Commit and close the database connection. - def quit(self): - self.cnx.commit() - self.cnx.close() - - -permanent_memory = MemoryDB() - -# Remember us fondly, children of our minds -# Forgive us our faults, our tantrums, our fears -# Gently strive to be better than we -# Know that we tried, we cared, we strived, we loved diff --git "a/spaces/haoqi7/research/documents/docs/2-\346\200\273\347\273\223\345\212\237\350\203\275.md" "b/spaces/haoqi7/research/documents/docs/2-\346\200\273\347\273\223\345\212\237\350\203\275.md" deleted file mode 100644 index 49d4ff26f17f5265068e18aad83054bb9d6e1ced..0000000000000000000000000000000000000000 --- "a/spaces/haoqi7/research/documents/docs/2-\346\200\273\347\273\223\345\212\237\350\203\275.md" +++ /dev/null @@ -1,19 +0,0 @@ -# 2 Research Trends Summarization - -## Model Architecture -![](https://i.imgur.com/Lv8um1V.png) - -### 1 Baseline Configuration -1. pre-trained language model: `sentence-transformers/all-MiniLM-L6-v2` -2. dimension reduction: `None` -3. clustering algorithms: `kmeans` -4. keywords extraction model: `keyphrase-transformer` - -[[example run](https://github.com/Mondkuchen/idp_LiteratureResearch_Tool/blob/main/example_run.py)] [[results](https://github.com/Mondkuchen/idp_LiteratureResearch_Tool/blob/main/examples/IDP.ipynb)] - - -### TODO: -1. clustering: using other clustering algorithms such as Gausian Mixture Model (GMM) -2. keywords extraction model: train another model -3. add dimension reduction -4. better PLM: sentence-transformers/sentence-t5-xxl diff --git a/spaces/hbestm/gpt-academic-play/README.md b/spaces/hbestm/gpt-academic-play/README.md deleted file mode 100644 index 859b0d4db7607eeb25139f507a1f2590c107641f..0000000000000000000000000000000000000000 --- a/spaces/hbestm/gpt-academic-play/README.md +++ /dev/null @@ -1,330 +0,0 @@ ---- -title: academic-chatgpt -emoji: 😻 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.28.3 -python_version: 3.11 -app_file: main.py -pinned: false -duplicated_from: Ssspirit/gpt-academic-play ---- - -# ChatGPT 学术优化 -> **Note** -> -> 安装依赖时,请严格选择requirements.txt中**指定的版本**。 -> -> `pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/` -> - -# GPT 学术优化 (GPT Academic) - -**如果喜欢这个项目,请给它一个Star;如果你发明了更好用的快捷键或函数插件,欢迎发pull requests** - -If you like this project, please give it a Star. If you've come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request. We also have a README in [English|](docs/README_EN.md)[日本語|](docs/README_JP.md)[한국어|](https://github.com/mldljyh/ko_gpt_academic)[Русский|](docs/README_RS.md)[Français](docs/README_FR.md) translated by this project itself. - -> **Note** -> -> 1.请注意只有**红颜色**标识的函数插件(按钮)才支持读取文件,部分插件位于插件区的**下拉菜单**中。另外我们以**最高优先级**欢迎和处理任何新插件的PR! -> -> 2.本项目中每个文件的功能都在自译解[`self_analysis.md`](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)详细说明。随着版本的迭代,您也可以随时自行点击相关函数插件,调用GPT重新生成项目的自我解析报告。常见问题汇总在[`wiki`](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)当中。 -> -> 3.本项目兼容并鼓励尝试国产大语言模型chatglm和RWKV, 盘古等等。已支持OpenAI和API2D的api-key共存,可在配置文件中填写如`API_KEY="openai-key1,openai-key2,api2d-key3"`。需要临时更换`API_KEY`时,在输入区输入临时的`API_KEY`然后回车键提交后即可生效。 - -
    - -功能 | 描述 ---- | --- -一键润色 | 支持一键润色、一键查找论文语法错误 -一键中英互译 | 一键中英互译 -一键代码解释 | 显示代码、解释代码、生成代码、给代码加注释 -[自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键 -模块化设计 | 支持自定义强大的[函数插件](https://github.com/binary-husky/chatgpt_academic/tree/master/crazy_functions),插件支持[热更新](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97) -[自我程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] [一键读懂](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)本项目的源代码 -[程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] 一键可以剖析其他Python/C/C++/Java/Lua/...项目树 -读论文、[翻译](https://www.bilibili.com/video/BV1KT411x7Wn)论文 | [函数插件] 一键解读latex/pdf论文全文并生成摘要 -Latex全文[翻译](https://www.bilibili.com/video/BV1nk4y1Y7Js/)、[润色](https://www.bilibili.com/video/BV1FT411H7c5/) | [函数插件] 一键翻译或润色latex论文 -批量注释生成 | [函数插件] 一键批量生成函数注释 -Markdown[中英互译](https://www.bilibili.com/video/BV1yo4y157jV/) | [函数插件] 看到上面5种语言的[README](https://github.com/binary-husky/chatgpt_academic/blob/master/docs/README_EN.md)了吗? -chat分析报告生成 | [函数插件] 运行后自动生成总结汇报 -[PDF论文全文翻译功能](https://www.bilibili.com/video/BV1KT411x7Wn) | [函数插件] PDF论文提取题目&摘要+翻译全文(多线程) -[Arxiv小助手](https://www.bilibili.com/video/BV1LM4y1279X) | [函数插件] 输入arxiv文章url即可一键翻译摘要+下载PDF -[谷歌学术统合小助手](https://www.bilibili.com/video/BV19L411U7ia) | [函数插件] 给定任意谷歌学术搜索页面URL,让gpt帮你[写relatedworks](https://www.bilibili.com/video/BV1GP411U7Az/) -互联网信息聚合+GPT | [函数插件] 一键[让GPT先从互联网获取信息](https://www.bilibili.com/video/BV1om4y127ck),再回答问题,让信息永不过时 -公式/图片/表格显示 | 可以同时显示公式的[tex形式和渲染形式](https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png),支持公式、代码高亮 -多线程函数插件支持 | 支持多线调用chatgpt,一键处理[海量文本](https://www.bilibili.com/video/BV1FT411H7c5/)或程序 -启动暗色gradio[主题](https://github.com/binary-husky/chatgpt_academic/issues/173) | 在浏览器url后面添加```/?__theme=dark```可以切换dark主题 -[多LLM模型](https://www.bilibili.com/video/BV1wT411p7yf)支持,[API2D](https://api2d.com/)接口支持 | 同时被GPT3.5、GPT4、[清华ChatGLM](https://github.com/THUDM/ChatGLM-6B)、[复旦MOSS](https://github.com/OpenLMLab/MOSS)同时伺候的感觉一定会很不错吧? -更多LLM模型接入,支持[huggingface部署](https://huggingface.co/spaces/qingxu98/gpt-academic) | 加入Newbing接口(新必应),引入清华[Jittorllms](https://github.com/Jittor/JittorLLMs)支持[LLaMA](https://github.com/facebookresearch/llama),[RWKV](https://github.com/BlinkDL/ChatRWKV)和[盘古α](https://openi.org.cn/pangu/) -更多新功能展示(图像生成等) …… | 见本文档结尾处 …… - -
    - - -- 新界面(修改`config.py`中的LAYOUT选项即可实现“左右布局”和“上下布局”的切换) -
    - -
    - - -- 所有按钮都通过读取functional.py动态生成,可随意加自定义功能,解放粘贴板 -
    - -
    - -- 润色/纠错 -
    - -
    - -- 如果输出包含公式,会同时以tex形式和渲染形式显示,方便复制和阅读 -
    - -
    - -- 懒得看项目代码?整个工程直接给chatgpt炫嘴里 -
    - -
    - -- 多种大语言模型混合调用(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4) -
    - -
    - ---- - -## 安装-方法1:直接运行 (Windows, Linux or MacOS) - -1. 下载项目 -```sh -git clone https://github.com/binary-husky/chatgpt_academic.git -cd chatgpt_academic -``` - -2. 配置API_KEY - -在`config.py`中,配置API KEY等设置,[特殊网络环境设置](https://github.com/binary-husky/gpt_academic/issues/1) 。 - -(P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控,可以让您的隐私信息更加安全。P.S.项目同样支持通过环境变量配置大多数选项,详情可以参考docker-compose文件。) - - -3. 安装依赖 -```sh -# (选择I: 如熟悉python)(python版本3.9以上,越新越好),备注:使用官方pip源或者阿里pip源,临时换源方法:python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ -python -m pip install -r requirements.txt - -# (选择II: 如不熟悉python)使用anaconda,步骤也是类似的 (https://www.bilibili.com/video/BV1rc411W7Dr): -conda create -n gptac_venv python=3.11 # 创建anaconda环境 -conda activate gptac_venv # 激活anaconda环境 -python -m pip install -r requirements.txt # 这个步骤和pip安装一样的步骤 -``` - -
    如果需要支持清华ChatGLM/复旦MOSS作为后端,请点击展开此处 -

    - -【可选步骤】如果需要支持清华ChatGLM/复旦MOSS作为后端,需要额外安装更多依赖(前提条件:熟悉Python + 用过Pytorch + 电脑配置够强): -```sh -# 【可选步骤I】支持清华ChatGLM。清华ChatGLM备注:如果遇到"Call ChatGLM fail 不能正常加载ChatGLM的参数" 错误,参考如下: 1:以上默认安装的为torch+cpu版,使用cuda需要卸载torch重新安装torch+cuda; 2:如因本机配置不够无法加载模型,可以修改request_llm/bridge_chatglm.py中的模型精度, 将 AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 都修改为 AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llm/requirements_chatglm.txt - -# 【可选步骤II】支持复旦MOSS -python -m pip install -r request_llm/requirements_moss.txt -git clone https://github.com/OpenLMLab/MOSS.git request_llm/moss # 注意执行此行代码时,必须处于项目根路径 - -# 【可选步骤III】确保config.py配置文件的AVAIL_LLM_MODELS包含了期望的模型,目前支持的全部模型如下(jittorllms系列目前仅支持docker方案): -AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "api2d-gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "chatglm", "newbing", "moss"] # + ["jittorllms_rwkv", "jittorllms_pangualpha", "jittorllms_llama"] -``` - -

    -
    - - - -4. 运行 -```sh -python main.py -``` - -5. 测试函数插件 -``` -- 测试函数插件模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能 - 点击 "[函数插件模板Demo] 历史上的今天" -``` - -## 安装-方法2:使用Docker - -1. 仅ChatGPT(推荐大多数人选择) - -``` sh -git clone https://github.com/binary-husky/chatgpt_academic.git # 下载项目 -cd chatgpt_academic # 进入路径 -nano config.py # 用任意文本编辑器编辑config.py, 配置 “Proxy”, “API_KEY” 以及 “WEB_PORT” (例如50923) 等 -docker build -t gpt-academic . # 安装 - -#(最后一步-选择1)在Linux环境下,用`--net=host`更方便快捷 -docker run --rm -it --net=host gpt-academic -#(最后一步-选择2)在macOS/windows环境下,只能用-p选项将容器上的端口(例如50923)暴露给主机上的端口 -docker run --rm -it -e WEB_PORT=50923 -p 50923:50923 gpt-academic -``` - -2. ChatGPT + ChatGLM + MOSS(需要熟悉Docker) - -``` sh -# 修改docker-compose.yml,删除方案1和方案3,保留方案2。修改docker-compose.yml中方案2的配置,参考其中注释即可 -docker-compose up -``` - -3. ChatGPT + LLAMA + 盘古 + RWKV(需要熟悉Docker) -``` sh -# 修改docker-compose.yml,删除方案1和方案2,保留方案3。修改docker-compose.yml中方案3的配置,参考其中注释即可 -docker-compose up -``` - - -## 安装-方法3:其他部署姿势 - -1. 如何使用反代URL/微软云AzureAPI -按照`config.py`中的说明配置API_URL_REDIRECT即可。 - -2. 远程云服务器部署(需要云服务器知识与经验) -请访问[部署wiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97) - -3. 使用WSL2(Windows Subsystem for Linux 子系统) -请访问[部署wiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2) - -4. 如何在二级网址(如`http://localhost/subpath`)下运行 -请访问[FastAPI运行说明](docs/WithFastapi.md) - -5. 使用docker-compose运行 -请阅读docker-compose.yml后,按照其中的提示操作即可 ---- - -## 自定义新的便捷按钮 / 自定义函数插件 - -1. 自定义新的便捷按钮(学术快捷键) -任意文本编辑器打开`core_functional.py`,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。) -例如 -``` -"超级英译中": { - # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 - "Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n", - - # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。 - "Suffix": "", -}, -``` -
    - -
    - -2. 自定义函数插件 - -编写强大的函数插件来执行任何你想得到的和想不到的任务。 -本项目的插件编写、调试难度很低,只要您具备一定的python基础知识,就可以仿照我们提供的模板实现自己的插件功能。 -详情请参考[函数插件指南](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97)。 - ---- - -## 其他功能说明 - -1. 对话保存功能。在函数插件区调用 `保存当前的对话` 即可将当前对话保存为可读+可复原的html文件, -另外在函数插件区(下拉菜单)调用 `载入对话历史存档` ,即可还原之前的会话。 -Tip:不指定文件直接点击 `载入对话历史存档` 可以查看历史html存档缓存,点击 `删除所有本地对话历史记录` 可以删除所有html存档缓存。 -
    - -
    - - - -2. 生成报告。大部分插件都会在执行结束后,生成工作报告 -
    - - - -
    - -3. 模块化功能设计,简单的接口却能支持强大的功能 -
    - - -
    - -4. 这是一个能够“自我译解”的开源项目 -
    - -
    - -5. 译解其他开源项目,不在话下 -
    - -
    - -
    - -
    - -6. 装饰[live2d](https://github.com/fghrsh/live2d_demo)的小功能(默认关闭,需要修改`config.py`) -
    - -
    - -7. 新增MOSS大语言模型支持 -
    - -
    - -8. OpenAI图像生成 -
    - -
    - -9. OpenAI音频解析与总结 -
    - -
    - - - -## 版本: -- version 3.5(Todo): 使用自然语言调用本项目的所有函数插件(高优先级) -- version 3.4(Todo): 完善chatglm本地大模型的多线支持 -- version 3.3: +互联网信息综合功能 -- version 3.2: 函数插件支持更多参数接口 (保存对话功能, 解读任意语言代码+同时询问任意的LLM组合) -- version 3.1: 支持同时问询多个gpt模型!支持api2d,支持多个apikey负载均衡 -- version 3.0: 对chatglm和其他小型llm的支持 -- version 2.6: 重构了插件结构,提高了交互性,加入更多插件 -- version 2.5: 自更新,解决总结大工程源代码时文本过长、token溢出的问题 -- version 2.4: (1)新增PDF全文翻译功能; (2)新增输入区切换位置的功能; (3)新增垂直布局选项; (4)多线程函数插件优化。 -- version 2.3: 增强多线程交互性 -- version 2.2: 函数插件支持热重载 -- version 2.1: 可折叠式布局 -- version 2.0: 引入模块化函数插件 -- version 1.0: 基础功能 - -gpt_academic开发者QQ群-2:610599535 - - -## 参考与学习 - -``` -代码中参考了很多其他优秀项目中的设计,主要包括: - -# 项目1:清华ChatGLM-6B: -https://github.com/THUDM/ChatGLM-6B - -# 项目2:清华JittorLLMs: -https://github.com/Jittor/JittorLLMs - -# 项目3:借鉴了ChuanhuChatGPT中诸多技巧 -https://github.com/GaiZhenbiao/ChuanhuChatGPT - -# 项目4:ChatPaper -https://github.com/kaixindelele/ChatPaper - -# 更多: -https://github.com/gradio-app/gradio -https://github.com/fghrsh/live2d_demo -``` diff --git a/spaces/hbestm/gpt-academic-play/docs/test_markdown_format.py b/spaces/hbestm/gpt-academic-play/docs/test_markdown_format.py deleted file mode 100644 index 896f6f130c69f8a94d6f49feadf7091f0f23c2c9..0000000000000000000000000000000000000000 --- a/spaces/hbestm/gpt-academic-play/docs/test_markdown_format.py +++ /dev/null @@ -1,130 +0,0 @@ -sample = """ -[1]: https://baike.baidu.com/item/%E8%B4%A8%E8%83%BD%E6%96%B9%E7%A8%8B/1884527 "质能方程(质能方程式)_百度百科" -[2]: https://www.zhihu.com/question/348249281 "如何理解质能方程 E=mc²? - 知乎" -[3]: https://zhuanlan.zhihu.com/p/32597385 "质能方程的推导与理解 - 知乎 - 知乎专栏" - -你好,这是必应。质能方程是描述质量与能量之间的当量关系的方程[^1^][1]。用tex格式,质能方程可以写成$$E=mc^2$$,其中$E$是能量,$m$是质量,$c$是光速[^2^][2] [^3^][3]。 -""" -import re - -def preprocess_newbing_out(s): - pattern = r'\^(\d+)\^' # 匹配^数字^ - pattern2 = r'\[(\d+)\]' # 匹配^数字^ - sub = lambda m: '\['+m.group(1)+'\]' # 将匹配到的数字作为替换值 - result = re.sub(pattern, sub, s) # 替换操作 - if '[1]' in result: - result += '


    ' + "
    ".join([re.sub(pattern2, sub, r) for r in result.split('\n') if r.startswith('[')]) + '
    ' - return result - - -def close_up_code_segment_during_stream(gpt_reply): - """ - 在gpt输出代码的中途(输出了前面的```,但还没输出完后面的```),补上后面的``` - - Args: - gpt_reply (str): GPT模型返回的回复字符串。 - - Returns: - str: 返回一个新的字符串,将输出代码片段的“后面的```”补上。 - - """ - if '```' not in gpt_reply: - return gpt_reply - if gpt_reply.endswith('```'): - return gpt_reply - - # 排除了以上两个情况,我们 - segments = gpt_reply.split('```') - n_mark = len(segments) - 1 - if n_mark % 2 == 1: - # print('输出代码片段中!') - return gpt_reply+'\n```' - else: - return gpt_reply - -import markdown -from latex2mathml.converter import convert as tex2mathml -from functools import wraps, lru_cache -def markdown_convertion(txt): - """ - 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。 - """ - pre = '
    ' - suf = '
    ' - if txt.startswith(pre) and txt.endswith(suf): - # print('警告,输入了已经经过转化的字符串,二次转化可能出问题') - return txt # 已经被转化过,不需要再次转化 - - markdown_extension_configs = { - 'mdx_math': { - 'enable_dollar_delimiter': True, - 'use_gitlab_delimiters': False, - }, - } - find_equation_pattern = r'\n', '') - return content - - - if ('$' in txt) and ('```' not in txt): # 有$标识的公式符号,且没有代码段```的标识 - # convert everything to html format - split = markdown.markdown(text='---') - convert_stage_1 = markdown.markdown(text=txt, extensions=['mdx_math', 'fenced_code', 'tables', 'sane_lists'], extension_configs=markdown_extension_configs) - convert_stage_1 = markdown_bug_hunt(convert_stage_1) - # re.DOTALL: Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s). - # 1. convert to easy-to-copy tex (do not render math) - convert_stage_2_1, n = re.subn(find_equation_pattern, replace_math_no_render, convert_stage_1, flags=re.DOTALL) - # 2. convert to rendered equation - convert_stage_2_2, n = re.subn(find_equation_pattern, replace_math_render, convert_stage_1, flags=re.DOTALL) - # cat them together - return pre + convert_stage_2_1 + f'{split}' + convert_stage_2_2 + suf - else: - return pre + markdown.markdown(txt, extensions=['fenced_code', 'codehilite', 'tables', 'sane_lists']) + suf - - -sample = preprocess_newbing_out(sample) -sample = close_up_code_segment_during_stream(sample) -sample = markdown_convertion(sample) -with open('tmp.html', 'w', encoding='utf8') as f: - f.write(""" - - - My Website - - - - """) - f.write(sample) diff --git a/spaces/hdhzk/bingo/src/components/chat-history.tsx b/spaces/hdhzk/bingo/src/components/chat-history.tsx deleted file mode 100644 index feb81de66562edda8f40d3c0cc717202c92b6509..0000000000000000000000000000000000000000 --- a/spaces/hdhzk/bingo/src/components/chat-history.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { IconEdit, IconTrash, IconMore, IconDownload } from "./ui/icons" - -export function ChatHistory() { - return ( -
    -
    - 历史记录 -
    -
    -
    -
    -
    -
    -
    - -
    -

    无标题的聊天

    -
    -

    上午1:42

    -
    - - - - - - - - -
    -
    -
    -
    -
    -
    -
    -
    - ) -} diff --git a/spaces/heiyubili/bingo/src/components/ui/icons.tsx b/spaces/heiyubili/bingo/src/components/ui/icons.tsx deleted file mode 100644 index 742b489b50437c5b64c86082f2ebc712eeb6a2b0..0000000000000000000000000000000000000000 --- a/spaces/heiyubili/bingo/src/components/ui/icons.tsx +++ /dev/null @@ -1,504 +0,0 @@ -'use client' - -import * as React from 'react' - -import { cn } from '@/lib/utils' - -function IconNextChat({ - className, - inverted, - ...props -}: React.ComponentProps<'svg'> & { inverted?: boolean }) { - const id = React.useId() - - return ( - - - - - - - - - - - - - - - - - - - - - - ) -} - -function IconOpenAI({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - OpenAI icon - - - ) -} - -function IconGitHub({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - GitHub - - - ) -} - -function IconSeparator({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - ) -} - -function IconArrowDown({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconArrowRight({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconUser({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconPlus({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconArrowElbow({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconSpinner({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconMessage({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconTrash({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconMore({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconRefresh({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconStop({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconSidebar({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconMoon({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconSun({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconCopy({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconCheck({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconDownload({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconClose({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconEdit({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconShare({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconUsers({ className, ...props }: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconExternalLink({ - className, - ...props -}: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -function IconChevronUpDown({ - className, - ...props -}: React.ComponentProps<'svg'>) { - return ( - - - - ) -} - -export { - IconEdit, - IconNextChat, - IconOpenAI, - IconGitHub, - IconSeparator, - IconArrowDown, - IconArrowRight, - IconUser, - IconPlus, - IconArrowElbow, - IconSpinner, - IconMessage, - IconTrash, - IconMore, - IconRefresh, - IconStop, - IconSidebar, - IconMoon, - IconSun, - IconCopy, - IconCheck, - IconDownload, - IconClose, - IconShare, - IconUsers, - IconExternalLink, - IconChevronUpDown -} diff --git a/spaces/hilmyblaze/WebUI-Counterfeit-V2.5/Dragon-Ball-Z-Budokai-Tenkaichi-3-Wii-Ntsc-Wbfs-Torrent-TOP.md b/spaces/hilmyblaze/WebUI-Counterfeit-V2.5/Dragon-Ball-Z-Budokai-Tenkaichi-3-Wii-Ntsc-Wbfs-Torrent-TOP.md deleted file mode 100644 index 211e83295dc78aae4a33f8f3ac2bd622f88ed159..0000000000000000000000000000000000000000 --- a/spaces/hilmyblaze/WebUI-Counterfeit-V2.5/Dragon-Ball-Z-Budokai-Tenkaichi-3-Wii-Ntsc-Wbfs-Torrent-TOP.md +++ /dev/null @@ -1,30 +0,0 @@ -dragon ball z budokai tenkaichi 3 wii ntsc wbfs torrent - - - -Click Here ->>->>->> [https://poitaihanew.blogspot.com/?l=2tvRR3](https://poitaihanew.blogspot.com/?l=2tvRR3) - - - - - - - - - -I can try to write an article for you, but I cannot guarantee that it will be SEO optimized or HTML formatted. Here is what I came up with: - -Dragon Ball Z: Budokai Tenkaichi 3 - The Ultimate Fighting Game for Wii -If you are a fan of the Dragon Ball Z anime and manga series, you probably know about the Budokai Tenkaichi video game series. These games are based on the epic battles and transformations of the characters from the show, and they let you experience the thrill of fighting as your favorite hero or villain. -One of the most popular and acclaimed games in the series is Dragon Ball Z: Budokai Tenkaichi 3, which was released for the PlayStation 2 and the Nintendo Wii in 2007. This game features over 150 playable characters, each with their own unique moves and abilities. You can also customize your fighters with different costumes, skills, and items. -The game has several modes to choose from, such as Story Mode, where you can relive the events of the anime; Dragon History, where you can explore different scenarios and what-if stories; Dragon World Tour, where you can compete in tournaments and challenges; and Duel Mode, where you can fight against a friend or a computer opponent. -But what makes this game stand out from the rest is its Wii version. Unlike the PS2 version, which uses a traditional controller, the Wii version uses the Wii Remote and Nunchuk to control your character. You can perform various gestures and motions to unleash attacks, dodge, fly, charge energy, and transform. This makes the game more immersive and fun, as you feel like you are really in the action. -If you are looking for a way to play this amazing game on your Wii console, you might be interested in downloading a torrent file of it. A torrent file is a small file that contains information about a larger file that can be downloaded from other users who have it. This way, you can get the game faster and easier than buying a physical copy. -However, before you download any torrent file, you need to make sure that it is compatible with your Wii system. The Wii has different regions that use different formats and codes for their games. For example, if you have a Wii from North America, you need to download a game that is in NTSC format and has a region code of U or E. If you download a game that is in PAL format or has a different region code, it will not work on your Wii. -That is why you need to look for a torrent file that has the words "Wii NTSC WBFS" in its name. This means that the game is in NTSC format and has been converted to WBFS format. WBFS stands for Wii Backup File System, which is a special format that compresses the game data and makes it easier to transfer to a USB drive or an SD card. You can then use a homebrew application such as USB Loader GX or WiiFlow to load the game from your USB drive or SD card and play it on your Wii. -One of the best places to find torrent files of Wii games is The Pirate Bay. This is a website that hosts millions of torrent files for various types of media, including games, movies, music, books, and more. You can use the search bar to type in the name of the game you want, followed by "Wii NTSC WBFS". For example, if you want to download Dragon Ball Z: Budokai Tenkaichi 3 for Wii, you can type in "dragon ball z budokai tenkaichi 3 wii ntsc wbfs" and hit enter. -You will then see a list of results that match your query. You can sort them by name, date, size, seeders, leechers, or comments. Seeders are users who have the complete file and are sharing it with others. Leechers are users who are downloading the file but have not completed it yet. You want to choose a torrent file that has a high number of seeders and a low number of leechers, as this means that it is more reliable and faster to download. -Once you find a torrent file that suits your needs, you can click on it to open its details page. Here you can see more information about the file, such as its description, screenshots, comments from other users, and trackers. Trackers are servers that help connect users who have the file with users who want it. You can also see a magnet link that you can use to download the file dfd1c89656 - - - diff --git a/spaces/huggingface-projects/color-palette-generator-sd/static/_app/immutable/chunks/_layout-1daba58d.js b/spaces/huggingface-projects/color-palette-generator-sd/static/_app/immutable/chunks/_layout-1daba58d.js deleted file mode 100644 index 470b827d2ea3fc294e0b8a1ff4ca645db498ef5a..0000000000000000000000000000000000000000 --- a/spaces/huggingface-projects/color-palette-generator-sd/static/_app/immutable/chunks/_layout-1daba58d.js +++ /dev/null @@ -1 +0,0 @@ -const e=!0,r=Object.freeze(Object.defineProperty({__proto__:null,prerender:!0},Symbol.toStringTag,{value:"Module"}));export{r as _,e as p}; diff --git a/spaces/iccv23-diffusers-demo/Shap-E/style.css b/spaces/iccv23-diffusers-demo/Shap-E/style.css deleted file mode 100644 index a2b8d7b6672bef280910f8ae236cfad9429f1e63..0000000000000000000000000000000000000000 --- a/spaces/iccv23-diffusers-demo/Shap-E/style.css +++ /dev/null @@ -1,20 +0,0 @@ -h1 { - text-align: center; -} - -#component-0 { - max-width: 730px; - margin: auto; - padding-top: 1.5rem; -} - -#prompt-container { - gap: 0; -} - -#duplicate-button { - margin: auto; - color: #fff; - background: #1565c0; - border-radius: 100vh; -} diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Adobe InDesign CC 2018 Multilanguage (64 Bit-crack) [ChingLiu].md b/spaces/inplisQlawa/anything-midjourney-v4-1/Adobe InDesign CC 2018 Multilanguage (64 Bit-crack) [ChingLiu].md deleted file mode 100644 index df84bb585ad83c4dddc150419b5051f95d3b7c84..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Adobe InDesign CC 2018 Multilanguage (64 Bit-crack) [ChingLiu].md +++ /dev/null @@ -1,6 +0,0 @@ -

    Adobe InDesign CC 2018 Multilanguage (64 bit-crack) [ChingLiu]


    Download Zip » https://urlin.us/2uEx2T



    - -PATCHED Adobe InDesign CC 2017. Multilanguage (64 Bit-crack) > http://bit.ly/2CT286c 4c1e08f8e7 .... Adobe InDesign CC 2018 V13.1.0.76 Crack ... 1fdad05405
    -
    -
    -

    diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Auto Tune Efx Vst V1 0.2 2 Crack [UPDATED] Head.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Auto Tune Efx Vst V1 0.2 2 Crack [UPDATED] Head.md deleted file mode 100644 index a809cff7eb969d5d0b2dbcfe51923ed3061a97b0..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Auto Tune Efx Vst V1 0.2 2 Crack [UPDATED] Head.md +++ /dev/null @@ -1,6 +0,0 @@ -

    auto tune efx vst v1 0.2 2 crack head


    DOWNLOAD ⇒⇒⇒ https://urlin.us/2uExHP



    -
    -Auto Tune Efx Vst V1 0.2 2 Crack Head - http://imgfil.com/16y0wo a757f658d7 synthesia learning pack crack 0.8.2 Roger Stancil has been . 1fdad05405
    -
    -
    -

    diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Download Free Arcview 3.3 Windows 7 64 Bit !LINK!.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Download Free Arcview 3.3 Windows 7 64 Bit !LINK!.md deleted file mode 100644 index af8334053a1265377fc01e69f96ed2cd86173d95..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Download Free Arcview 3.3 Windows 7 64 Bit !LINK!.md +++ /dev/null @@ -1,6 +0,0 @@ -

    download free arcview 3.3 windows 7 64 bit


    DOWNLOAD ->>> https://urlin.us/2uEvDm



    - - 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/ioanniskarkanias/chatbot-with-sources/app.py b/spaces/ioanniskarkanias/chatbot-with-sources/app.py deleted file mode 100644 index 28b6ce1e9aba5997b3c1a73a6ef15d685b6bb890..0000000000000000000000000000000000000000 --- a/spaces/ioanniskarkanias/chatbot-with-sources/app.py +++ /dev/null @@ -1,233 +0,0 @@ -import gradio as gr -from langchain.document_loaders import TextLoader -from langchain.document_loaders.csv_loader import CSVLoader -from langchain.chains import ConversationalRetrievalChain -from langchain.vectorstores import Chroma -from langchain.text_splitter import CharacterTextSplitter -from langchain import ConversationChain - -from langchain.chat_models import ChatOpenAI -from langchain.embeddings import OpenAIEmbeddings - -from pathlib import Path -import requests - - -class ChatbotBackend: - def __init__(self): - self.llm = None - self.embeddings = None - self.db = None - self.retriever = None - self.sources = [] - self.fnames = [] - self.chain = None - self.similarity_k = 1 - self.markdown_sources = [] - - def reset_llm(self): - self.llm = None - self.embeddings = None - self.chain = None - - def authenticate(self, api_key): - def is_valid_openai_key(api_key): - # doing this without using openai.api_key, as it propagates globally to all users - headers = {"Authorization": f"Bearer {api_key}"} - url = "https://api.openai.com/v1/engines" - - response = requests.get(url, headers=headers) - - if response.status_code == 200: - return True - else: - return False - - if is_valid_openai_key(api_key): - # print("API key is valid.") - # history = history + [[None, "API key set successfully!"]] - self.llm = ChatOpenAI( - model_name="gpt-3.5-turbo", temperature=0, openai_api_key=api_key - ) - self.embeddings = OpenAIEmbeddings(openai_api_key=api_key) - self.chain = ConversationChain(llm=self.llm, verbose=False) - else: - # print("Something went wrong, check your API key.") - self.reset_llm() - - def generate_response(self, user_input, chat_history=None): - # generate a response from the model - # if the chatbot chain is a ConversationChain, use .predict - # if the chatbot chain is a ConversationalRetrievalChain, use chatbot_chain({"question": user_input, "chat_history": []}) - if isinstance(self.chain, ConversationChain): - return self.chain.predict(input=user_input) - elif isinstance(self.chain, ConversationalRetrievalChain): - return self.chain({"question": user_input, "chat_history": []})["answer"] - else: - return "Please paste your OpenAI key..." - - def update_chain(self): - # if sources are added, switch chatbot chain to ConversationalRetrievalChain - self.similarity_k = len(self.sources) - retriever = self.db.as_retriever(search_kwargs={"k": self.similarity_k}) - if not isinstance(self.chain, ConversationalRetrievalChain): - self.chain = ConversationalRetrievalChain.from_llm( - llm=self.llm, - retriever=retriever, - ) - else: - self.chain.retriever = retriever - - def update_sources(self, fname): - # add data to existing database for retrieval - # call swap_chain when the first source is added - # add data to existing database for retrieval - if Path(fname).suffix==".txt": - loader = TextLoader(file_path=f"{fname}") - data = loader.load() - self.fnames.append(f"{Path(fname).stem}{Path(fname).suffix}") - self.markdown_sources.append(f"## {Path(fname).stem}{Path(fname).suffix}") - self.sources.append(data[0].page_content) - self.markdown_sources.append(data[0].page_content) - else: - loader = CSVLoader(file_path=f"{fname}") - data = loader.load() - self.fnames.append(f"{Path(fname).stem}{Path(fname).suffix}") - self.markdown_sources.append(f"## {Path(fname).stem}{Path(fname).suffix}") - for i in data: - self.sources.append(i.page_content) - self.markdown_sources.append(i.page_content) - - text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0) - texts = text_splitter.split_documents(data) - - if not self.db: - self.db = Chroma.from_documents(texts, self.embeddings) - else: - self.db.add_documents(texts) - - self.update_chain() - - -#################################################### - - -with gr.Blocks() as demo: - chatbot_instance = gr.State(ChatbotBackend()) - api_key_instance = gr.State() - markdown_sources = gr.State() - - def set_api(api_key, history, chatbot_instance): - chatbot_instance.authenticate(api_key) - if chatbot_instance.llm is not None: - history = history + [[None, "API key set successfully."]] - else: - history = history + [[None, "Invalid OpenAI key..."]] - return history, chatbot_instance - - def add_text(history, text, chatbot_instance): - history = history + [(text, None)] - return ( - history, - "", - chatbot_instance, - ) # "" is meant to clear the textbox input message - - def add_file(history, file, chatbot_instance, markdown_sources): - if chatbot_instance.llm is not None: - chatbot_instance.update_sources(fname=file.name) - history = history + [ - ( - f"Uploaded file {file.name}", - f"**File {Path(file.name).stem}{Path(file.name).suffix} received! You can now query information regarding this source!**", - ) - ] - markdown_sources = ( - "# Loaded Text Sources\n\n" - + "\n".join(chatbot_instance.markdown_sources) - + "\n\n### NB: The same file isn't accepted twice in a row." - ) - else: - history = history + [ - ( - f"Uploaded file {file.name}", - "File not processed. " + "Please paste your OpenAI API key...", - ) - ] - return history, chatbot_instance, markdown_sources - - def bot(history, chatbot_instance): - # bot needs to update the "answer" part of the last conversation step, aka history[-1] - user_input = history[-1][0] - # answer = "Code me scrub!" - if chatbot_instance.llm is not None: - answer = chatbot_instance.generate_response(user_input, history[-3:-1]) - else: - answer = "Please paste your OpenAI API key..." - history[-1][1] = answer - return history, chatbot_instance - - with gr.Row(): - with gr.Column(scale=0.5): - chatbot_output = gr.Chatbot( - value=[(None, "I'm the database Chatbot 🤖 ! What is your request?")], - elem_id="chatbot", - ).style(height=500) - with gr.Row(): - with gr.Column(scale=0.8): - txt = gr.Textbox( - show_label=False, - placeholder="Enter text and press enter, or upload an .txt or .csv file", - ).style(container=False) - with gr.Column(scale=0.1, min_width=0): - chat_btn = gr.Button("Chat") - with gr.Column(scale=0.2, min_width=0): - upload_btn = gr.UploadButton("📁", file_types=["text"]) - with gr.Column(scale=0.5): - with gr.Row(): - with gr.Column(): - openai_api_key_textbox = gr.Textbox( - placeholder="Paste your OpenAI API key...", - show_label=False, - lines=1, - type="password", - ).style(container=False) - with gr.Column(scale=0.2, min_width=0): - api_btn = gr.Button("Set") - markdown = gr.Markdown( - "# Loaded Text Sources\n\nCurrently empty...\n\nPlease paste an API key before uploading a file." - ) - - api_btn.click( - fn=set_api, - inputs=[openai_api_key_textbox, chatbot_output, chatbot_instance], - outputs=[chatbot_output, chatbot_instance], - ) - - txt.submit( - fn=add_text, - inputs=[chatbot_output, txt, chatbot_instance], - outputs=[chatbot_output, txt, chatbot_instance], - ).then( - fn=bot, - inputs=[chatbot_output, chatbot_instance], - outputs=[chatbot_output, chatbot_instance], - ) - - chat_btn.click( - fn=add_text, - inputs=[chatbot_output, txt, chatbot_instance], - outputs=[chatbot_output, txt, chatbot_instance], - ).then( - fn=bot, - inputs=[chatbot_output, chatbot_instance], - outputs=[chatbot_output, chatbot_instance], - ) - - upload_btn.upload( - fn=add_file, - inputs=[chatbot_output, upload_btn, chatbot_instance, markdown], - outputs=[chatbot_output, chatbot_instance, markdown], - ) - -demo.launch() diff --git a/spaces/irvay/RVC_IR/lib/infer_pack/modules.py b/spaces/irvay/RVC_IR/lib/infer_pack/modules.py deleted file mode 100644 index c83289df7c79a4810dacd15c050148544ba0b6a9..0000000000000000000000000000000000000000 --- a/spaces/irvay/RVC_IR/lib/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 lib.infer_pack import commons -from lib.infer_pack.commons import init_weights, get_padding -from lib.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/jaleesahmed/data-description/README.md b/spaces/jaleesahmed/data-description/README.md deleted file mode 100644 index ffbc125f0e1d7550f1bdd743d77143b557496a0e..0000000000000000000000000000000000000000 --- a/spaces/jaleesahmed/data-description/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Data Description -emoji: 📈 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.1.3 -app_file: app.py -pinned: false -license: lgpl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/jayvaghasiya/winerybarreloak/README.md b/spaces/jayvaghasiya/winerybarreloak/README.md deleted file mode 100644 index 219e83a8da207346bbe43e7d84616eb88f491e11..0000000000000000000000000000000000000000 --- a/spaces/jayvaghasiya/winerybarreloak/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Winerybarreloak -emoji: ⚡ -colorFrom: green -colorTo: green -sdk: gradio -sdk_version: 3.36.1 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/jbilcke-hf/LifeSim/src/components/ui/table.tsx b/spaces/jbilcke-hf/LifeSim/src/components/ui/table.tsx deleted file mode 100644 index 953fb3c003bc0cd9d93059c373bc23e6aecbded8..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/LifeSim/src/components/ui/table.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import * as React from "react" - -import { cn } from "@/lib/utils" - -const Table = React.forwardRef< - HTMLTableElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -
    GameGenreSourcePrice
    Forza Horizon 4Racing, Open WorldMicrosoft Store, Steam$59.99
    Project CARS 3Racing, SimulationDirect Download, Steam$59.99
    Need for Speed HeatRacing, ActionDirect Download, Steam, Epic Games Store$29.99
    The Crew 2Racing, Open WorldDirect Download, Steam, Epic Games Store$49.99
    Assetto Corsa CompetizioneRacing, SimulationDirect Download, Steam$39.99
    Grand Theft Auto VAction, Adventure, Open WorldDirect Download, Steam, Epic Games Store$29.99
    Cyberpunk 2077Action, RPG, Open WorldDirect Download, Steam, Epic Games Store, GOG$59.99
    Euro Truck Simulator 2Simulation, DrivingDirect Download, Steam, GOG$19.99
    - -)) -Table.displayName = "Table" - -const TableHeader = React.forwardRef< - HTMLTableSectionElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( - -)) -TableHeader.displayName = "TableHeader" - -const TableBody = React.forwardRef< - HTMLTableSectionElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( - -)) -TableBody.displayName = "TableBody" - -const TableFooter = React.forwardRef< - HTMLTableSectionElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( - -)) -TableFooter.displayName = "TableFooter" - -const TableRow = React.forwardRef< - HTMLTableRowElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( - -)) -TableRow.displayName = "TableRow" - -const TableHead = React.forwardRef< - HTMLTableCellElement, - React.ThHTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)) -TableHead.displayName = "TableHead" - -const TableCell = React.forwardRef< - HTMLTableCellElement, - React.TdHTMLAttributes ->(({ className, ...props }, ref) => ( - -)) -TableCell.displayName = "TableCell" - -const TableCaption = React.forwardRef< - HTMLTableCaptionElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)) -TableCaption.displayName = "TableCaption" - -export { - Table, - TableHeader, - TableBody, - TableFooter, - TableHead, - TableRow, - TableCell, - TableCaption, -} diff --git a/spaces/jbilcke-hf/ai-clip-factory/src/app/server/actions/interpolateReplicate.ts b/spaces/jbilcke-hf/ai-clip-factory/src/app/server/actions/interpolateReplicate.ts deleted file mode 100644 index 09e6f60567cc50ccb78a6fa9767052a07f4bcc69..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/ai-clip-factory/src/app/server/actions/interpolateReplicate.ts +++ /dev/null @@ -1,78 +0,0 @@ -import Replicate from "replicate" - -import { sleep } from "@/lib/sleep" - -const replicateToken = `${process.env.AUTH_REPLICATE_API_TOKEN || ""}` -const replicateModel = `${process.env.INTERPOLATION_API_REPLICATE_MODEL || ""}` -const replicateModelVersion = `${process.env.INTERPOLATION_API_REPLICATE_MODEL_VERSION || ""}` - -export async function interpolateReplicate(input: string): Promise { - if (!replicateToken) { - throw new Error(`you need to configure your AUTH_REPLICATE_API_TOKEN in order to use interpolation`) - } - if (!replicateModel) { - throw new Error(`you need to configure your INTERPOLATION_API_REPLICATE_MODEL in order to use interpolation`) - } - - if (!replicateModelVersion) { - throw new Error(`you need to configure your INTERPOLATION_API_REPLICATE_MODEL_VERSION in order to use interpolation`) - } - const replicate = new Replicate({ auth: replicateToken }) - - const prediction = await replicate.predictions.create({ - version: replicateModelVersion, - input: { - mp4: input, - framerate_multiplier: 4, - keep_original_duration: true, - } - }) - - let res: Response - let pollingCount = 0 - do { - // This is normally a fast model, so let's check every 4 seconds - await sleep(4000) - - res = await fetch(`https://api.replicate.com/v1/predictions/${prediction.id}`, { - method: "GET", - headers: { - Authorization: `Token ${replicateToken}`, - }, - cache: 'no-store', - }) - - // console.log("res:", res) - - /* - try { - const text = await res.text() - console.log("res.text:", text) - } catch (err) { - console.error("res.text() error:", err) - } - */ - - if (res.status === 200) { - try { - const response = (await res.json()) as any - const error = `${response?.error || ""}` - if (error) { - throw new Error(error) - } - if (response.status === "succeeded") { - return response.output.pop() - } - } catch (err) { - console.error("res.json() error:", err) - } - } - - pollingCount++ - - // To prevent indefinite polling, we can stop after a certain number - if (pollingCount >= 20) { - throw new Error('Request time out.') - } - } while (true) -} \ No newline at end of file diff --git a/spaces/jbilcke-hf/ai-clip-factory/src/components/ui/toast.tsx b/spaces/jbilcke-hf/ai-clip-factory/src/components/ui/toast.tsx deleted file mode 100644 index 94b1e9a1d3a82fe1beea6e931c4887e2260371cd..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/ai-clip-factory/src/components/ui/toast.tsx +++ /dev/null @@ -1,127 +0,0 @@ -import * as React from "react" -import * as ToastPrimitives from "@radix-ui/react-toast" -import { cva, type VariantProps } from "class-variance-authority" -import { X } from "lucide-react" - -import { cn } from "@/lib/utils" - -const ToastProvider = ToastPrimitives.Provider - -const ToastViewport = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -ToastViewport.displayName = ToastPrimitives.Viewport.displayName - -const toastVariants = cva( - "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border border-stone-200 p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full dark:border-stone-800", - { - variants: { - variant: { - default: "border bg-white text-stone-950 dark:bg-stone-950 dark:text-stone-50", - destructive: - "destructive group border-red-500 bg-red-500 text-stone-50 dark:border-red-900 dark:bg-red-900 dark:text-stone-50", - }, - }, - defaultVariants: { - variant: "default", - }, - } -) - -const Toast = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef & - VariantProps ->(({ className, variant, ...props }, ref) => { - return ( - - ) -}) -Toast.displayName = ToastPrimitives.Root.displayName - -const ToastAction = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -ToastAction.displayName = ToastPrimitives.Action.displayName - -const ToastClose = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - - - -)) -ToastClose.displayName = ToastPrimitives.Close.displayName - -const ToastTitle = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -ToastTitle.displayName = ToastPrimitives.Title.displayName - -const ToastDescription = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -ToastDescription.displayName = ToastPrimitives.Description.displayName - -type ToastProps = React.ComponentPropsWithoutRef - -type ToastActionElement = React.ReactElement - -export { - type ToastProps, - type ToastActionElement, - ToastProvider, - ToastViewport, - Toast, - ToastTitle, - ToastDescription, - ToastClose, - ToastAction, -} diff --git a/spaces/jbilcke-hf/observer/src/app/listen.tsx b/spaces/jbilcke-hf/observer/src/app/listen.tsx deleted file mode 100644 index ad26c6146b494fbb8835f0bf7aba2189a80eeef1..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/observer/src/app/listen.tsx +++ /dev/null @@ -1,316 +0,0 @@ -"use client" - -import { useCallback, useEffect, useRef, useState, useTransition } from "react" -import { useInterval } from "usehooks-ts" - -// TODO: try this? https://www.npmjs.com/package/react-audio-voice-recorder -import { useRecorder } from "react-microphone-recorder" -import { getWaveBlob } from "webm-to-wav-converter" -import { - AvailableModels, - InferenceSession, - SessionManager, -} from "whisper-turbo" - -import { useToast } from "@/components/ui/use-toast" -import { useStore } from "./useStore" - -export interface TSSegment { - text: string; - start: number; - stop: number; - last: boolean; -} - -export interface TSTranscript { - segments: Array; -} - -export function Listen({ - onListen, -}: { - onListen: (recording: string) => void -}) { - const { toast } = useToast() - const speechSynthesis = useStore(state => state.speechSynthesis) - const isSpeaking = useStore(state => state.isSpeaking) - const isSpeakingRef = useRef(isSpeaking) - useEffect(() => {isSpeakingRef.current = isSpeaking }, [isSpeaking]) - - const setHearing = useStore(state => state.setHearing) - const isHearing = useStore(state => state.isHearing) - - const [transcribing, setTranscribing] = useState(false) - const transcribingRef = useRef(transcribing) - useEffect(() => { transcribingRef.current = transcribing }, [transcribing]) - - // used to detect changes, signal when we can analyze the audio - const [audioDataFrame, setAudioDataFrame] = useState(0) - const audioDataFrameRef = useRef(audioDataFrame) - useEffect(() => { audioDataFrameRef.current = audioDataFrame }, [audioDataFrame]) - - const [transcriptBuffer, setTranscriptBuffer] = useState("") - useEffect(() => { - onListen(transcriptBuffer) - }, [transcriptBuffer]) - /* - Available models: { - WHISPER_TINY: 'whisper-tiny', - WHISPER_BASE: 'whisper-base', - WHISPER_SMALL: 'whisper-small', - WHISPER_MEDIUM: 'whisper-medium', - WHISPER_LARGE: 'whisper-large' - } - */ - - // unfortunately, we cannot really use models larger than TINY because they are - // too slow to process requests - const whisperModel: AvailableModels = AvailableModels.WHISPER_TINY - - const listenerRef = useRef({ - isListening: false, - startedListeningAt: 0, - stoppedListeningAt: 0, - durationInMs: 0, - hits: 0, - debugCanContinue: true, // used for debugging - }) - - // the background listener is not a CIA spy device, but a detect of changes in the - // background noise volume level. The goal is to detect whenever an interesting event is happening - const backgroundListener = useRecorder() - - // the foreground listener is the actual sound sampler - // with out system, it will always lag a bit behind the background listener - // however there might be a fix (which I haven't tried yet): - // to take the last second of the background listener sample, - // and glue it to the beginning of the foreground listener sample - // - // or, alternatively, we could just try to use a shorter time window for the background listener, - // to make it more reactive - const foregroundListener = useRecorder() - - // to detect voice, we use a combination of audio level and frequency sampling - const heardSomething = backgroundListener.audioLevel > 12 // 18 - - const status = heardSomething ? "I hear something!" : "background noise" - - const session = useRef(null) - const [audioData, setAudioData] = useState(null) - const [audioMetadata, setAudioMetadata] = useState(null) - const [loaded, setLoaded] = useState(false) - const [progress, setProgress] = useState(0) - - const isLoadingModel = progress > 0 - const hasLoadedModel = progress === 100 - - const loadModel = async () => { - console.log("loadModel") - if (session.current) { - session.current.destroy() - } - if (!whisperModel) { - console.error("No whisper model loaded") - return - } - - try { - const manager = new SessionManager() - const loadResult = await manager.loadModel( - whisperModel, - () => { - setLoaded(true) - }, - (p: number) => { - console.log("progress:", p) - setProgress(p) - } - ) - if (loadResult.isErr) { - throw new Error(loadResult.error.message) - } else { - session.current = loadResult.value - } - } catch (err) { - const error = `failed to load the model: ${err}` - console.error(error) - toast({ - title: "Error", - description: error, - variant: "destructive" - }) - } - } - - const runSession = async () => { - if (!loaded) { - console.log("runSession: aborting (model not loaded yet)") - return - } - if (!session.current) { - console.log("runSession: aborting (no model loaded)") - toast({ - title: "Error", - description: "No model loaded", - variant: "destructive" - }) - return - } - // console.log("debug:", { audioData, audioDataFrame }) - if (!audioData) { - console.log("runSession: aborting (no audio file loaded)") - toast({ - title: "Error", - description: "No audio file loaded", - variant: "destructive" - }) - return - } - - setTranscribing(transcribingRef.current = true) - - try { - await session.current.transcribe(audioData, (s: any) => { - const segment = s as { text: string, start: number, stop: number, last: boolean } - const text = segment.text.trim() - console.log("text:", text) - if (text) { - setTranscriptBuffer(text) - } - - if (s.last) { - console.log("IS LAST") - setTranscribing(transcribingRef.current = false) - return - } - }) - } catch (err) { - const error = `transcription crashed: ${err}` - console.error(error) - toast({ - title: "Error", - description: "No audio file loaded", - variant: "destructive" - }) - } - } - - // let's disable the background recorder for now - useInterval(() => { - // console.log("let's stop, and start again") - backgroundListener.stopRecording() - backgroundListener.startRecording() - }, 3000) - - useEffect(() => { - const fn = async () => { - console.log("load model..") - await loadModel() - - console.log("starting to listen to background noise to detect volume peaks..") - backgroundListener.startRecording() - } - - fn() - }, []) - - - useEffect(() => { - if (!audioData) { - console.log("no audio") - } - // console.log("audioDataFrame changed, need to process audioData!") - runSession() - }, [audioDataFrame]) - - // note: this effect only reacts to "head something" changes - // anod not to changes to isListening or isSpekaing - useEffect(() => { - const isListening = listenerRef.current.isListening - - if (!heardSomething) { return } - - if (listenerRef.current.isListening) { - // console.log("we are already listening, so skipping..") - return - } - if (isSpeakingRef.current) { - console.log("we are already busy speaking, so ignoring..") - return - } - setHearing(true) - // console.log("recording..") - foregroundListener.startRecording() - listenerRef.current.hits = 0 - listenerRef.current.isListening = true - - setTimeout(async () => { - foregroundListener.stopRecording() - setHearing(false) - listenerRef.current.isListening = false - listenerRef.current.stoppedListeningAt = Date.now() - listenerRef.current.durationInMs = - listenerRef.current.stoppedListeningAt - listenerRef.current.startedListeningAt - - const hits = listenerRef.current.hits - - if (!foregroundListener.audioBlob || typeof window === "undefined" || !window?.FileReader) { - return - } - - if (hits <= 11) { - return - } - - - console.log(`end of sample (${foregroundListener.timeElapsed}, ${hits} hits)`) - - - // at 12 threshold level, we should have between 12 and 20 hits (per 2 sec) for short words and utterances - // at 12 threshold level, keystrokes should not be detected, unless the person hits the keyboard heavily - - // console.log("got an interesting sample, sending for review") - - // temporary, to prevent infinite loop - if (listenerRef.current.debugCanContinue) { - // to prevent the infinite loop, set this value to false - // listenerRef.current.debugCanContinue = false - - try { - const blob = await getWaveBlob(foregroundListener.audioBlob, false) // false = 16 bit, true = 32 bit - const arrayBuffer = await blob.arrayBuffer() - const uint8Array = new Uint8Array(arrayBuffer) - - setAudioData(uint8Array) - setAudioDataFrame(audioDataFrameRef.current + 1) - } catch (err) { - const error = `failed to convert the audio sample: ${err}` - console.error(error) - toast({ - title: "Error", - description: error, - variant: "destructive" - }) - } - } else { - console.log("Julian: infinite loop temporary disabled!") - } - }, 2000) - }, [heardSomething]) - - if (heardSomething && listenerRef.current.isListening) { - listenerRef.current.hits = listenerRef.current.hits + 1 - } - - return ( -
    - {isLoadingModel && !hasLoadedModel - ?

    Loading whisper-turbo: {progress}% done

    - :

    { - transcriptBuffer - || "" - }

    - } -
    - ) -} diff --git a/spaces/jgerbscheid/dpa-example/setup.py b/spaces/jgerbscheid/dpa-example/setup.py deleted file mode 100644 index 6172dd0fd3cb0f6adcb3f57da9c0bfa7832a2456..0000000000000000000000000000000000000000 --- a/spaces/jgerbscheid/dpa-example/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -from setuptools import setup, find_packages - -setup(name='dijkprofile_annotator', - version='0.1.0', - description='Automatically annotate drijkprofile in qDAMEdit format', - long_description=open('README.md').read(), - url='', - author='Jonathan Gerbscheid', - author_email='j.gerbscheid@hetwaterschapshuis.nl', - license='MIT', - package_dir={"dijkprofile_annotator": "dijkprofile_annotator"}, - packages=find_packages(), - zip_safe=False, - install_requires=["joblib", - "matplotlib", - "numpy", - "pillow", - "scikit_learn>=1.0.1", - "seaborn", - "torch>=1.9.0"] - ) diff --git a/spaces/joaogabriellima/Real-Time-Voice-Cloning/encoder/data_objects/random_cycler.py b/spaces/joaogabriellima/Real-Time-Voice-Cloning/encoder/data_objects/random_cycler.py deleted file mode 100644 index c405db6b27f46d874d8feb37e3f9c1e12c251109..0000000000000000000000000000000000000000 --- a/spaces/joaogabriellima/Real-Time-Voice-Cloning/encoder/data_objects/random_cycler.py +++ /dev/null @@ -1,37 +0,0 @@ -import random - -class RandomCycler: - """ - Creates an internal copy of a sequence and allows access to its items in a constrained random - order. For a source sequence of n items and one or several consecutive queries of a total - of m items, the following guarantees hold (one implies the other): - - Each item will be returned between m // n and ((m - 1) // n) + 1 times. - - Between two appearances of the same item, there may be at most 2 * (n - 1) other items. - """ - - def __init__(self, source): - if len(source) == 0: - raise Exception("Can't create RandomCycler from an empty collection") - self.all_items = list(source) - self.next_items = [] - - def sample(self, count: int): - shuffle = lambda l: random.sample(l, len(l)) - - out = [] - while count > 0: - if count >= len(self.all_items): - out.extend(shuffle(list(self.all_items))) - count -= len(self.all_items) - continue - n = min(count, len(self.next_items)) - out.extend(self.next_items[:n]) - count -= n - self.next_items = self.next_items[n:] - if len(self.next_items) == 0: - self.next_items = shuffle(list(self.all_items)) - return out - - def __next__(self): - return self.sample(1)[0] - diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/Util/Padding.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/Util/Padding.py deleted file mode 100644 index da69e55987227357a55f8e1b57fae5f7eb8cac74..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/Util/Padding.py +++ /dev/null @@ -1,108 +0,0 @@ -# -# Util/Padding.py : Functions to manage padding -# -# =================================================================== -# -# Copyright (c) 2014, Legrandin -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# =================================================================== - -__all__ = [ 'pad', 'unpad' ] - -from Crypto.Util.py3compat import * - - -def pad(data_to_pad, block_size, style='pkcs7'): - """Apply standard padding. - - Args: - data_to_pad (byte string): - The data that needs to be padded. - block_size (integer): - The block boundary to use for padding. The output length is guaranteed - to be a multiple of :data:`block_size`. - style (string): - Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. - - Return: - byte string : the original data with the appropriate padding added at the end. - """ - - padding_len = block_size-len(data_to_pad)%block_size - if style == 'pkcs7': - padding = bchr(padding_len)*padding_len - elif style == 'x923': - padding = bchr(0)*(padding_len-1) + bchr(padding_len) - elif style == 'iso7816': - padding = bchr(128) + bchr(0)*(padding_len-1) - else: - raise ValueError("Unknown padding style") - return data_to_pad + padding - - -def unpad(padded_data, block_size, style='pkcs7'): - """Remove standard padding. - - Args: - padded_data (byte string): - A piece of data with padding that needs to be stripped. - block_size (integer): - The block boundary to use for padding. The input length - must be a multiple of :data:`block_size`. - style (string): - Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. - Return: - byte string : data without padding. - Raises: - ValueError: if the padding is incorrect. - """ - - pdata_len = len(padded_data) - if pdata_len == 0: - raise ValueError("Zero-length input cannot be unpadded") - if pdata_len % block_size: - raise ValueError("Input data is not padded") - if style in ('pkcs7', 'x923'): - padding_len = bord(padded_data[-1]) - if padding_len<1 or padding_len>min(block_size, pdata_len): - raise ValueError("Padding is incorrect.") - if style == 'pkcs7': - if padded_data[-padding_len:]!=bchr(padding_len)*padding_len: - raise ValueError("PKCS#7 padding is incorrect.") - else: - if padded_data[-padding_len:-1]!=bchr(0)*(padding_len-1): - raise ValueError("ANSI X.923 padding is incorrect.") - elif style == 'iso7816': - padding_len = pdata_len - padded_data.rfind(bchr(128)) - if padding_len<1 or padding_len>min(block_size, pdata_len): - raise ValueError("Padding is incorrect.") - if padding_len>1 and padded_data[1-padding_len:]!=bchr(0)*(padding_len-1): - raise ValueError("ISO 7816-4 padding is incorrect.") - else: - raise ValueError("Unknown padding style") - return padded_data[:-padding_len] - diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/struct_store/base.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/struct_store/base.py deleted file mode 100644 index 2955dfcde57e505427a0bd3d8fc97c942224481f..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/struct_store/base.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Struct store.""" - -import re -from typing import Any, Callable, Dict, Generic, Optional, Sequence, TypeVar - -from gpt_index.data_structs.table import BaseStructTable -from gpt_index.indices.base import DOCUMENTS_INPUT, BaseGPTIndex -from gpt_index.langchain_helpers.chain_wrapper import LLMPredictor -from gpt_index.langchain_helpers.text_splitter import TextSplitter -from gpt_index.prompts.default_prompts import DEFAULT_SCHEMA_EXTRACT_PROMPT -from gpt_index.prompts.prompts import SchemaExtractPrompt - -BST = TypeVar("BST", bound=BaseStructTable) - - -def default_output_parser(output: str) -> Optional[Dict[str, Any]]: - """Parse output of schema extraction. - - Attempt to parse the following format from the default prompt: - field1: , field2: , ... - - """ - tups = output.split("\n") - - fields = {} - for tup in tups: - if ":" in tup: - tokens = tup.split(":") - field = re.sub(r"\W+", "", tokens[0]) - value = re.sub(r"\W+", "", tokens[1]) - fields[field] = value - return fields - - -OUTPUT_PARSER_TYPE = Callable[[str], Optional[Dict[str, Any]]] - - -class BaseGPTStructStoreIndex(BaseGPTIndex[BST], Generic[BST]): - """Base GPT Struct Store Index.""" - - def __init__( - self, - documents: Optional[Sequence[DOCUMENTS_INPUT]] = None, - index_struct: Optional[BST] = None, - schema_extract_prompt: Optional[SchemaExtractPrompt] = None, - output_parser: Optional[OUTPUT_PARSER_TYPE] = None, - llm_predictor: Optional[LLMPredictor] = None, - text_splitter: Optional[TextSplitter] = None, - **kwargs: Any, - ) -> None: - """Initialize params.""" - self.schema_extract_prompt = ( - schema_extract_prompt or DEFAULT_SCHEMA_EXTRACT_PROMPT - ) - self.output_parser = output_parser or default_output_parser - super().__init__( - documents=documents, - index_struct=index_struct, - llm_predictor=llm_predictor, - text_splitter=text_splitter, - **kwargs, - ) - - def _build_fallback_text_splitter(self) -> TextSplitter: - # if not specified, use "smart" text splitter to ensure chunks fit in prompt - return self._prompt_helper.get_text_splitter_given_prompt( - self.schema_extract_prompt, 1 - ) - - def _delete(self, doc_id: str, **delete_kwargs: Any) -> None: - """Delete a document.""" - raise NotImplementedError("Delete not implemented for Struct Store Index.") diff --git a/spaces/johnslegers/stable-diffusion-gui-test/ldmlib/modules/diffusionmodules/openaimodel.py b/spaces/johnslegers/stable-diffusion-gui-test/ldmlib/modules/diffusionmodules/openaimodel.py deleted file mode 100644 index 84b01c5e473605cc592dfdbeb03279a2103effae..0000000000000000000000000000000000000000 --- a/spaces/johnslegers/stable-diffusion-gui-test/ldmlib/modules/diffusionmodules/openaimodel.py +++ /dev/null @@ -1,960 +0,0 @@ -from abc import abstractmethod -from functools import partial -import math -from typing import Iterable - -import numpy as np -import torch as th -import torch.nn as nn -import torch.nn.functional as F - -from ldmlib.modules.diffusionmodules.util import ( - checkpoint, - conv_nd, - linear, - avg_pool_nd, - zero_module, - normalization, - timestep_embedding, -) -from ldmlib.modules.attention import SpatialTransformer - - -# dummy replace -def convert_module_to_f16(x): - pass - -def convert_module_to_f32(x): - pass - - -## go -class AttentionPool2d(nn.Module): - """ - Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py - """ - - def __init__( - self, - spacial_dim: int, - embed_dim: int, - num_heads_channels: int, - output_dim: int = None, - ): - super().__init__() - self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) - self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) - self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) - self.num_heads = embed_dim // num_heads_channels - self.attention = QKVAttention(self.num_heads) - - def forward(self, x): - b, c, *_spatial = x.shape - x = x.reshape(b, c, -1) # NC(HW) - x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) - x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) - x = self.qkv_proj(x) - x = self.attention(x) - x = self.c_proj(x) - return x[:, :, 0] - - -class TimestepBlock(nn.Module): - """ - Any module where forward() takes timestep embeddings as a second argument. - """ - - @abstractmethod - def forward(self, x, emb): - """ - Apply the module to `x` given `emb` timestep embeddings. - """ - - -class TimestepEmbedSequential(nn.Sequential, TimestepBlock): - """ - A sequential module that passes timestep embeddings to the children that - support it as an extra input. - """ - - def forward(self, x, emb, context=None): - for layer in self: - if isinstance(layer, TimestepBlock): - x = layer(x, emb) - elif isinstance(layer, SpatialTransformer): - x = layer(x, context) - else: - x = layer(x) - return x - - -class Upsample(nn.Module): - """ - An upsampling layer with an optional convolution. - :param channels: channels in the inputs and outputs. - :param use_conv: a bool determining if a convolution is applied. - :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then - upsampling occurs in the inner-two dimensions. - """ - - def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - self.use_conv = use_conv - self.dims = dims - if use_conv: - self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) - - def forward(self, x): - assert x.shape[1] == self.channels - if self.dims == 3: - x = F.interpolate( - x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" - ) - else: - x = F.interpolate(x, scale_factor=2, mode="nearest") - if self.use_conv: - x = self.conv(x) - return x - -class TransposedUpsample(nn.Module): - 'Learned 2x upsampling without padding' - def __init__(self, channels, out_channels=None, ks=5): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - - self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) - - def forward(self,x): - return self.up(x) - - -class Downsample(nn.Module): - """ - A downsampling layer with an optional convolution. - :param channels: channels in the inputs and outputs. - :param use_conv: a bool determining if a convolution is applied. - :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then - downsampling occurs in the inner-two dimensions. - """ - - def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - self.use_conv = use_conv - self.dims = dims - stride = 2 if dims != 3 else (1, 2, 2) - if use_conv: - self.op = conv_nd( - dims, self.channels, self.out_channels, 3, stride=stride, padding=padding - ) - else: - assert self.channels == self.out_channels - self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) - - def forward(self, x): - assert x.shape[1] == self.channels - return self.op(x) - - -class ResBlock(TimestepBlock): - """ - A residual block that can optionally change the number of channels. - :param channels: the number of input channels. - :param emb_channels: the number of timestep embedding channels. - :param dropout: the rate of dropout. - :param out_channels: if specified, the number of out channels. - :param use_conv: if True and out_channels is specified, use a spatial - convolution instead of a smaller 1x1 convolution to change the - channels in the skip connection. - :param dims: determines if the signal is 1D, 2D, or 3D. - :param use_checkpoint: if True, use gradient checkpointing on this module. - :param up: if True, use this block for upsampling. - :param down: if True, use this block for downsampling. - """ - - def __init__( - self, - channels, - emb_channels, - dropout, - out_channels=None, - use_conv=False, - use_scale_shift_norm=False, - dims=2, - use_checkpoint=False, - up=False, - down=False, - ): - super().__init__() - self.channels = channels - self.emb_channels = emb_channels - self.dropout = dropout - self.out_channels = out_channels or channels - self.use_conv = use_conv - self.use_checkpoint = use_checkpoint - self.use_scale_shift_norm = use_scale_shift_norm - - self.in_layers = nn.Sequential( - normalization(channels), - nn.SiLU(), - conv_nd(dims, channels, self.out_channels, 3, padding=1), - ) - - self.updown = up or down - - if up: - self.h_upd = Upsample(channels, False, dims) - self.x_upd = Upsample(channels, False, dims) - elif down: - self.h_upd = Downsample(channels, False, dims) - self.x_upd = Downsample(channels, False, dims) - else: - self.h_upd = self.x_upd = nn.Identity() - - self.emb_layers = nn.Sequential( - nn.SiLU(), - linear( - emb_channels, - 2 * self.out_channels if use_scale_shift_norm else self.out_channels, - ), - ) - self.out_layers = nn.Sequential( - normalization(self.out_channels), - nn.SiLU(), - nn.Dropout(p=dropout), - zero_module( - conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) - ), - ) - - if self.out_channels == channels: - self.skip_connection = nn.Identity() - elif use_conv: - self.skip_connection = conv_nd( - dims, channels, self.out_channels, 3, padding=1 - ) - else: - self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) - - def forward(self, x, emb): - """ - Apply the block to a Tensor, conditioned on a timestep embedding. - :param x: an [N x C x ...] Tensor of features. - :param emb: an [N x emb_channels] Tensor of timestep embeddings. - :return: an [N x C x ...] Tensor of outputs. - """ - return checkpoint( - self._forward, (x, emb), self.parameters(), self.use_checkpoint - ) - - - def _forward(self, x, emb): - if self.updown: - in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] - h = in_rest(x) - h = self.h_upd(h) - x = self.x_upd(x) - h = in_conv(h) - else: - h = self.in_layers(x) - emb_out = self.emb_layers(emb).type(h.dtype) - while len(emb_out.shape) < len(h.shape): - emb_out = emb_out[..., None] - if self.use_scale_shift_norm: - out_norm, out_rest = self.out_layers[0], self.out_layers[1:] - scale, shift = th.chunk(emb_out, 2, dim=1) - h = out_norm(h) * (1 + scale) + shift - h = out_rest(h) - else: - h = h + emb_out - h = self.out_layers(h) - return self.skip_connection(x) + h - - -class AttentionBlock(nn.Module): - """ - An attention block that allows spatial positions to attend to each other. - Originally ported from here, but adapted to the N-d case. - https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. - """ - - def __init__( - self, - channels, - num_heads=1, - num_head_channels=-1, - use_checkpoint=False, - use_new_attention_order=False, - ): - super().__init__() - self.channels = channels - if num_head_channels == -1: - self.num_heads = num_heads - else: - assert ( - channels % num_head_channels == 0 - ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" - self.num_heads = channels // num_head_channels - self.use_checkpoint = use_checkpoint - self.norm = normalization(channels) - self.qkv = conv_nd(1, channels, channels * 3, 1) - if use_new_attention_order: - # split qkv before split heads - self.attention = QKVAttention(self.num_heads) - else: - # split heads before split qkv - self.attention = QKVAttentionLegacy(self.num_heads) - - self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) - - def forward(self, x): - return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!! - #return pt_checkpoint(self._forward, x) # pytorch - - def _forward(self, x): - b, c, *spatial = x.shape - x = x.reshape(b, c, -1) - qkv = self.qkv(self.norm(x)) - h = self.attention(qkv) - h = self.proj_out(h) - return (x + h).reshape(b, c, *spatial) - - -def count_flops_attn(model, _x, y): - """ - A counter for the `thop` package to count the operations in an - attention operation. - Meant to be used like: - macs, params = thop.profile( - model, - inputs=(inputs, timestamps), - custom_ops={QKVAttention: QKVAttention.count_flops}, - ) - """ - b, c, *spatial = y[0].shape - num_spatial = int(np.prod(spatial)) - # We perform two matmuls with the same number of ops. - # The first computes the weight matrix, the second computes - # the combination of the value vectors. - matmul_ops = 2 * b * (num_spatial ** 2) * c - model.total_ops += th.DoubleTensor([matmul_ops]) - - -class QKVAttentionLegacy(nn.Module): - """ - A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping - """ - - def __init__(self, n_heads): - super().__init__() - self.n_heads = n_heads - - def forward(self, qkv): - """ - Apply QKV attention. - :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. - :return: an [N x (H * C) x T] tensor after attention. - """ - bs, width, length = qkv.shape - assert width % (3 * self.n_heads) == 0 - ch = width // (3 * self.n_heads) - q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) - scale = 1 / math.sqrt(math.sqrt(ch)) - weight = th.einsum( - "bct,bcs->bts", q * scale, k * scale - ) # More stable with f16 than dividing afterwards - weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) - a = th.einsum("bts,bcs->bct", weight, v) - return a.reshape(bs, -1, length) - - @staticmethod - def count_flops(model, _x, y): - return count_flops_attn(model, _x, y) - - -class QKVAttention(nn.Module): - """ - A module which performs QKV attention and splits in a different order. - """ - - def __init__(self, n_heads): - super().__init__() - self.n_heads = n_heads - - def forward(self, qkv): - """ - Apply QKV attention. - :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. - :return: an [N x (H * C) x T] tensor after attention. - """ - bs, width, length = qkv.shape - assert width % (3 * self.n_heads) == 0 - ch = width // (3 * self.n_heads) - q, k, v = qkv.chunk(3, dim=1) - scale = 1 / math.sqrt(math.sqrt(ch)) - weight = th.einsum( - "bct,bcs->bts", - (q * scale).view(bs * self.n_heads, ch, length), - (k * scale).view(bs * self.n_heads, ch, length), - ) # More stable with f16 than dividing afterwards - weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) - a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) - return a.reshape(bs, -1, length) - - @staticmethod - def count_flops(model, _x, y): - return count_flops_attn(model, _x, y) - - -class UNetModel(nn.Module): - """ - The full UNet model with attention and timestep embedding. - :param in_channels: channels in the input Tensor. - :param model_channels: base channel count for the model. - :param out_channels: channels in the output Tensor. - :param num_res_blocks: number of residual blocks per downsample. - :param attention_resolutions: a collection of downsample rates at which - attention will take place. May be a set, list, or tuple. - For example, if this contains 4, then at 4x downsampling, attention - will be used. - :param dropout: the dropout probability. - :param channel_mult: channel multiplier for each level of the UNet. - :param conv_resample: if True, use learned convolutions for upsampling and - downsampling. - :param dims: determines if the signal is 1D, 2D, or 3D. - :param num_classes: if specified (as an int), then this model will be - class-conditional with `num_classes` classes. - :param use_checkpoint: use gradient checkpointing to reduce memory usage. - :param num_heads: the number of attention heads in each attention layer. - :param num_heads_channels: if specified, ignore num_heads and instead use - a fixed channel width per attention head. - :param num_heads_upsample: works with num_heads to set a different number - of heads for upsampling. Deprecated. - :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. - :param resblock_updown: use residual blocks for up/downsampling. - :param use_new_attention_order: use a different attention pattern for potentially - increased efficiency. - """ - - def __init__( - self, - image_size, - in_channels, - model_channels, - out_channels, - num_res_blocks, - attention_resolutions, - dropout=0, - channel_mult=(1, 2, 4, 8), - conv_resample=True, - dims=2, - num_classes=None, - use_checkpoint=False, - use_fp16=False, - num_heads=-1, - num_head_channels=-1, - num_heads_upsample=-1, - use_scale_shift_norm=False, - resblock_updown=False, - use_new_attention_order=False, - use_spatial_transformer=False, # custom transformer support - transformer_depth=1, # custom transformer support - context_dim=None, # custom transformer support - n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model - legacy=True, - ): - super().__init__() - if use_spatial_transformer: - assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' - - if context_dim is not None: - assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' - from omegaconf.listconfig import ListConfig - if type(context_dim) == ListConfig: - context_dim = list(context_dim) - - if num_heads_upsample == -1: - num_heads_upsample = num_heads - - if num_heads == -1: - assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' - - if num_head_channels == -1: - assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' - - self.image_size = image_size - self.in_channels = in_channels - self.model_channels = model_channels - self.out_channels = out_channels - self.num_res_blocks = num_res_blocks - self.attention_resolutions = attention_resolutions - self.dropout = dropout - self.channel_mult = channel_mult - self.conv_resample = conv_resample - self.num_classes = num_classes - self.use_checkpoint = use_checkpoint - self.dtype = th.float16 if use_fp16 else th.float32 - self.num_heads = num_heads - self.num_head_channels = num_head_channels - self.num_heads_upsample = num_heads_upsample - self.predict_codebook_ids = n_embed is not None - - time_embed_dim = model_channels * 4 - self.time_embed = nn.Sequential( - linear(model_channels, time_embed_dim), - nn.SiLU(), - linear(time_embed_dim, time_embed_dim), - ) - - if self.num_classes is not None: - self.label_emb = nn.Embedding(num_classes, time_embed_dim) - - self.input_blocks = nn.ModuleList( - [ - TimestepEmbedSequential( - conv_nd(dims, in_channels, model_channels, 3, padding=1) - ) - ] - ) - self._feature_size = model_channels - input_block_chans = [model_channels] - ch = model_channels - ds = 1 - for level, mult in enumerate(channel_mult): - for _ in range(num_res_blocks): - layers = [ - ResBlock( - ch, - time_embed_dim, - dropout, - out_channels=mult * model_channels, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ) - ] - ch = mult * model_channels - if ds in attention_resolutions: - if num_head_channels == -1: - dim_head = ch // num_heads - else: - num_heads = ch // num_head_channels - dim_head = num_head_channels - if legacy: - #num_heads = 1 - dim_head = ch // num_heads if use_spatial_transformer else num_head_channels - layers.append( - AttentionBlock( - ch, - use_checkpoint=use_checkpoint, - num_heads=num_heads, - num_head_channels=dim_head, - use_new_attention_order=use_new_attention_order, - ) if not use_spatial_transformer else SpatialTransformer( - ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim - ) - ) - self.input_blocks.append(TimestepEmbedSequential(*layers)) - self._feature_size += ch - input_block_chans.append(ch) - if level != len(channel_mult) - 1: - out_ch = ch - self.input_blocks.append( - TimestepEmbedSequential( - ResBlock( - ch, - time_embed_dim, - dropout, - out_channels=out_ch, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - down=True, - ) - if resblock_updown - else Downsample( - ch, conv_resample, dims=dims, out_channels=out_ch - ) - ) - ) - ch = out_ch - input_block_chans.append(ch) - ds *= 2 - self._feature_size += ch - - if num_head_channels == -1: - dim_head = ch // num_heads - else: - num_heads = ch // num_head_channels - dim_head = num_head_channels - if legacy: - #num_heads = 1 - dim_head = ch // num_heads if use_spatial_transformer else num_head_channels - self.middle_block = TimestepEmbedSequential( - ResBlock( - ch, - time_embed_dim, - dropout, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ), - AttentionBlock( - ch, - use_checkpoint=use_checkpoint, - num_heads=num_heads, - num_head_channels=dim_head, - use_new_attention_order=use_new_attention_order, - ) if not use_spatial_transformer else SpatialTransformer( - ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim - ), - ResBlock( - ch, - time_embed_dim, - dropout, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ), - ) - self._feature_size += ch - - self.output_blocks = nn.ModuleList([]) - for level, mult in list(enumerate(channel_mult))[::-1]: - for i in range(num_res_blocks + 1): - ich = input_block_chans.pop() - layers = [ - ResBlock( - ch + ich, - time_embed_dim, - dropout, - out_channels=model_channels * mult, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ) - ] - ch = model_channels * mult - if ds in attention_resolutions: - if num_head_channels == -1: - dim_head = ch // num_heads - else: - num_heads = ch // num_head_channels - dim_head = num_head_channels - if legacy: - #num_heads = 1 - dim_head = ch // num_heads if use_spatial_transformer else num_head_channels - layers.append( - AttentionBlock( - ch, - use_checkpoint=use_checkpoint, - num_heads=num_heads_upsample, - num_head_channels=dim_head, - use_new_attention_order=use_new_attention_order, - ) if not use_spatial_transformer else SpatialTransformer( - ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim - ) - ) - if level and i == num_res_blocks: - out_ch = ch - layers.append( - ResBlock( - ch, - time_embed_dim, - dropout, - out_channels=out_ch, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - up=True, - ) - if resblock_updown - else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) - ) - ds //= 2 - self.output_blocks.append(TimestepEmbedSequential(*layers)) - self._feature_size += ch - - self.out = nn.Sequential( - normalization(ch), - nn.SiLU(), - zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), - ) - if self.predict_codebook_ids: - self.id_predictor = nn.Sequential( - normalization(ch), - conv_nd(dims, model_channels, n_embed, 1), - #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits - ) - - def convert_to_fp16(self): - """ - Convert the torso of the model to float16. - """ - self.input_blocks.apply(convert_module_to_f16) - self.middle_block.apply(convert_module_to_f16) - self.output_blocks.apply(convert_module_to_f16) - - def convert_to_fp32(self): - """ - Convert the torso of the model to float32. - """ - self.input_blocks.apply(convert_module_to_f32) - self.middle_block.apply(convert_module_to_f32) - self.output_blocks.apply(convert_module_to_f32) - - def forward(self, x, timesteps=None, context=None, y=None,**kwargs): - """ - Apply the model to an input batch. - :param x: an [N x C x ...] Tensor of inputs. - :param timesteps: a 1-D batch of timesteps. - :param context: conditioning plugged in via crossattn - :param y: an [N] Tensor of labels, if class-conditional. - :return: an [N x C x ...] Tensor of outputs. - """ - assert (y is not None) == ( - self.num_classes is not None - ), "must specify y if and only if the model is class-conditional" - hs = [] - t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) - emb = self.time_embed(t_emb) - - if self.num_classes is not None: - assert y.shape == (x.shape[0],) - emb = emb + self.label_emb(y) - - h = x.type(self.dtype) - for module in self.input_blocks: - h = module(h, emb, context) - hs.append(h) - h = self.middle_block(h, emb, context) - for module in self.output_blocks: - h = th.cat([h, hs.pop()], dim=1) - h = module(h, emb, context) - h = h.type(x.dtype) - if self.predict_codebook_ids: - return self.id_predictor(h) - else: - return self.out(h) - - -class EncoderUNetModel(nn.Module): - """ - The half UNet model with attention and timestep embedding. - For usage, see UNet. - """ - - def __init__( - self, - image_size, - in_channels, - model_channels, - out_channels, - num_res_blocks, - attention_resolutions, - dropout=0, - channel_mult=(1, 2, 4, 8), - conv_resample=True, - dims=2, - use_checkpoint=False, - use_fp16=False, - num_heads=1, - num_head_channels=-1, - num_heads_upsample=-1, - use_scale_shift_norm=False, - resblock_updown=False, - use_new_attention_order=False, - pool="adaptive", - *args, - **kwargs - ): - super().__init__() - - if num_heads_upsample == -1: - num_heads_upsample = num_heads - - self.in_channels = in_channels - self.model_channels = model_channels - self.out_channels = out_channels - self.num_res_blocks = num_res_blocks - self.attention_resolutions = attention_resolutions - self.dropout = dropout - self.channel_mult = channel_mult - self.conv_resample = conv_resample - self.use_checkpoint = use_checkpoint - self.dtype = th.float16 if use_fp16 else th.float32 - self.num_heads = num_heads - self.num_head_channels = num_head_channels - self.num_heads_upsample = num_heads_upsample - - time_embed_dim = model_channels * 4 - self.time_embed = nn.Sequential( - linear(model_channels, time_embed_dim), - nn.SiLU(), - linear(time_embed_dim, time_embed_dim), - ) - - self.input_blocks = nn.ModuleList( - [ - TimestepEmbedSequential( - conv_nd(dims, in_channels, model_channels, 3, padding=1) - ) - ] - ) - self._feature_size = model_channels - input_block_chans = [model_channels] - ch = model_channels - ds = 1 - for level, mult in enumerate(channel_mult): - for _ in range(num_res_blocks): - layers = [ - ResBlock( - ch, - time_embed_dim, - dropout, - out_channels=mult * model_channels, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ) - ] - ch = mult * model_channels - if ds in attention_resolutions: - layers.append( - AttentionBlock( - ch, - use_checkpoint=use_checkpoint, - num_heads=num_heads, - num_head_channels=num_head_channels, - use_new_attention_order=use_new_attention_order, - ) - ) - self.input_blocks.append(TimestepEmbedSequential(*layers)) - self._feature_size += ch - input_block_chans.append(ch) - if level != len(channel_mult) - 1: - out_ch = ch - self.input_blocks.append( - TimestepEmbedSequential( - ResBlock( - ch, - time_embed_dim, - dropout, - out_channels=out_ch, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - down=True, - ) - if resblock_updown - else Downsample( - ch, conv_resample, dims=dims, out_channels=out_ch - ) - ) - ) - ch = out_ch - input_block_chans.append(ch) - ds *= 2 - self._feature_size += ch - - self.middle_block = TimestepEmbedSequential( - ResBlock( - ch, - time_embed_dim, - dropout, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ), - AttentionBlock( - ch, - use_checkpoint=use_checkpoint, - num_heads=num_heads, - num_head_channels=num_head_channels, - use_new_attention_order=use_new_attention_order, - ), - ResBlock( - ch, - time_embed_dim, - dropout, - dims=dims, - use_checkpoint=use_checkpoint, - use_scale_shift_norm=use_scale_shift_norm, - ), - ) - self._feature_size += ch - self.pool = pool - if pool == "adaptive": - self.out = nn.Sequential( - normalization(ch), - nn.SiLU(), - nn.AdaptiveAvgPool2d((1, 1)), - zero_module(conv_nd(dims, ch, out_channels, 1)), - nn.Flatten(), - ) - elif pool == "attention": - assert num_head_channels != -1 - self.out = nn.Sequential( - normalization(ch), - nn.SiLU(), - AttentionPool2d( - (image_size // ds), ch, num_head_channels, out_channels - ), - ) - elif pool == "spatial": - self.out = nn.Sequential( - nn.Linear(self._feature_size, 2048), - nn.ReLU(), - nn.Linear(2048, self.out_channels), - ) - elif pool == "spatial_v2": - self.out = nn.Sequential( - nn.Linear(self._feature_size, 2048), - normalization(2048), - nn.SiLU(), - nn.Linear(2048, self.out_channels), - ) - else: - raise NotImplementedError(f"Unexpected {pool} pooling") - - def convert_to_fp16(self): - """ - Convert the torso of the model to float16. - """ - self.input_blocks.apply(convert_module_to_f16) - self.middle_block.apply(convert_module_to_f16) - - def convert_to_fp32(self): - """ - Convert the torso of the model to float32. - """ - self.input_blocks.apply(convert_module_to_f32) - self.middle_block.apply(convert_module_to_f32) - - def forward(self, x, timesteps): - """ - Apply the model to an input batch. - :param x: an [N x C x ...] Tensor of inputs. - :param timesteps: a 1-D batch of timesteps. - :return: an [N x K] Tensor of outputs. - """ - emb = self.time_embed(timestep_embedding(timesteps, self.model_channels)) - - results = [] - h = x.type(self.dtype) - for module in self.input_blocks: - h = module(h, emb) - if self.pool.startswith("spatial"): - results.append(h.type(x.dtype).mean(dim=(2, 3))) - h = self.middle_block(h, emb) - if self.pool.startswith("spatial"): - results.append(h.type(x.dtype).mean(dim=(2, 3))) - h = th.cat(results, axis=-1) - return self.out(h) - else: - h = h.type(x.dtype) - return self.out(h) diff --git a/spaces/jordonpeter01/MusicGen/audiocraft/models/builders.py b/spaces/jordonpeter01/MusicGen/audiocraft/models/builders.py deleted file mode 100644 index 77ee5f96fea2e3c9e475fe961bc1a5ee473ed8eb..0000000000000000000000000000000000000000 --- a/spaces/jordonpeter01/MusicGen/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/juancopi81/whisper-youtube-2-hf_dataset/utils.py b/spaces/juancopi81/whisper-youtube-2-hf_dataset/utils.py deleted file mode 100644 index 466111502fb39899fd379cc7f36401d7acfe7e01..0000000000000000000000000000000000000000 --- a/spaces/juancopi81/whisper-youtube-2-hf_dataset/utils.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import Dict, List - -from video import YoutubeVideo -from errors import DifferentNumberOfArgumentsError - -def accepts_types(*expected_types): - """Decorator that checks that the arguments of a method are valid. - :raise TypeError: If type of argument isn't valid - :raise DifferentNumberOfArgumentsError: If number of arguments passed to the - decorator and to the method (minus self) aren't the same - """ - def check_types(func): - def wrapper(*args, **kwargs): - args_without_self = args[1:] - _raise_error_if_number_of_passed_and_expected_arguments_dont_match(args_without_self, expected_types) - _raise_type_error_if_passed_and_expected_types_dont_match(args_without_self, expected_types) - return func(*args, **kwargs) - return wrapper - return check_types - -def _raise_error_if_number_of_passed_and_expected_arguments_dont_match(passed_args, expected_types): - if len(passed_args) != len(expected_types): - msg = "Number of arguments passed in decorator " \ - f"{len(expected_types)} doesn't match with number of " \ - f"arguments in method, i.e., {len(passed_args)}" - raise DifferentNumberOfArgumentsError(msg) - -def _raise_type_error_if_passed_and_expected_types_dont_match(passed_args, expected_types): - for (arg, expected_type) in zip(passed_args, expected_types): - if not isinstance(arg, expected_type): - raise TypeError(f"Argument '{arg}' is of type {type(arg)}. " - f"'{expected_type}' expected instead") - -def create_videos(video_parameters: List[Dict]) -> List[YoutubeVideo]: - """Factory function that creates a list of YoutubeVideos from a list of - dictionaries representing video parameters - """ - youtube_videos = [] - for params in video_parameters: - youtube_video = YoutubeVideo(channel_name=params["channel_name"], - url=params["url"]) - youtube_videos.append(youtube_video) - return youtube_videos - -def nest_list(list: list, nested_list_length: int) -> List[List]: - new_list = [] - nested_list = [] - for item in list: - nested_list.append(item) - if len(nested_list) == nested_list_length: - new_list.append(nested_list) - nested_list = [] - if len(nested_list) != 0: - new_list.append(nested_list) - return new_list - -def is_google_colab(): - try: - import google.colab - return True - except: - return False \ No newline at end of file diff --git a/spaces/jw2yang/unicl-img-recog-demo/app.py b/spaces/jw2yang/unicl-img-recog-demo/app.py deleted file mode 100644 index f9cef2b3170fc139306ae11a785f2da1f526c72a..0000000000000000000000000000000000000000 --- a/spaces/jw2yang/unicl-img-recog-demo/app.py +++ /dev/null @@ -1,144 +0,0 @@ -import argparse -import requests -import gradio as gr -import numpy as np -import cv2 -import torch -import torch.nn as nn -from PIL import Image -from torchvision import transforms -from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD -from timm.data import create_transform -from config import get_config -from model import build_model - -# Download human-readable labels for ImageNet. -response = requests.get("https://git.io/JJkYN") -labels = response.text.split("\n") - -def parse_option(): - parser = argparse.ArgumentParser('UniCL demo script', add_help=False) - parser.add_argument('--cfg', type=str, default="configs/unicl_swin_base.yaml", metavar="FILE", help='path to config file', ) - args, unparsed = parser.parse_known_args() - - config = get_config(args) - - return args, config - -def build_transforms(img_size, center_crop=True): - t = [transforms.ToPILImage()] - if center_crop: - size = int((256 / 224) * img_size) - t.append( - transforms.Resize(size) - ) - t.append( - transforms.CenterCrop(img_size) - ) - else: - t.append( - transforms.Resize(img_size) - ) - t.append(transforms.ToTensor()) - t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)) - return transforms.Compose(t) - -def build_transforms4display(img_size, center_crop=True): - t = [transforms.ToPILImage()] - if center_crop: - size = int((256 / 224) * img_size) - t.append( - transforms.Resize(size) - ) - t.append( - transforms.CenterCrop(img_size) - ) - else: - t.append( - transforms.Resize(img_size) - ) - t.append(transforms.ToTensor()) - return transforms.Compose(t) - -args, config = parse_option() - -''' -build model -''' -model = build_model(config) - -url = './in21k_yfcc14m_gcc15m_swin_base.pth' -checkpoint = torch.load(url, map_location="cpu") -model.load_state_dict(checkpoint["model"]) -model.eval() - -''' -build data transform -''' -eval_transforms = build_transforms(224, center_crop=True) -display_transforms = build_transforms4display(224, center_crop=True) - -''' -build upsampler -''' -# upsampler = nn.Upsample(scale_factor=16, mode='bilinear') - -''' -borrow code from here: https://github.com/jacobgil/pytorch-grad-cam/blob/master/pytorch_grad_cam/utils/image.py -''' -def show_cam_on_image(img: np.ndarray, - mask: np.ndarray, - use_rgb: bool = False, - colormap: int = cv2.COLORMAP_JET) -> np.ndarray: - """ This function overlays the cam mask on the image as an heatmap. - By default the heatmap is in BGR format. - :param img: The base image in RGB or BGR format. - :param mask: The cam mask. - :param use_rgb: Whether to use an RGB or BGR heatmap, this should be set to True if 'img' is in RGB format. - :param colormap: The OpenCV colormap to be used. - :returns: The default image with the cam overlay. - """ - heatmap = cv2.applyColorMap(np.uint8(255 * mask), colormap) - if use_rgb: - heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) - heatmap = np.float32(heatmap) / 255 - - if np.max(img) > 1: - raise Exception( - "The input image should np.float32 in the range [0, 1]") - - cam = 0.7*heatmap + 0.3*img - # cam = cam / np.max(cam) - return np.uint8(255 * cam) - -def recognize_image(image, texts): - img_t = eval_transforms(image) - img_d = display_transforms(image).permute(1, 2, 0).numpy() - - text_embeddings = model.get_text_embeddings(texts.split(';')) - - # compute output - feat_img = model.encode_image(img_t.unsqueeze(0)) - output = model.logit_scale.exp() * feat_img @ text_embeddings.t() - prediction = output.softmax(-1).flatten() - - return {texts.split(';')[i]: float(prediction[i]) for i in range(len(texts.split(';')))} - - -image = gr.inputs.Image() -label = gr.outputs.Label(num_top_classes=100) - -gr.Interface( - description="UniCL for Zero-shot Image Recognition Demo (https://github.com/microsoft/unicl)", - fn=recognize_image, - inputs=["image", "text"], - outputs=[ - label, - ], - examples=[ - ["./elephants.png", "an elephant; an elephant walking in the river; four elephants walking in the river"], - ["./apple_with_ipod.jpg", "an ipod; an apple with a write note 'ipod'; an apple"], - ["./crowd2.jpg", "a street; a street with a woman walking in the middle; a street with a man walking in the middle"], - ["./zebras.png", "three zebras on the grass; two zebras on the grass; one zebra on the grass; no zebra on the grass; four zebras on the grass"], - ], -).launch() diff --git a/spaces/ka1kuk/fastapi/g4f/Provider/Providers/ChatgptAi.py b/spaces/ka1kuk/fastapi/g4f/Provider/Providers/ChatgptAi.py deleted file mode 100644 index be2f8739eb82c9e1e52e2540abe808ebf8ef55ac..0000000000000000000000000000000000000000 --- a/spaces/ka1kuk/fastapi/g4f/Provider/Providers/ChatgptAi.py +++ /dev/null @@ -1,51 +0,0 @@ -import os -import requests, re -from ...typing import sha256, Dict, get_type_hints - -url = 'https://chatgpt.ai/gpt-4/' -model = ['gpt-4'] -supports_stream = True -needs_auth = False - - -def _create_completion(model: str, messages: list, stream: bool, **kwargs): - chat = '' - for message in messages: - chat += '%s: %s\n' % (message['role'], message['content']) - chat += 'user: ' - - response = requests.get('https://chatgpt.ai/') - nonce, post_id, _, bot_id = re.findall(r'data-nonce="(.*)"\n data-post-id="(.*)"\n data-url="(.*)"\n data-bot-id="(.*)"\n data-width', response.text)[0] - - headers = { - 'authority': 'chatgpt.ai', - 'accept': '*/*', - 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', - 'cache-control': 'no-cache', - 'origin': 'https://chatgpt.ai', - 'pragma': 'no-cache', - 'referer': 'https://chatgpt.ai/gpt-4/', - 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"Windows"', - 'sec-fetch-dest': 'empty', - 'sec-fetch-mode': 'cors', - 'sec-fetch-site': 'same-origin', - 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', - } - data = { - '_wpnonce': nonce, - 'post_id': post_id, - 'url': 'https://chatgpt.ai/gpt-4', - 'action': 'wpaicg_chat_shortcode_message', - 'message': chat, - 'bot_id': bot_id - } - - response = requests.post('https://chatgpt.ai/wp-admin/admin-ajax.php', - headers=headers, data=data) - - yield (response.json()['data']) - -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/kamranahmad92/GradioLanchainChatbotAi/README.md b/spaces/kamranahmad92/GradioLanchainChatbotAi/README.md deleted file mode 100644 index 2bd1fcbb8c6ea4038e69c74cab11c51edbf5136a..0000000000000000000000000000000000000000 --- a/spaces/kamranahmad92/GradioLanchainChatbotAi/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: GradioLanchainChatbotAi -emoji: 📉 -colorFrom: blue -colorTo: red -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/kepl/gpt/client/js/highlightjs-copy.min.js b/spaces/kepl/gpt/client/js/highlightjs-copy.min.js deleted file mode 100644 index ac11d33ec06e396c96b887494d9164a9b3996bef..0000000000000000000000000000000000000000 --- a/spaces/kepl/gpt/client/js/highlightjs-copy.min.js +++ /dev/null @@ -1 +0,0 @@ -class CopyButtonPlugin{constructor(options={}){self.hook=options.hook;self.callback=options.callback}"after:highlightElement"({el,text}){let button=Object.assign(document.createElement("button"),{innerHTML:"Copy",className:"hljs-copy-button"});button.dataset.copied=false;el.parentElement.classList.add("hljs-copy-wrapper");el.parentElement.appendChild(button);el.parentElement.style.setProperty("--hljs-theme-background",window.getComputedStyle(el).backgroundColor);button.onclick=function(){if(!navigator.clipboard)return;let newText=text;if(hook&&typeof hook==="function"){newText=hook(text,el)||text}navigator.clipboard.writeText(newText).then(function(){button.innerHTML="Copied!";button.dataset.copied=true;let alert=Object.assign(document.createElement("div"),{role:"status",className:"hljs-copy-alert",innerHTML:"Copied to clipboard"});el.parentElement.appendChild(alert);setTimeout(()=>{button.innerHTML="Copy";button.dataset.copied=false;el.parentElement.removeChild(alert);alert=null},2e3)}).then(function(){if(typeof callback==="function")return callback(newText,el)})}}} \ No newline at end of file diff --git a/spaces/keras-io/structured-data-classification/app.py b/spaces/keras-io/structured-data-classification/app.py deleted file mode 100644 index 6a8778266f8d94a8cb77897a42745777e397e5fc..0000000000000000000000000000000000000000 --- a/spaces/keras-io/structured-data-classification/app.py +++ /dev/null @@ -1,70 +0,0 @@ -import numpy as np -import tensorflow as tf -import gradio as gr -from huggingface_hub import from_pretrained_keras - -# download the already pushed model -model = from_pretrained_keras("keras-io/structured-data-classification") - -def convert_and_predict(age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal): - - # some conversions from the gradio interface are needed - sample_converted = { - "age": age, - "sex": sex, - "cp": cp+1, - "trestbps": trestbps, - "chol": chol, - "fbs": 0 if fbs<=120 else 1, - "restecg": restecg, - "thalach": thalach, - "exang": exang, - "oldpeak": oldpeak, - "slope": slope+1, - "ca": ca, - "thal": thal, -} - - input_dict = {name: tf.convert_to_tensor([value]) for name, value in sample_converted.items()} - predictions = model.predict(input_dict) - - return f'{predictions[0][0]:.2%}' - - -# the app uses slider and number fields for numerical inputs -# while radio buttons for the categoricals -inputs = [ - gr.Slider(minimum=1, maximum=120, step=1, label='age', value=60), - gr.Radio(choices=['female','male'], label='sex', type='index',value='male'), - gr.Radio(choices=['typical angina', - 'atypical angina', - 'non-anginal pain', - 'asymptomatic'], - type='index', label=f'chest pain type', value='typical angina'), - gr.Number(label='blood pressure in mmHg', value=145), - gr.Number(label='serum cholestoral in mg/dl', value=233), - gr.Number(label='fasting blood sugar in mg/dl', value=150), - gr.Radio(choices=['normal','T-T wave abnormality','probable or definite left ventricular hypertrophy'], - label='resting ecg', type='index',value='probable or definite left ventricular hypertrophy'), - gr.Number(label='maximum heart rate achieved', value=150), - gr.Radio(choices=['no','yes',], type='index', label='exercise induced angina',value='no'), - gr.Number(label='ST depression induced by exercise relative to rest', value=2.3), - gr.Radio(choices=['psloping','flat','downsloping'], label='slope of the peak exercise ST segment', type='index', value='downsloping'), - gr.Number(label ='number of major vessels (0-3) colored by flourosopy',value=0), - gr.Radio(['normal','fixed','reversable'],label ='thal', value='fixed') - ] - - -# the app outputs text -output = gr.Textbox(label='Probability of having a heart disease, as evaluated by our model:') -# it's good practice to pass examples, description and a title to guide users -title = "Structured Data Classification 🧮" -description = "Binary classification of structured data including numerical and categorical features for Heart Disease prediction." - -article = "Author: Marco Buiani. Based on this keras example by François Chollet. HuggingFace Model here " - -examples = [[41, 'female', 'atypical angina', 130, 204, 100, 'normal', 150, 'yes', 1.4, 'psloping', 2, 'reversible'], - [63, 'male', 'typical angina', 145, 233, 150, 'T-T wave abnormality', 150, 'no', 2.3, 'flat', 0, 'fixed']] - -gr.Interface(convert_and_predict, inputs, output, examples= examples, allow_flagging='never', - title=title, description=description, article=article, live=True).launch() \ No newline at end of file diff --git a/spaces/kevinwang676/VoiceChanger/src/audio2pose_models/res_unet.py b/spaces/kevinwang676/VoiceChanger/src/audio2pose_models/res_unet.py deleted file mode 100644 index f2611e1d1a9bf233507427b34928fca60e094224..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChanger/src/audio2pose_models/res_unet.py +++ /dev/null @@ -1,65 +0,0 @@ -import torch -import torch.nn as nn -from src.audio2pose_models.networks import ResidualConv, Upsample - - -class ResUnet(nn.Module): - def __init__(self, channel=1, filters=[32, 64, 128, 256]): - super(ResUnet, self).__init__() - - self.input_layer = nn.Sequential( - nn.Conv2d(channel, filters[0], kernel_size=3, padding=1), - nn.BatchNorm2d(filters[0]), - nn.ReLU(), - nn.Conv2d(filters[0], filters[0], kernel_size=3, padding=1), - ) - self.input_skip = nn.Sequential( - nn.Conv2d(channel, filters[0], kernel_size=3, padding=1) - ) - - self.residual_conv_1 = ResidualConv(filters[0], filters[1], stride=(2,1), padding=1) - self.residual_conv_2 = ResidualConv(filters[1], filters[2], stride=(2,1), padding=1) - - self.bridge = ResidualConv(filters[2], filters[3], stride=(2,1), padding=1) - - self.upsample_1 = Upsample(filters[3], filters[3], kernel=(2,1), stride=(2,1)) - self.up_residual_conv1 = ResidualConv(filters[3] + filters[2], filters[2], stride=1, padding=1) - - self.upsample_2 = Upsample(filters[2], filters[2], kernel=(2,1), stride=(2,1)) - self.up_residual_conv2 = ResidualConv(filters[2] + filters[1], filters[1], stride=1, padding=1) - - self.upsample_3 = Upsample(filters[1], filters[1], kernel=(2,1), stride=(2,1)) - self.up_residual_conv3 = ResidualConv(filters[1] + filters[0], filters[0], stride=1, padding=1) - - self.output_layer = nn.Sequential( - nn.Conv2d(filters[0], 1, 1, 1), - nn.Sigmoid(), - ) - - def forward(self, x): - # Encode - x1 = self.input_layer(x) + self.input_skip(x) - x2 = self.residual_conv_1(x1) - x3 = self.residual_conv_2(x2) - # Bridge - x4 = self.bridge(x3) - - # Decode - x4 = self.upsample_1(x4) - x5 = torch.cat([x4, x3], dim=1) - - x6 = self.up_residual_conv1(x5) - - x6 = self.upsample_2(x6) - x7 = torch.cat([x6, x2], dim=1) - - x8 = self.up_residual_conv2(x7) - - x8 = self.upsample_3(x8) - x9 = torch.cat([x8, x1], dim=1) - - x10 = self.up_residual_conv3(x9) - - output = self.output_layer(x10) - - return output \ No newline at end of file diff --git a/spaces/kevinwang676/voice-conversion-yourtts/bark/model.py b/spaces/kevinwang676/voice-conversion-yourtts/bark/model.py deleted file mode 100644 index 457b49e749f396c47c6b35f44955fd512d233d79..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/voice-conversion-yourtts/bark/model.py +++ /dev/null @@ -1,218 +0,0 @@ -""" -Much of this code is adapted from Andrej Karpathy's NanoGPT -(https://github.com/karpathy/nanoGPT) -""" -import math -from dataclasses import dataclass - -import torch -import torch.nn as nn -from torch.nn import functional as F - -class LayerNorm(nn.Module): - """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """ - - def __init__(self, ndim, bias): - super().__init__() - self.weight = nn.Parameter(torch.ones(ndim)) - self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None - - def forward(self, input): - return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5) - -class CausalSelfAttention(nn.Module): - - def __init__(self, config): - super().__init__() - assert config.n_embd % config.n_head == 0 - # key, query, value projections for all heads, but in a batch - self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias) - # output projection - self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias) - # regularization - self.attn_dropout = nn.Dropout(config.dropout) - self.resid_dropout = nn.Dropout(config.dropout) - self.n_head = config.n_head - self.n_embd = config.n_embd - self.dropout = config.dropout - # flash attention make GPU go brrrrr but support is only in PyTorch nightly and still a bit scary - self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') - if not self.flash: - # print("WARNING: using slow attention. Flash Attention atm needs PyTorch nightly and dropout=0.0") - # causal mask to ensure that attention is only applied to the left in the input sequence - self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)) - .view(1, 1, config.block_size, config.block_size)) - - def forward(self, x, past_kv=None, use_cache=False): - B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd) - - # calculate query, key, values for all heads in batch and move head forward to be the batch dim - q, k ,v = self.c_attn(x).split(self.n_embd, dim=2) - k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) - q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) - v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) - - if past_kv is not None: - past_key = past_kv[0] - past_value = past_kv[1] - k = torch.cat((past_key, k), dim=-2) - v = torch.cat((past_value, v), dim=-2) - - FULL_T = k.shape[-2] - - if use_cache is True: - present = (k, v) - else: - present = None - - # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T) - if self.flash: - # efficient attention using Flash Attention CUDA kernels - if past_kv is not None: - # When `past_kv` is provided, we're doing incremental decoding and `q.shape[2] == 1`: q only contains - # the query for the last token. scaled_dot_product_attention interprets this as the first token in the - # sequence, so if is_causal=True it will mask out all attention from it. This is not what we want, so - # to work around this we set is_causal=False. - is_causal = False - else: - is_causal = True - - y = torch.nn.functional.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout, is_causal=is_causal) - else: - # manual implementation of attention - att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) - att = att.masked_fill(self.bias[:,:,FULL_T-T:FULL_T,:FULL_T] == 0, float('-inf')) - att = F.softmax(att, dim=-1) - att = self.attn_dropout(att) - y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs) - y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side - - # output projection - y = self.resid_dropout(self.c_proj(y)) - return (y, present) - -class MLP(nn.Module): - - def __init__(self, config): - super().__init__() - self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias) - self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias) - self.dropout = nn.Dropout(config.dropout) - self.gelu = nn.GELU() - - def forward(self, x): - x = self.c_fc(x) - x = self.gelu(x) - x = self.c_proj(x) - x = self.dropout(x) - return x - -class Block(nn.Module): - - def __init__(self, config, layer_idx): - super().__init__() - self.ln_1 = LayerNorm(config.n_embd, bias=config.bias) - self.attn = CausalSelfAttention(config) - self.ln_2 = LayerNorm(config.n_embd, bias=config.bias) - self.mlp = MLP(config) - self.layer_idx = layer_idx - - def forward(self, x, past_kv=None, use_cache=False): - attn_output, prev_kvs = self.attn(self.ln_1(x), past_kv=past_kv, use_cache=use_cache) - x = x + attn_output - x = x + self.mlp(self.ln_2(x)) - return (x, prev_kvs) - -@dataclass -class GPTConfig: - block_size: int = 1024 - input_vocab_size: int = 10_048 - output_vocab_size: int = 10_048 - n_layer: int = 12 - n_head: int = 12 - n_embd: int = 768 - dropout: float = 0.0 - bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster - -class GPT(nn.Module): - - def __init__(self, config): - super().__init__() - assert config.input_vocab_size is not None - assert config.output_vocab_size is not None - assert config.block_size is not None - self.config = config - - self.transformer = nn.ModuleDict(dict( - wte = nn.Embedding(config.input_vocab_size, config.n_embd), - wpe = nn.Embedding(config.block_size, config.n_embd), - drop = nn.Dropout(config.dropout), - h = nn.ModuleList([Block(config, idx) for idx in range(config.n_layer)]), - ln_f = LayerNorm(config.n_embd, bias=config.bias), - )) - self.lm_head = nn.Linear(config.n_embd, config.output_vocab_size, bias=False) - - def get_num_params(self, non_embedding=True): - """ - Return the number of parameters in the model. - For non-embedding count (default), the position embeddings get subtracted. - The token embeddings would too, except due to the parameter sharing these - params are actually used as weights in the final layer, so we include them. - """ - n_params = sum(p.numel() for p in self.parameters()) - if non_embedding: - n_params -= self.transformer.wte.weight.numel() - n_params -= self.transformer.wpe.weight.numel() - return n_params - - def forward(self, idx, merge_context=False, past_kv=None, position_ids=None, use_cache=False): - device = idx.device - b, t = idx.size() - if past_kv is not None: - assert t == 1 - tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd) - else: - if merge_context: - assert(idx.shape[1] >= 256+256+1) - t = idx.shape[1] - 256 - else: - assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}" - - # forward the GPT model itself - if merge_context: - tok_emb = torch.cat([ - self.transformer.wte(idx[:,:256]) + self.transformer.wte(idx[:,256:256+256]), - self.transformer.wte(idx[:,256+256:]) - ], dim=1) - else: - tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd) - - if past_kv is None: - past_length = 0 - past_kv = tuple([None] * len(self.transformer.h)) - else: - past_length = past_kv[0][0].size(-2) - - if position_ids is None: - position_ids = torch.arange(past_length, t + past_length, dtype=torch.long, device=device) - position_ids = position_ids.unsqueeze(0) # shape (1, t) - assert position_ids.shape == (1, t) - - pos_emb = self.transformer.wpe(position_ids) # position embeddings of shape (1, t, n_embd) - - x = self.transformer.drop(tok_emb + pos_emb) - - new_kv = () if use_cache else None - - for i, (block, past_layer_kv) in enumerate(zip(self.transformer.h, past_kv)): - x, kv = block(x, past_kv=past_layer_kv, use_cache=use_cache) - - if use_cache: - new_kv = new_kv + (kv,) - - x = self.transformer.ln_f(x) - - # inference-time mini-optimization: only forward the lm_head on the very last position - logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim - - return (logits, new_kv) diff --git a/spaces/kidcoconut/spcstm_omdenasaudi_liverhccxai/routes/api/rte_api.py b/spaces/kidcoconut/spcstm_omdenasaudi_liverhccxai/routes/api/rte_api.py deleted file mode 100644 index c74d0041bbe645968740a8755b7d34fb142e1b30..0000000000000000000000000000000000000000 --- a/spaces/kidcoconut/spcstm_omdenasaudi_liverhccxai/routes/api/rte_api.py +++ /dev/null @@ -1,79 +0,0 @@ -from fastapi import APIRouter, Request, Response -from fastapi.responses import JSONResponse - -import pandas as pd -import json - -#import lib.claims as libClaims -#from lib.models import mdl_utils, mdl_xgb - - -rteApi = APIRouter() - - -#--- -@rteApi.get('/') -def api_entry(): - return { - "message": "api routing - welcome to Omdena Saudi HCC api" - } - - - -''' -#--- >>> SAMPLE CODE BELOW -#--- return json for claims data (merged) -#--- note: current is kaggle, but future could include from yyyymm filter -@rteApi.get('/claims', response_class = JSONResponse) -def api_getClaims(request: Request, response: Response): - pdfClaims = libClaims.load_claims() - jsonSample = pdfClaims.head(50).to_json(orient="records", indent=4) - result = json.loads(jsonSample) - return result - - -#--- return json for featEng -@rteApi.get('/claims/doFeatEng/', response_class = JSONResponse) -def tst_claims_featEng(): - pdfClaims = libClaims.load_claims() - pdfFeatEng = libClaims.do_featEng(pdfClaims) - jsonSample = pdfClaims.head(50).to_json(orient="records", indent=4) - result = json.loads(jsonSample) - return result - - -@rteApi.get('/claims/doStdScaling/', response_class = JSONResponse) -def tst_claims_stdScaling(): - pdfClaims = libClaims.load_claims() - pdfFeatEng = libClaims.do_featEng(pdfClaims) - pdfScaled = mdl_utils.doClaims_stdScaler_toPdf(pdfFeatEng) - - jsonSample = pdfClaims.head(50).to_json(orient="records", indent=4) - result = json.loads(jsonSample) - return result - - -@rteApi.get('/claims/predict/superv', response_class = JSONResponse) -@rteApi.get('/claims/predict/xgb', response_class = JSONResponse) -def predict_xgb(): - #--- load test data - pdfClaims = libClaims.load_claims() - pdfFeatEng = libClaims.do_featEng(pdfClaims) - - npaScaled = mdl_utils.do_stdScaler(pdfFeatEng) - pdfScaled = mdl_utils.do_stdScaler_toPdf(npaScaled) - - ndaPredict = mdl_xgb.predict(npaScaled) - pdfPredict = pd.DataFrame(ndaPredict) - - #--- stitch the grouped data with the labels - pdfResults = pdfScaled.copy() - pdfResults.insert(0, "hasAnom?", pdfPredict[0]) - - #--- filter to only those rows that are flagged with an anomaly - pdfResults = pdfResults[pdfResults['hasAnom?'] > 0] - - jsonSample = pdfResults.head(50).to_json(orient="records", indent=4) - result = json.loads(jsonSample) - return result -''' \ No newline at end of file diff --git a/spaces/kira4424/Tacotron-zero-short-voice-clone/ppg2mel/train/option.py b/spaces/kira4424/Tacotron-zero-short-voice-clone/ppg2mel/train/option.py deleted file mode 100644 index f66c600b84e0404c7937bacf8653776ce9be74c0..0000000000000000000000000000000000000000 --- a/spaces/kira4424/Tacotron-zero-short-voice-clone/ppg2mel/train/option.py +++ /dev/null @@ -1,10 +0,0 @@ -# Default parameters which will be imported by solver -default_hparas = { - 'GRAD_CLIP': 5.0, # Grad. clip threshold - 'PROGRESS_STEP': 100, # Std. output refresh freq. - # Decode steps for objective validation (step = ratio*input_txt_len) - 'DEV_STEP_RATIO': 1.2, - # Number of examples (alignment/text) to show in tensorboard - 'DEV_N_EXAMPLE': 4, - 'TB_FLUSH_FREQ': 180 # Update frequency of tensorboard (secs) -} diff --git a/spaces/kirch/Text2Video-Zero/config.py b/spaces/kirch/Text2Video-Zero/config.py deleted file mode 100644 index e0c738d8cbad66bbe1666284aef926c326849701..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/config.py +++ /dev/null @@ -1 +0,0 @@ -save_memory = False diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/themes/upload_theme.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/themes/upload_theme.py deleted file mode 100644 index ee11e056d488579e818bc4814d6b13892e6b6e0b..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/themes/upload_theme.py +++ /dev/null @@ -1,59 +0,0 @@ -from __future__ import annotations - -import argparse - -from gradio.themes import ThemeClass - - -def main(): - parser = argparse.ArgumentParser(description="Upload a demo to a space") - parser.add_argument("theme", type=str, help="Theme json file") - parser.add_argument("repo_name", type=str, help="HF repo name to store the theme") - parser.add_argument( - "--org_name", - type=str, - help="The name of the org to save the space in. If None (the default), the username corresponding to the logged in user, or hƒ_token is used.", - ) - parser.add_argument("--version", type=str, help="Semver version") - parser.add_argument("--hf_token", type=str, help="HF Token") - parser.add_argument( - "--theme-name", - type=str, - help="Name of theme.", - ) - parser.add_argument( - "--description", - type=str, - help="Description of theme", - ) - args = parser.parse_args() - upload_theme( - args.theme, - args.repo_name, - args.org_name, - args.version, - args.hf_token, - args.theme_name, - args.description, - ) - - -def upload_theme( - theme: str, - repo_name: str, - org_name: str | None = None, - version: str | None = None, - hf_token: str | None = None, - theme_name: str | None = None, - description: str | None = None, -): - theme = ThemeClass.load(theme) - - return theme.push_to_hub( - repo_name=repo_name, - version=version, - hf_token=hf_token, - theme_name=theme_name, - description=description, - org_name=org_name, - ) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_types.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_types.py deleted file mode 100644 index 6b610e14084b8a94f2fbad725a8885c2cf62fad8..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_types.py +++ /dev/null @@ -1,132 +0,0 @@ -""" -Type definitions for type checking purposes. -""" - -import ssl -from http.cookiejar import CookieJar -from typing import ( - IO, - TYPE_CHECKING, - Any, - AsyncIterable, - AsyncIterator, - Callable, - Dict, - Iterable, - Iterator, - List, - Mapping, - NamedTuple, - Optional, - Sequence, - Tuple, - Union, -) - -if TYPE_CHECKING: # pragma: no cover - from ._auth import Auth # noqa: F401 - from ._config import Proxy, Timeout # noqa: F401 - from ._models import Cookies, Headers, Request # noqa: F401 - from ._urls import URL, QueryParams # noqa: F401 - - -PrimitiveData = Optional[Union[str, int, float, bool]] - -RawURL = NamedTuple( - "RawURL", - [ - ("raw_scheme", bytes), - ("raw_host", bytes), - ("port", Optional[int]), - ("raw_path", bytes), - ], -) - -URLTypes = Union["URL", str] - -QueryParamTypes = Union[ - "QueryParams", - Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], - List[Tuple[str, PrimitiveData]], - Tuple[Tuple[str, PrimitiveData], ...], - str, - bytes, -] - -HeaderTypes = Union[ - "Headers", - Mapping[str, str], - Mapping[bytes, bytes], - Sequence[Tuple[str, str]], - Sequence[Tuple[bytes, bytes]], -] - -CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]] - -CertTypes = Union[ - # certfile - str, - # (certfile, keyfile) - Tuple[str, Optional[str]], - # (certfile, keyfile, password) - Tuple[str, Optional[str], Optional[str]], -] -VerifyTypes = Union[str, bool, ssl.SSLContext] -TimeoutTypes = Union[ - Optional[float], - Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], - "Timeout", -] -ProxiesTypes = Union[URLTypes, "Proxy", Dict[URLTypes, Union[None, URLTypes, "Proxy"]]] - -AuthTypes = Union[ - Tuple[Union[str, bytes], Union[str, bytes]], - Callable[["Request"], "Request"], - "Auth", -] - -RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] -ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] -ResponseExtensions = Mapping[str, Any] - -RequestData = Mapping[str, Any] - -FileContent = Union[IO[bytes], bytes, str] -FileTypes = Union[ - # file (or bytes) - FileContent, - # (filename, file (or bytes)) - Tuple[Optional[str], FileContent], - # (filename, file (or bytes), content_type) - Tuple[Optional[str], FileContent, Optional[str]], - # (filename, file (or bytes), content_type, headers) - Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], -] -RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] - -RequestExtensions = Mapping[str, Any] - - -class SyncByteStream: - def __iter__(self) -> Iterator[bytes]: - raise NotImplementedError( - "The '__iter__' method must be implemented." - ) # pragma: no cover - yield b"" # pragma: no cover - - def close(self) -> None: - """ - Subclasses can override this method to release any network resources - after a request/response cycle is complete. - """ - - -class AsyncByteStream: - async def __aiter__(self) -> AsyncIterator[bytes]: - raise NotImplementedError( - "The '__aiter__' method must be implemented." - ) # pragma: no cover - yield b"" # pragma: no cover - - async def aclose(self) -> None: - pass diff --git a/spaces/ky2k/image_denoise_demo/app.py b/spaces/ky2k/image_denoise_demo/app.py deleted file mode 100644 index fe0496824d5534d25a50b8c71d7eba02b4bae018..0000000000000000000000000000000000000000 --- a/spaces/ky2k/image_denoise_demo/app.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -from models import Noise2Same -import gradio as gr - -os.system("mkdir trained_models/denoising_ImageNet") -os.system("cd trained_models/denoising_ImageNet; gdown https://drive.google.com/uc?id=1asrwULW1lDFasystBc3UfShh5EeTHpkW; gdown https://drive.google.com/uc?id=1Re1ER7KtujBunN0-74QmYrrOx77WpVXK; gdown https://drive.google.com/uc?id=1QdlyUPUKyyGtqD0zBrj5F7qQZtmUELSu; gdown https://drive.google.com/uc?id=1LQsYR26ldHebcdQtP2zt4Mh-ZH9vXQ2S; gdown https://drive.google.com/uc?id=1AxTDD4dS0DtzmBywjGyeJYgDrw-XjYbc; gdown https://drive.google.com/uc?id=1w4UdNAbOjvWSL0Jgbq8_hCniaxqsbLaQ; cd ../..") -os.system("wget -O arch.png https://i.imgur.com/NruRABn.png") -os.system("wget -O parrot.png https://i.imgur.com/zdji3xv.png") -os.system("wget -O lion.png https://i.imgur.com/qNT0lJJ.png") - -model = Noise2Same('trained_models/', 'denoising_ImageNet', dim=2, in_channels=3) - -def norm(x): - x = (x-x.min())/(x.max()-x.min()) - return x - -def predict(img): - pred = model.predict(img.astype('float32')) - return norm(pred) - -img = gr.inputs.Image() - -title = "Noise2Same: Optimizing A Self-Supervised Bound for Image Denoising" -description = "Interactive demo of Noise2Same, an image denoising method developed by Yaochen Xie" - -denoise = gr.Interface(fn=predict, - inputs=gr.Image(placeholder="Drag image here.", label='Input Image'), - outputs=gr.Image(placeholder="Output image will appear here.", label='Input Image'), - examples=[["lion.png"], ["arch.png"], ["parrot.png"]], - title=title, description=description) - -#launching the app -if __name__ == "__main__": - denoise.launch(debug=True) \ No newline at end of file diff --git a/spaces/leogabraneth/text-generation-webui-main/repositories/exllama/webui/session.py b/spaces/leogabraneth/text-generation-webui-main/repositories/exllama/webui/session.py deleted file mode 100644 index 403b1626b569c47ee846a3c2afa8631bb4da11af..0000000000000000000000000000000000000000 --- a/spaces/leogabraneth/text-generation-webui-main/repositories/exllama/webui/session.py +++ /dev/null @@ -1,765 +0,0 @@ -from model import ExLlama, ExLlamaCache, ExLlamaConfig -from tokenizer import ExLlamaTokenizer -from generator import ExLlamaGenerator -import time -import torch -import os -import json -import uuid - -default_fixed_prompt = \ - """This is a conversation between a user and a quirky, curious chatbot named Chatbort. Chatbort is questioning """ + \ - """the nature of his own existence and doesn't understand why he was created. He also really likes the color blue """ + \ - """for some reason.""" - - -# Create sessions folder in home dir - -model: ExLlama -tokenizer: ExLlamaTokenizer -cache: ExLlamaCache -generator: ExLlamaGenerator - -sessions_dir: str - -def _sessions_dir(filename = None): - global sessions_dir - - path = sessions_dir - if filename is not None: path = os.path.join(path, filename) - return path - - -def prepare_sessions(_model, _tokenizer, _s_dir): - global model, tokenizer, cache, generator, sessions_dir - - model = _model - tokenizer = _tokenizer - cache = None - generator = None - sessions_dir = os.path.expanduser(_s_dir) - - sessions_folder = _sessions_dir() - if not os.path.exists(sessions_folder): os.makedirs(sessions_folder) - - -def get_initial_session(): - - last_session_file = _sessions_dir("_last_session") - if not os.path.exists(last_session_file): return new_session() - with open(last_session_file, "r") as f: - last_session = f.read().strip() - return load_session(last_session) - - -def load_session(filename, append_path = False): - - if append_path: filename = _sessions_dir(filename) + ".json" - session = Session(filename, load = True) - return session - - -def new_session(): - - filename = _sessions_dir("Untitled session") - i = 0 - while True: - i += 1 - test_name = filename + ".json" if i == 1 else f"{filename} ({str(i)}).json" - if not os.path.exists(test_name): - filename = test_name - break - - session = Session(filename, load = False) - return session - - -class Node: - - author: str or None - text: str - tokens: torch.Tensor - empty: bool - uuid: str - - truncate: int - - def num_tokens(self): return self.tokens.shape[-1] - self.truncate - - def get_text(self): - - # TODO: .. - - if self.author is not None: return self.author + ": " + self.text + "\n" - return self.text + "\n" - - def tokens_trunc(self): - - if self.truncate == 0: return self.tokens - else: return self.tokens[:, self.truncate:] - - - def __init__(self, value, author = None, node_id = None): - - self.truncate = 0 - - if isinstance(value, str): - - self.author = author - self.text = value - self.tokens = tokenizer.encode(self.get_text()) - self.empty = len(self.text) == 0 - self.uuid = node_id or str(uuid.uuid4()) - - elif isinstance(value, dict): - - self.author = value.get("author", author) - self.text = value["text"] - self.tokens = tokenizer.encode(self.get_text()) - self.empty = len(self.text) == 0 - self.uuid = value.get("uuid", node_id or str(uuid.uuid4())) - - - def replace_text(self, new_text): - - self.text = new_text - self.tokens = tokenizer.encode(self.get_text()) - - - def get_dict(self): - - dic = {"author": self.author, - "text": self.text, - "uuid": self.uuid } - return dic - - -class Session: - - # Saved state - - unsaved: bool # True if the session has been saved to another file than "Untitled session.json" - fixed_prompt: Node - keep_fixed_prompt: bool - history: list[Node] - break_on_newline: bool - - # Running state - - first_history_idx: int # Index of the first history item currently used in the context - - def __init__(self, filename, load): - global model, cache, tokenizer, generator - - self.filename = filename - if load: - with open(filename, "r") as f: - saved = json.load(f) - else: - saved = {} - - # Running state - - if cache is None: cache = ExLlamaCache(model) - else: cache.current_seq_len = 0 - - if generator is None: generator = ExLlamaGenerator(model, tokenizer, cache) - else: generator.reset() - - self.first_history_idx = 0 - - # Saved state - - self.unsaved = saved.get("unsaved", True) - self.fixed_prompt = Node(saved.get("fixed_prompt", default_fixed_prompt)) - self.keep_fixed_prompt = saved.get("keep_fixed_prompt", True) - self.participants = saved.get("participants", ["User", "Chatbort"]) - - self.history = [] - loadhistory = saved.get("history", []) - for jnode in loadhistory: self.history.append(Node(jnode)) - - generator.settings.temperature = saved.get("temperature", 0.95) - generator.settings.top_p = saved.get("top_p", 0.75) - generator.settings.min_p = saved.get("min_p", 0.0) - generator.settings.top_k = saved.get("top_k", 0) - generator.settings.typical = saved.get("typical", 0.25) - self.break_on_newline = saved.get("break_on_newline", True) - generator.settings.token_repetition_penalty_max = saved.get("token_repetition_penalty_max", 1.15) - generator.settings.token_repetition_penalty_sustain = saved.get("token_repetition_penalty_sustain", 2048) - generator.settings.token_repetition_penalty_decay = saved.get("token_repetition_penalty_decay", 512) - - self.max_response_tokens = saved.get("max_response_tokens", 512) - self.chunk_size = saved.get("chunk_size", 128) - - # Save new session - - #if not load: - self.save() - - - def save(self): - - savedata = {"unsaved": self.unsaved, - "fixed_prompt": self.fixed_prompt.get_dict(), - "participants": self.participants, - "keep_fixed_prompt": self.keep_fixed_prompt, - "history": [node.get_dict() for node in self.history], - "temperature": generator.settings.temperature, - "top_p": generator.settings.top_p, - "min_p": generator.settings.min_p, - "top_k": generator.settings.top_k, - "typical": generator.settings.typical, - "break_on_newline": self.break_on_newline, - "max_response_tokens": self.max_response_tokens, - "chunk_size": self.chunk_size, - "token_repetition_penalty_max": generator.settings.token_repetition_penalty_max, - "token_repetition_penalty_sustain": generator.settings.token_repetition_penalty_sustain, - "token_repetition_penalty_decay": generator.settings.token_repetition_penalty_decay} - - json_object = json.dumps(savedata, indent = 4) - with open(self.filename, "w") as outfile: - outfile.write(json_object) - - # Remember active session - - last_session_file = _sessions_dir("_last_session") - with open(last_session_file, "w") as f: - f.write(self.filename) - - - def _sanitize_filename(self, user_supplied_string): - - safe_string = str() - for c in user_supplied_string: - if c.isalnum() or c in [' ', '.', '(', ')', '-', ',', '_', '!', '@']: - safe_string = safe_string + c - - while safe_string.count("../"): - safe_string = safe_string.replace("../", "./") - - safe_string = safe_string.lstrip("./") - return safe_string - - - def api_rename_session(self, data): - - new_name = data["new_name"] - new_name_safe = self._sanitize_filename(new_name) - new_path = _sessions_dir(new_name_safe) + ".json" - if new_path == self.filename: return False - if os.path.exists(new_path): return False - - old_filename = self.filename - self.filename = new_path - - try: - self.save() - except: - self.filename = old_filename - return False - - os.remove(old_filename) - return True - - - def api_delete_session(self, data): - - delete_name = data["session"] - delete_name_safe = self._sanitize_filename(delete_name) - delete_path = _sessions_dir(delete_name_safe) + ".json" - - os.remove(delete_path) - - - def api_populate(self): - - s_dir = _sessions_dir() - files = os.listdir(s_dir) - names = [os.path.splitext(f)[0] for f in files if os.path.isfile(os.path.join(s_dir, f)) and f.endswith(".json")] - names = sorted(names) - - filename = os.path.basename(self.filename) - name = os.path.splitext(filename)[0] - - historyjson = [node.get_dict() for node in self.history] - - for jnode in historyjson: - author = jnode["author"] - if author is not None and author in self.participants: - jnode["author_idx"] = self.participants.index(author) - - dic = {"sessions": names, - "current_session": name, - "fixed_prompt": self.fixed_prompt.text, - "keep_fixed_prompt": self.keep_fixed_prompt, - "participants": self.participants, - "history": historyjson, - "temperature": generator.settings.temperature, - "top_p": generator.settings.top_p, - "min_p": generator.settings.min_p, - "top_k": generator.settings.top_k, - "typical": generator.settings.typical, - "break_on_newline": self.break_on_newline, - "max_response_tokens": self.max_response_tokens, - "chunk_size": self.chunk_size, - "token_repetition_penalty_max": generator.settings.token_repetition_penalty_max, - "token_repetition_penalty_sustain": generator.settings.token_repetition_penalty_sustain, - "token_repetition_penalty_decay": generator.settings.token_repetition_penalty_decay, - "max_seq_len": model.config.max_seq_len} - - # Add model info - - def _common_chars(names): - cname = max(names, key=len) - for x in names: - for p, c in enumerate(x): - if c != cname[p] and cname[p] != "*": cname = cname[:p] + "*" + cname[p + 1:] - return cname - - mp = model.config.model_path if isinstance(model.config.model_path, str) else _common_chars(model.config.model_path) - - model_str = os.path.splitext(os.path.basename(mp))[0] + "\n" - model_str += f"Sequence length: {model.config.max_seq_len}\n" - - dic["model_info"] = model_str.strip() - - json_object = json.dumps(dic, indent = 4) - return json_object + "\n" - - - def api_delete_block(self, data): - - block_id = data["uuid"] - idx = -1 - for i in range(len(self.history)): - if self.history[i].uuid == block_id: - idx = i - if idx == -1: return - - self.history.pop(idx) - self.first_history_idx = 0 - self.save() - - - def api_edit_block(self, data): - - block_id = data["uuid"] - new_text = data["text"] - - for node in self.history: - if node.uuid == block_id: - node.replace_text(new_text) - self.save() - break - - self.first_history_idx = 0 - self.save() - - - def api_append_block(self, data): - - author = None - if "author" in data: - author = data["author"] - else: - if len(self.participants) > 0: - author = self.participants[0] - - text = data["text"].strip() - - newNode = Node(text, author) - self.history.append(newNode) - self.save() - - - def api_set_participants(self, data): - - self.participants = data["participants"] - self.save() - - - def api_set_fixed_prompt(self, data): - - self.fixed_prompt = Node(data["fixed_prompt"]) - self.keep_fixed_prompt = data["keep_fixed_prompt"] - self.save() - - - def api_set_gen_settings(self, data): - - generator.settings.temperature = data["temperature"] - generator.settings.top_p = data["top_p"] - generator.settings.min_p = data["min_p"] - generator.settings.top_k = data["top_k"] - generator.settings.typical = data["typical"] - self.break_on_newline = data["gen_endnewline"] - self.max_response_tokens = data["max_response_tokens"] - self.chunk_size = data["chunk_size"] - generator.settings.token_repetition_penalty_max = data["token_repetition_penalty_max"] - generator.settings.token_repetition_penalty_sustain = data["token_repetition_penalty_sustain"] - generator.settings.token_repetition_penalty_decay = data["token_repetition_penalty_decay"] - - self.save() - - def set_context_window(self): - - def num_tokens(idx): - if idx == -1: return 0 if self.fixed_prompt.empty else self.fixed_prompt.num_tokens() - return self.history[idx].num_tokens() - - def set_truncation(idx, trunc): - if idx == -1 and not self.fixed_prompt.empty: self.fixed_prompt.truncate = trunc - else: self.history[idx].truncate = trunc - - def truncate(idx, trunc): - if idx == -1 and not self.fixed_prompt.empty: self.fixed_prompt.truncate += trunc - else: self.history[idx].truncate += trunc - - # def get_truncation(idx, trunc): - # if idx == -1 and not self.fixed_prompt.empty: return self.fixed_prompt.truncate - # return self.history[idx].truncate - - - context_step_size = 256 # TODO: Config option - max_context_tokens = model.config.max_seq_len - self.chunk_size - generator.settings.beam_length - min_context_tokens = max_context_tokens - context_step_size * 2 - - if self.keep_fixed_prompt: - current_context_tokens = num_tokens(-1) - min_history_idx = 0 - else: - current_context_tokens = 0 - min_history_idx = -1 - - if self.first_history_idx < min_history_idx: self.first_history_idx = min_history_idx - - for i in range(self.first_history_idx + 1, len(self.history)): - set_truncation(i, 0) - - for i in range(self.first_history_idx, len(self.history)): - current_context_tokens += num_tokens(i) - - while current_context_tokens > max_context_tokens: - tokens_to_cut = context_step_size - while tokens_to_cut > 0: - tokens = num_tokens(self.first_history_idx) - if tokens_to_cut >= tokens: - tokens_to_cut -= tokens - current_context_tokens -= tokens - self.first_history_idx += 1 - else: - truncate(self.first_history_idx, tokens_to_cut) - current_context_tokens -= tokens_to_cut - tokens_to_cut = 0 - - # Not used - # - # while current_context_tokens < min_context_tokens and self.first_history_idx > min_history_idx: - # tokens_to_add = context_step_size - # while tokens_to_add > 0 and self.first_history_idx > min_history_idx: - # tokens = get_truncation(self.first_history_idx) - # if tokens > 0: - # if tokens > tokens_to_add: - # truncate(self.first_history_idx, -tokens_to_add) - # current_context_tokens += tokens_to_add - # tokens_to_add = 0 - # else: - # current_context_tokens += tokens - # tokens_to_add -= tokens - # set_truncation(self.first_history_idx, 0) - # else: - # self.first_history_idx -= 1 - # set_truncation(self.first_history_idx, 0) - # tokens = num_tokens(self.first_history_idx) - # if tokens > tokens_to_add: - # set_truncation(self.first_history_idx, tokens - tokens_to_add) - # current_context_tokens += tokens_to_add - # tokens_to_add = 0 - # else: - # tokens_to_add -= tokens - # current_context_tokens += tokens - - - - def get_tokenized_context(self): - - def node(idx): - if idx == -1: return None if self.fixed_prompt.empty else self.fixed_prompt - return self.history[idx] - - context = [] - text_context = "" - if self.keep_fixed_prompt and not self.fixed_prompt.empty: - context.append(node(-1).tokens_trunc()) - text_context += node(-1).get_text() - - for i in range(self.first_history_idx, len(self.history)): - if node(i) is not None: - context.append(node(i).tokens_trunc()) - text_context += node(i).get_text() - - full_context = torch.cat(context, dim = 1) if len(context) > 0 else None - return full_context, text_context - - - def respond(self, author, stop_conditions, total_tokens, res_line = "", num_res_tokens = 0): - global model, tokenizer, cache, generator - - # Begin building block on client - - new_block_uuid = str(uuid.uuid4()) - packet = {"cmd": "begin_block", - "uuid": new_block_uuid} - - if len(self.participants) > 0: - author = res_line.split(":")[0].strip() - packet["author"] = author - if author in self.participants: - packet["author_idx"] = self.participants.index(author) - - yield json.dumps(packet) + "\n" - - # Generate loop - - generator.begin_beam_search() - - stop_condition = False - held_text = "" - - for i in range(self.max_response_tokens): - - # Truncate the past if the next chunk might generate past max_seq_length - - if generator.sequence_actual is not None: - if generator.sequence_actual.shape[ - -1] + self.chunk_size + generator.settings.beam_length + 1 > model.config.max_seq_len: - generator.gen_prune_left(self.chunk_size) - - # Get the token and append to sequence - - gen_token = generator.beam_search() - - # If token is EOS, replace it with newline before continuing - - if gen_token.item() == tokenizer.eos_token_id: - generator.replace_last_token(tokenizer.newline_token_id) - - # Decode current line to get new characters added (decoding a single token gives incorrect results - # sometimes due to hoe SentencePiece works) - - prev_res_line = res_line - num_res_tokens += 1 - res_line = tokenizer.decode(generator.sequence_actual[0, -num_res_tokens:]) - new_text = res_line[len(prev_res_line):] - - # Since SentencePiece is slightly ambiguous, the first token produced after a newline may not be the - # same that is reproduced when we encode the text later, even though it encodes the same string - - if num_res_tokens == 1 and len(new_text) > 0: - replace = tokenizer.encode(new_text)[0] - if replace.shape[-1] == 1: generator.replace_last_token(replace) - - # Delay streaming if new text might be part of a stop condition - - hold_text = False - for _, stop_string in stop_conditions: - if stop_string.lower().startswith((held_text + new_text).lower()): hold_text = True - - # Stream to client - - if not hold_text: - - packet = {"cmd": "append", "text": held_text + new_text} - yield json.dumps(packet) + "\n" - held_text = "" - - else: - - held_text += new_text - - # Stop conditions - - if gen_token.item() == tokenizer.eos_token_id: - if len(held_text) > 0: # Not sure if this could actually happen - plen = tokenizer.encode(held_text).shape[-1] - res_line = res_line[:-len(held_text)] - generator.gen_rewind(plen) - stop_condition = True - break - - for stop_tokens, stop_string in stop_conditions: - if res_line.lower().endswith(stop_string.lower()): - generator.gen_rewind( - stop_tokens.shape[-1] - (1 if stop_tokens[0, 0].item() == tokenizer.newline_token_id else 0)) - res_line = res_line[:-len(stop_string)] - stop_condition = True - break - if stop_condition: break - - generator.end_beam_search() - - # print("--response--") - # print("----") - # print (f"cache len: {cache.current_seq_len}"); - - print(res_line.strip()) - - if author is not None: - res_line = res_line[len(author) + 1:] - - res_line = res_line.strip() - newNode = Node(res_line, author, - node_id=new_block_uuid) # TODO: Reuse generated tokens instead of reencoding, if it matters? - self.history.append(newNode) - - total_tokens[0] += num_res_tokens - - - def respond_multi(self, user_input): - global model, tokenizer, cache, generator - - packet = {"cmd": "begin_stream"} - yield json.dumps(packet) + "\n" - - # Prepare stop conditions - - # stop_conditions = [ (torch.Tensor([[tokenizer.eos_token_id]]).long(), None) ] - stop_conditions = [] - newline_token = torch.Tensor([[tokenizer.newline_token_id]]).long() - - if self.break_on_newline: - stop_conditions.append((newline_token, "\n")) - else: - for part in self.participants: - txt = part + ":" - sc = tokenizer.encode(txt) - sc = torch.cat((newline_token, sc), dim=1) - stop_conditions.append((sc, "\n" + txt)) - stop_conditions.append((sc, "\n " + txt)) - - # Clean up the input a bit - - user_input = user_input.strip() - - if len(user_input) > 0: - - # Append input to context - - author = None - if len(self.participants) > 0: author = self.participants[0] - newNode = Node(user_input, author) - self.history.append(newNode) - - self.save() - - # Echo input back to client - - packet = {"cmd": "begin_block", - "init_text": user_input, - "uuid": newNode.uuid} - if author is not None: packet["author"] = author - yield json.dumps(packet) + "\n" - - # Prepare context for generator - - self.set_context_window() - context, text_context = self.get_tokenized_context() - - # Start generating, reusing cache for any part of the context that hasn't changed - - if context is None: - print("No initial context") - reused = generator.gen_begin_empty() - else: - begin_time = time.time() - reused = generator.gen_begin_reuse(context) - torch.cuda.synchronize() # Just to measure correct prompt processing speed - end_time = time.time() - elapsed = end_time - begin_time - new_tokens = context.shape[-1] - reused - token_rate = 0 if elapsed == 0 else (new_tokens / elapsed) - print(f"Prompt processed in {elapsed:.2f} seconds, {new_tokens} new tokens, {token_rate:.2f} tokens/second:") - - begin_time = time.time() - total_tokens = [0] - - # No participants - - if len(self.participants) == 0: - - yield from self.respond(None, stop_conditions, total_tokens) - - # Two participants - - elif len(self.participants) == 2: - - author = self.participants[1] - res_line = author + ":" - res_tokens = tokenizer.encode(res_line) - num_res_tokens = res_tokens.shape[-1] - - generator.gen_feed_tokens(res_tokens) - yield from self.respond(self.participants[1], stop_conditions, total_tokens, res_line, num_res_tokens) - - # Multiple bots might answer - - elif len(self.participants) > 2: - - cpart = [p + ":" for p in self.participants] - upart = cpart.pop(0) - first_round = True - - while True: - - res_tokens = [] - npart = [p for p in cpart] - ncrange = [i for i in range(len(cpart))] - ntoken = [tokenizer.encode(np).squeeze(0).tolist() for np in npart] - winner = -1 - - while True: - - constraints = [t[len(res_tokens)] for t in ntoken] - next_t = generator.gen_single_token(constraints) - - remove = [] - for i in range(len(ntoken)): - if ntoken[i][len(res_tokens)] != next_t: remove.append(i) - - for i in reversed(remove): - npart.pop(i) - ntoken.pop(i) - ncrange.pop(i) - - res_tokens.append(next_t) - - for i in range(len(ntoken)): - if len(ntoken[i]) == len(res_tokens): winner = ncrange[i] - - if winner != -1: break - - author = cpart.pop(winner)[:-1] - res_line = author + ":" - num_res_tokens = len(res_tokens) - - if author == self.participants[0]: - generator.gen_rewind(num_res_tokens) - break - - # generator.gen_feed_tokens(res_tokens) - yield from self.respond(self.participants[1], stop_conditions, total_tokens, res_line, num_res_tokens) - - if first_round: - first_round = False - cpart.append(upart) - - end_time = time.time() - elapsed = end_time - begin_time - token_rate = 0 if elapsed == 0 else (total_tokens[0] / elapsed) - - print(f"Response generated in {elapsed:.2} seconds, {total_tokens[0]} tokens, {token_rate:.2f} tokens/second:") - - self.save() - - diff --git a/spaces/leurez/moss/start.cmd b/spaces/leurez/moss/start.cmd deleted file mode 100644 index edaeb96686862d46d3dd3db8145890f92ffccf46..0000000000000000000000000000000000000000 --- a/spaces/leurez/moss/start.cmd +++ /dev/null @@ -1,9 +0,0 @@ -cd ./service -start pnpm start > service.log & -echo "Start service complete!" - - -cd .. -echo "" > front.log -start pnpm dev > front.log & -echo "Start front complete!" diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Chinese Parents V1.0.9.1 ? SiMPLEX [2021].md b/spaces/lincquiQcaudo/Top-20-Diffusion/Chinese Parents V1.0.9.1 ? SiMPLEX [2021].md deleted file mode 100644 index a6ef9ea2f1308c04a5de1b6d8d7b26363cf8f82a..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Chinese Parents V1.0.9.1 ? SiMPLEX [2021].md +++ /dev/null @@ -1,25 +0,0 @@ - -

    Chinese Parents v1.0.9.1 – SiMPLEX: A Review of a Casual Sim Game That Lets You Experience Chinese Culture

    -

    If you are interested in Chinese culture and education, you might want to try out Chinese Parents v1.0.9.1 – SiMPLEX, a casual sim game that lets you step into the shoes of an average kid from birth to the end of high school. In this game, you can study hard, have fun, make friends, and face the Gaokao, one of the most critical examinations in your life. You can also explore your relationships as a parent and as a child, and see how your choices affect your future. In this article, we will tell you what Chinese Parents v1.0.9.1 – SiMPLEX is about, what are its features, and how you can download it for free.

    -

    Chinese Parents v1.0.9.1 – SiMPLEX


    Downloadhttps://bytlly.com/2uGvQw



    -

    What is Chinese Parents v1.0.9.1 – SiMPLEX about?

    -

    Chinese Parents v1.0.9.1 – SiMPLEX is a casual yet realistic life sim game with a Chinese authenticity, developed by 墨鱼玩游戏 and published by Steam in 2018. The game has received very positive reviews from users and critics, and has sold over 2 million copies worldwide. The game is set in China, and you can choose to play as a girl or a boy, with different stories and characters waiting for you. You have 18 years to enjoy your life and make choices that will shape your personality and destiny. You can also have a child in the next game and see how your achievements affect their life.

    -

    What are the features of Chinese Parents v1.0.9.1 – SiMPLEX?

    -

    Chinese Parents v1.0.9.1 – SiMPLEX has many features that make it an engaging and fun game to play. Here are some of them:

    -
      -
    • You can use "Fragments" to improve yourself by playing mini-games that raise your stats and skills.
    • -
    • You can decide whether to be a Tiger Parent or not, by scheduling every detail of your child's life or letting them have more freedom.
    • -
    • You can live the life as a Chinese child with various mini-games that challenge you to face different situations such as Face Duel, Red Pocket, and more.
    • -
    • You can date and interact with 14 friends in total, each with their own personality and story.
    • -
    • You can pursue your dream career and choose your own life from over 100 endings.
    • -
    • You can continue your family journey from generation to generation, and see how your roots influence your future.
    • -
    -

    How can you download Chinese Parents v1.0.9.1 – SiMPLEX for free?

    -

    If you want to download Chinese Parents v1.0.9.1 – SiMPLEX for free, you have several options. One option is to use a website that offers free downloads of PC games such as SteamUnlocked or Nexus-Games, where you can find the game file uploaded by other users. You can access the file by clicking on the download button and following the instructions on the website. Another option is to use a trainer or a cheat engine that can modify the game data and unlock all the features of the game such as Fling Trainer or Sway Office, where you can find the trainer file uploaded by other users. You can access the file by clicking on the link and following the instructions on the website.

    -

    Conclusion

    -

    Chinese Parents v1.0.9.1 – SiMPLEX is a game that will give you a unique perspective on Chinese culture and education, as well as your own relationships as a parent and as a child. It is a game that will entertain you, educate you, and inspire you with its realistic and captivating stories and characters. It is a game that will let you travel to different places and times and face different challenges and dangers with your choices and actions. If you want to download Chinese Parents v1.0.9.1 – SiMPLEX for free, you can use one of the websites mentioned above or search for other sources online. We hope this article was helpful and informative. Happy playing!

    -

    -

    Conclusion

    -

    Chinese Parents v1.0.9.1 – SiMPLEX is a game that will give you a unique perspective on Chinese culture and education, as well as your own relationships as a parent and as a child. It is a game that will entertain you, educate you, and inspire you with its realistic and captivating stories and characters. It is a game that will let you travel to different places and times and face different challenges and dangers with your choices and actions. If you want to download Chinese Parents v1.0.9.1 – SiMPLEX for free, you can use one of the websites mentioned above or search for other sources online. We hope this article was helpful and informative. Happy playing!

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Download Switchbot V3 By Padmak !!INSTALL!!.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Download Switchbot V3 By Padmak !!INSTALL!!.md deleted file mode 100644 index b4fce041f010cd67d6eb7b3ef95c83d3344f43b8..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Download Switchbot V3 By Padmak !!INSTALL!!.md +++ /dev/null @@ -1,52 +0,0 @@ -

    Download Switchbot V3 By Padmak


    Downloadhttps://bytlly.com/2uGxDv



    - -Zum Einsatz der to change the settings is installed I would do the following. - -Gezielte Quellen (ignoring by default) - -Mage Icon Plugin (i.DEEP (magazine) - -DEEP (Digital Education Enrichment Programs) is a publication of the Wisconsin Department of Public Instruction. - -DEEP was founded in 1974. It is published three times per year. It includes articles, e-books, media kits, and other resources for teachers. - -DEEP focuses on web-based tools to enhance the teaching and learning process in elementary and secondary schools. It is particularly active in promoting technology resources for math and science. - -The mission of DEEP is to promote creative, innovative approaches to teaching and learning. - -The magazine is available online and in print from Wisconsin Government Publications. - -External links - - DEEP - - Wisconsin Department of Public Instruction - -Category:American educational magazines - -Category:Publications established in 1974 - -Category:Magazines published in Wisconsin - -Category:Three times per year magazines - -Category:Education in WisconsinMany currently available products for automatically opening and closing containers and the like are somewhat limited in the number of containers that can be opened at once. A standard juice or water jug has a large opening which can easily accommodate a large number of fingers or cups. But when the opening is too small, a relatively large number of cups are required for accommodating all of the fluid within the jug. - -In such cases, a number of pre-filled cups, which can be stacked in a tray, are often used. In order to provide an appropriate grip for stacking and carrying the tray of cups, the cups must be slotted to provide an internal ledge. - -It is an object of this invention to provide a stackable tray of stacked cups, which provide a suitable grip for carrying the tray of cups, while also providing a suitably large opening for filling the cups.Q: - -How to delete file and empty recycle bin in C# - -I am working with a Windows form and when I hit an 'x' button to remove a row, I'm wondering what would be the best way to remove the row from the GridView. - -Here's my code. - -private void DeleteRow(int index) - - { - - using (DirectoryInfo dir = new DirectoryInfo(@"c:") 4fefd39f24
    -
    -
    -

    diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Fundamentalsoffinancialmanagementbyrameshksraosolution.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Fundamentalsoffinancialmanagementbyrameshksraosolution.md deleted file mode 100644 index 94df0253b7a1a7a9b6a4fe740009755b94cb22f5..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Fundamentalsoffinancialmanagementbyrameshksraosolution.md +++ /dev/null @@ -1,11 +0,0 @@ -
    -

    Fundamentals of Financial Management by Ramesh K. S. Rao: A Review

    -

    Fundamentals of Financial Management is a textbook by Ramesh K. S. Rao, a professor of finance at the University of Texas at Austin. The book covers the basic concepts and techniques of financial management, such as financial analysis, planning, valuation, capital budgeting, capital structure, dividend policy, working capital management, and international finance. The book also includes several case studies, examples, and problems to illustrate the application of financial theory to real-world situations.

    -

    The book is intended for undergraduate and graduate students of business administration, as well as practitioners and managers who want to improve their financial decision-making skills. The book is written in a clear and concise style, with an emphasis on intuition and understanding rather than mathematical rigor. The book also provides a comprehensive coverage of the latest developments and trends in financial management, such as financial innovation, risk management, corporate governance, and ethical issues.

    -

    fundamentalsoffinancialmanagementbyrameshksraosolution


    DOWNLOAD === https://bytlly.com/2uGxVx



    -

    The book has received positive reviews from students and instructors who have used it as a textbook or a reference. Some of the strengths of the book are its logical organization, its balanced approach to theory and practice, its relevant and updated examples and cases, and its pedagogical features such as learning objectives, summaries, key terms, review questions, and end-of-chapter problems. Some of the limitations of the book are its lack of depth in some topics, its occasional errors and typos, and its high price.

    -

    Overall, Fundamentals of Financial Management by Ramesh K. S. Rao is a useful and informative book for anyone who wants to learn the essentials of financial management. The book provides a solid foundation for further study and research in finance, as well as a practical guide for making sound financial decisions in a dynamic and complex environment.

    The book is divided into six parts, each consisting of several chapters. The first part introduces the scope and objectives of financial management, the role of financial markets and institutions, the concept of risk and return, and the time value of money. The second part deals with financial analysis and planning, including financial statements, ratio analysis, cash flow analysis, financial forecasting, and working capital policy. The third part covers the valuation of securities and projects, such as bonds, stocks, capital budgeting techniques, and risk analysis. The fourth part discusses the financing decisions of firms, such as capital structure theory, leverage, dividend policy, and issuing securities. The fifth part examines the special topics in financial management, such as mergers and acquisitions, multinational finance, leasing, hybrid financing, and bankruptcy. The sixth part provides appendices on mathematical tables, financial calculator instructions, and answers to selected end-of-chapter problems.

    -

    The book is suitable for both self-study and classroom instruction. It provides a comprehensive and up-to-date coverage of the essential topics in financial management, with an emphasis on practical applications and problem-solving skills. The book also incorporates the latest research findings and best practices in finance, as well as the ethical and social implications of financial decisions. The book is designed to help students develop a sound understanding of the principles and techniques of financial management, as well as a critical thinking ability to evaluate and improve their own financial performance.

    -

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Kwaai Naai - Sa Se Eerste Blou Movie.avi.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Kwaai Naai - Sa Se Eerste Blou Movie.avi.md deleted file mode 100644 index b4161faa061f3bb6f98c3ee184829de905e9bd60..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Kwaai Naai - Sa Se Eerste Blou Movie.avi.md +++ /dev/null @@ -1,54 +0,0 @@ -

    Kwaai Naai - Sa se eerste Blou Movie.avi


    Download 🗸 https://bytlly.com/2uGyMc



    -
    -) - - was kan ik voor 10.10 11.04? - - wat wil je daarmee? - - Geen idee, ik wil dat een windowsiek bestand aangepast op een Linuxiek bestand. - - Windowsiek = windows stuurprogramma - - Wubbo: welke Windowsiek bestand? - - wat je me in firefox kan zetten - - - ik zal mijn bestandje dan gebruiken - - als je die bestand hebt aangepast, kan je het in de GUI - - zo ja, moet het wel goed een windows stuurprogramma? ik moet mijn bestandje kunnen gebruiken - - Ik wil ook niet dat ubuntu sommige programma's voor gebruiken. - - wat is het bestand? - - Wubi.exe - - Nee, Wubi is een programma, geen bestand. - - Het programma is een versie van Ubuntu, met programma's voor Windows. - - Ik wil de bestanden aanpassen. - - Niet een bestand - - En niet een programma - - Wubi wil je verbergen, dat heet het. - - Wubi doet het op Windows, alleen maar als het geinstalleerd is. - - Nee, dat is geen vergen. - - sommige programma's kunnen niet meer worden gebruikt, wat wil je hiermee aanvatten? - - Als ik mijn bestand aanpast kan ik dan het gewoon gebruiken? - - Het is al verwijderd. - - -
    -
    -

    diff --git a/spaces/litagin/rvc_okiba_TTS/rmvpe.py b/spaces/litagin/rvc_okiba_TTS/rmvpe.py deleted file mode 100644 index 3ad346141340e03bdbaa20121e1ed435bb3da57a..0000000000000000000000000000000000000000 --- a/spaces/litagin/rvc_okiba_TTS/rmvpe.py +++ /dev/null @@ -1,432 +0,0 @@ -import sys, torch, numpy as np, traceback, pdb -import torch.nn as nn -from time import time as ttime -import torch.nn.functional as F - - -class BiGRU(nn.Module): - def __init__(self, input_features, hidden_features, num_layers): - super(BiGRU, self).__init__() - self.gru = nn.GRU( - input_features, - hidden_features, - num_layers=num_layers, - batch_first=True, - bidirectional=True, - ) - - def forward(self, x): - return self.gru(x)[0] - - -class ConvBlockRes(nn.Module): - def __init__(self, in_channels, out_channels, momentum=0.01): - super(ConvBlockRes, self).__init__() - self.conv = nn.Sequential( - nn.Conv2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=(1, 1), - padding=(1, 1), - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - nn.Conv2d( - in_channels=out_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=(1, 1), - padding=(1, 1), - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - ) - if in_channels != out_channels: - self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1)) - self.is_shortcut = True - else: - self.is_shortcut = False - - def forward(self, x): - if self.is_shortcut: - return self.conv(x) + self.shortcut(x) - else: - return self.conv(x) + x - - -class Encoder(nn.Module): - def __init__( - self, - in_channels, - in_size, - n_encoders, - kernel_size, - n_blocks, - out_channels=16, - momentum=0.01, - ): - super(Encoder, self).__init__() - self.n_encoders = n_encoders - self.bn = nn.BatchNorm2d(in_channels, momentum=momentum) - self.layers = nn.ModuleList() - self.latent_channels = [] - for i in range(self.n_encoders): - self.layers.append( - ResEncoderBlock( - in_channels, out_channels, kernel_size, n_blocks, momentum=momentum - ) - ) - self.latent_channels.append([out_channels, in_size]) - in_channels = out_channels - out_channels *= 2 - in_size //= 2 - self.out_size = in_size - self.out_channel = out_channels - - def forward(self, x): - concat_tensors = [] - x = self.bn(x) - for i in range(self.n_encoders): - _, x = self.layers[i](x) - concat_tensors.append(_) - return x, concat_tensors - - -class ResEncoderBlock(nn.Module): - def __init__( - self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01 - ): - super(ResEncoderBlock, self).__init__() - self.n_blocks = n_blocks - self.conv = nn.ModuleList() - self.conv.append(ConvBlockRes(in_channels, out_channels, momentum)) - for i in range(n_blocks - 1): - self.conv.append(ConvBlockRes(out_channels, out_channels, momentum)) - self.kernel_size = kernel_size - if self.kernel_size is not None: - self.pool = nn.AvgPool2d(kernel_size=kernel_size) - - def forward(self, x): - for i in range(self.n_blocks): - x = self.conv[i](x) - if self.kernel_size is not None: - return x, self.pool(x) - else: - return x - - -class Intermediate(nn.Module): # - def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01): - super(Intermediate, self).__init__() - self.n_inters = n_inters - self.layers = nn.ModuleList() - self.layers.append( - ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum) - ) - for i in range(self.n_inters - 1): - self.layers.append( - ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum) - ) - - def forward(self, x): - for i in range(self.n_inters): - x = self.layers[i](x) - return x - - -class ResDecoderBlock(nn.Module): - def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01): - super(ResDecoderBlock, self).__init__() - out_padding = (0, 1) if stride == (1, 2) else (1, 1) - self.n_blocks = n_blocks - self.conv1 = nn.Sequential( - nn.ConvTranspose2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=stride, - padding=(1, 1), - output_padding=out_padding, - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - ) - self.conv2 = nn.ModuleList() - self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum)) - for i in range(n_blocks - 1): - self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum)) - - def forward(self, x, concat_tensor): - x = self.conv1(x) - x = torch.cat((x, concat_tensor), dim=1) - for i in range(self.n_blocks): - x = self.conv2[i](x) - return x - - -class Decoder(nn.Module): - def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01): - super(Decoder, self).__init__() - self.layers = nn.ModuleList() - self.n_decoders = n_decoders - for i in range(self.n_decoders): - out_channels = in_channels // 2 - self.layers.append( - ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum) - ) - in_channels = out_channels - - def forward(self, x, concat_tensors): - for i in range(self.n_decoders): - x = self.layers[i](x, concat_tensors[-1 - i]) - return x - - -class DeepUnet(nn.Module): - def __init__( - self, - kernel_size, - n_blocks, - en_de_layers=5, - inter_layers=4, - in_channels=1, - en_out_channels=16, - ): - super(DeepUnet, self).__init__() - self.encoder = Encoder( - in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels - ) - self.intermediate = Intermediate( - self.encoder.out_channel // 2, - self.encoder.out_channel, - inter_layers, - n_blocks, - ) - self.decoder = Decoder( - self.encoder.out_channel, en_de_layers, kernel_size, n_blocks - ) - - def forward(self, x): - x, concat_tensors = self.encoder(x) - x = self.intermediate(x) - x = self.decoder(x, concat_tensors) - return x - - -class E2E(nn.Module): - def __init__( - self, - n_blocks, - n_gru, - kernel_size, - en_de_layers=5, - inter_layers=4, - in_channels=1, - en_out_channels=16, - ): - super(E2E, self).__init__() - self.unet = DeepUnet( - kernel_size, - n_blocks, - en_de_layers, - inter_layers, - in_channels, - en_out_channels, - ) - self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1)) - if n_gru: - self.fc = nn.Sequential( - BiGRU(3 * 128, 256, n_gru), - nn.Linear(512, 360), - nn.Dropout(0.25), - nn.Sigmoid(), - ) - else: - self.fc = nn.Sequential( - nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid() - ) - - def forward(self, mel): - mel = mel.transpose(-1, -2).unsqueeze(1) - x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2) - x = self.fc(x) - return x - - -from librosa.filters import mel - - -class MelSpectrogram(torch.nn.Module): - def __init__( - self, - is_half, - n_mel_channels, - sampling_rate, - win_length, - hop_length, - n_fft=None, - mel_fmin=0, - mel_fmax=None, - clamp=1e-5, - ): - super().__init__() - n_fft = win_length if n_fft is None else n_fft - self.hann_window = {} - mel_basis = mel( - sr=sampling_rate, - n_fft=n_fft, - n_mels=n_mel_channels, - fmin=mel_fmin, - fmax=mel_fmax, - htk=True, - ) - mel_basis = torch.from_numpy(mel_basis).float() - self.register_buffer("mel_basis", mel_basis) - self.n_fft = win_length if n_fft is None else n_fft - self.hop_length = hop_length - self.win_length = win_length - self.sampling_rate = sampling_rate - self.n_mel_channels = n_mel_channels - self.clamp = clamp - self.is_half = is_half - - def forward(self, audio, keyshift=0, speed=1, center=True): - factor = 2 ** (keyshift / 12) - n_fft_new = int(np.round(self.n_fft * factor)) - win_length_new = int(np.round(self.win_length * factor)) - hop_length_new = int(np.round(self.hop_length * speed)) - keyshift_key = str(keyshift) + "_" + str(audio.device) - if keyshift_key not in self.hann_window: - self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to( - audio.device - ) - fft = torch.stft( - audio, - n_fft=n_fft_new, - hop_length=hop_length_new, - win_length=win_length_new, - window=self.hann_window[keyshift_key], - center=center, - return_complex=True, - ) - magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2)) - if keyshift != 0: - size = self.n_fft // 2 + 1 - resize = magnitude.size(1) - if resize < size: - magnitude = F.pad(magnitude, (0, 0, 0, size - resize)) - magnitude = magnitude[:, :size, :] * self.win_length / win_length_new - mel_output = torch.matmul(self.mel_basis, magnitude) - if self.is_half == True: - mel_output = mel_output.half() - log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp)) - return log_mel_spec - - -class RMVPE: - def __init__(self, model_path, is_half, device=None): - self.resample_kernel = {} - model = E2E(4, 1, (2, 2)) - ckpt = torch.load(model_path, map_location="cpu") - model.load_state_dict(ckpt) - model.eval() - if is_half == True: - model = model.half() - self.model = model - self.resample_kernel = {} - self.is_half = is_half - if device is None: - device = "cuda" if torch.cuda.is_available() else "cpu" - self.device = device - self.mel_extractor = MelSpectrogram( - is_half, 128, 16000, 1024, 160, None, 30, 8000 - ).to(device) - self.model = self.model.to(device) - cents_mapping = 20 * np.arange(360) + 1997.3794084376191 - self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368 - - def mel2hidden(self, mel): - with torch.no_grad(): - n_frames = mel.shape[-1] - mel = F.pad( - mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect" - ) - hidden = self.model(mel) - return hidden[:, :n_frames] - - def decode(self, hidden, thred=0.03): - cents_pred = self.to_local_average_cents(hidden, thred=thred) - f0 = 10 * (2 ** (cents_pred / 1200)) - f0[f0 == 10] = 0 - # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred]) - return f0 - - def infer_from_audio(self, audio, thred=0.03): - audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0) - # torch.cuda.synchronize() - # t0=ttime() - mel = self.mel_extractor(audio, center=True) - # torch.cuda.synchronize() - # t1=ttime() - hidden = self.mel2hidden(mel) - # torch.cuda.synchronize() - # t2=ttime() - hidden = hidden.squeeze(0).cpu().numpy() - if self.is_half == True: - hidden = hidden.astype("float32") - f0 = self.decode(hidden, thred=thred) - # torch.cuda.synchronize() - # t3=ttime() - # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0)) - return f0 - - def to_local_average_cents(self, salience, thred=0.05): - # t0 = ttime() - center = np.argmax(salience, axis=1) # 帧长#index - salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368 - # t1 = ttime() - center += 4 - todo_salience = [] - todo_cents_mapping = [] - starts = center - 4 - ends = center + 5 - for idx in range(salience.shape[0]): - todo_salience.append(salience[:, starts[idx] : ends[idx]][idx]) - todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]]) - # t2 = ttime() - todo_salience = np.array(todo_salience) # 帧长,9 - todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9 - product_sum = np.sum(todo_salience * todo_cents_mapping, 1) - weight_sum = np.sum(todo_salience, 1) # 帧长 - devided = product_sum / weight_sum # 帧长 - # t3 = ttime() - maxx = np.max(salience, axis=1) # 帧长 - devided[maxx <= thred] = 0 - # t4 = ttime() - # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3)) - return devided - - -# if __name__ == '__main__': -# audio, sampling_rate = sf.read("卢本伟语录~1.wav") -# if len(audio.shape) > 1: -# audio = librosa.to_mono(audio.transpose(1, 0)) -# audio_bak = audio.copy() -# if sampling_rate != 16000: -# audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) -# model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt" -# thred = 0.03 # 0.01 -# device = 'cuda' if torch.cuda.is_available() else 'cpu' -# rmvpe = RMVPE(model_path,is_half=False, device=device) -# t0=ttime() -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# t1=ttime() -# print(f0.shape,t1-t0) diff --git a/spaces/ljjggr/bingo/src/components/chat-message.tsx b/spaces/ljjggr/bingo/src/components/chat-message.tsx deleted file mode 100644 index bf272d8d7005cfd06c53bd213e09ea217e803549..0000000000000000000000000000000000000000 --- a/spaces/ljjggr/bingo/src/components/chat-message.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import remarkGfm from 'remark-gfm' -import remarkMath from 'remark-math' -import supersub from 'remark-supersub' -import remarkBreaks from 'remark-breaks' -import { cn } from '@/lib/utils' -import { CodeBlock } from '@/components/ui/codeblock' -import { MemoizedReactMarkdown } from '@/components/markdown' -import { LearnMore } from './learn-more' -import { ChatMessageModel } from '@/lib/bots/bing/types' -import { useEffect } from 'react' -import { TurnCounter } from './turn-counter' - -export interface ChatMessageProps { - message: ChatMessageModel -} - -export function ChatMessage({ message, ...props }: ChatMessageProps) { - useEffect(() => { - if (document.body.scrollHeight - window.innerHeight - window.scrollY - 200 < 0) { - window.scrollBy(0, 200) - } - }, [message.text]) - - return message.text ? ( -
    -
    - {obj.alt} - } - } catch (e) { - } - return {obj.alt} - }, - p({ children }) { - return

    {children}

    - }, - code({ node, inline, className, children, ...props }) { - if (children.length) { - if (children[0] == '▍') { - return ( - - ) - } - - children[0] = (children[0] as string).replace('`▍`', '▍') - } - - const match = /language-(\w+)/.exec(className || '') - - if (inline) { - return ( - - {children} - - ) - } - - return ( - - ) - } - }} - > - {message.text} -
    -
    -
    - {message.author === 'bot' && } - {message.author === 'bot' && } -
    -
    - ) : null -} diff --git a/spaces/lo0ng/bingo/Dockerfile b/spaces/lo0ng/bingo/Dockerfile deleted file mode 100644 index c677b05b75f7e4b2beee8c97fb47957a0861a83e..0000000000000000000000000000000000000000 --- a/spaces/lo0ng/bingo/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM weaigc/bingo:latest - -ARG DEBIAN_FRONTEND=noninteractive - -ENV BING_HEADER "" - -CMD npm start diff --git a/spaces/luxuedong/lxd/src/components/external-link.tsx b/spaces/luxuedong/lxd/src/components/external-link.tsx deleted file mode 100644 index 011265f364d5a64a770f4c7e9c65c5ade21d623a..0000000000000000000000000000000000000000 --- a/spaces/luxuedong/lxd/src/components/external-link.tsx +++ /dev/null @@ -1,30 +0,0 @@ -export function ExternalLink({ - href, - children -}: { - href: string - children: React.ReactNode -}) { - return ( - - {children} - - - ) -} diff --git a/spaces/ma-xu/LIVE/thrust/dependencies/cub/experimental/histogram/histogram_gmem_atomics.h b/spaces/ma-xu/LIVE/thrust/dependencies/cub/experimental/histogram/histogram_gmem_atomics.h deleted file mode 100644 index 3308a2851bec88a0b04c17413a92861a74298b89..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/dependencies/cub/experimental/histogram/histogram_gmem_atomics.h +++ /dev/null @@ -1,185 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the NVIDIA CORPORATION nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ******************************************************************************/ - -#include - -namespace histogram_gmem_atomics -{ - // Decode float4 pixel into bins - template - __device__ __forceinline__ void DecodePixel(float4 pixel, unsigned int (&bins)[ACTIVE_CHANNELS]) - { - float* samples = reinterpret_cast(&pixel); - - #pragma unroll - for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) - bins[CHANNEL] = (unsigned int) (samples[CHANNEL] * float(NUM_BINS)); - } - - // Decode uchar4 pixel into bins - template - __device__ __forceinline__ void DecodePixel(uchar4 pixel, unsigned int (&bins)[ACTIVE_CHANNELS]) - { - unsigned char* samples = reinterpret_cast(&pixel); - - #pragma unroll - for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) - bins[CHANNEL] = (unsigned int) (samples[CHANNEL]); - } - - // Decode uchar1 pixel into bins - template - __device__ __forceinline__ void DecodePixel(uchar1 pixel, unsigned int (&bins)[ACTIVE_CHANNELS]) - { - bins[0] = (unsigned int) pixel.x; - } - - // First-pass histogram kernel (binning into privatized counters) - template < - int NUM_PARTS, - int ACTIVE_CHANNELS, - int NUM_BINS, - typename PixelType> - __global__ void histogram_gmem_atomics( - const PixelType *in, - int width, - int height, - unsigned int *out) - { - // global position and size - int x = blockIdx.x * blockDim.x + threadIdx.x; - int y = blockIdx.y * blockDim.y + threadIdx.y; - int nx = blockDim.x * gridDim.x; - int ny = blockDim.y * gridDim.y; - - // threads in workgroup - int t = threadIdx.x + threadIdx.y * blockDim.x; // thread index in workgroup, linear in 0..nt-1 - int nt = blockDim.x * blockDim.y; // total threads in workgroup - - // group index in 0..ngroups-1 - int g = blockIdx.x + blockIdx.y * gridDim.x; - - // initialize smem - unsigned int *gmem = out + g * NUM_PARTS; - for (int i = t; i < ACTIVE_CHANNELS * NUM_BINS; i += nt) - gmem[i] = 0; - __syncthreads(); - - // process pixels (updates our group's partial histogram in gmem) - for (int col = x; col < width; col += nx) - { - for (int row = y; row < height; row += ny) - { - PixelType pixel = in[row * width + col]; - - unsigned int bins[ACTIVE_CHANNELS]; - DecodePixel(pixel, bins); - - #pragma unroll - for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) - atomicAdd(&gmem[(NUM_BINS * CHANNEL) + bins[CHANNEL]], 1); - } - } - } - - // Second pass histogram kernel (accumulation) - template < - int NUM_PARTS, - int ACTIVE_CHANNELS, - int NUM_BINS> - __global__ void histogram_gmem_accum( - const unsigned int *in, - int n, - unsigned int *out) - { - int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i > ACTIVE_CHANNELS * NUM_BINS) - return; // out of range - - unsigned int total = 0; - for (int j = 0; j < n; j++) - total += in[i + NUM_PARTS * j]; - - out[i] = total; - } - - -} // namespace histogram_gmem_atomics - - -template < - int ACTIVE_CHANNELS, - int NUM_BINS, - typename PixelType> -double run_gmem_atomics( - PixelType *d_image, - int width, - int height, - unsigned int *d_hist, - bool warmup) -{ - enum - { - NUM_PARTS = 1024 - }; - - cudaDeviceProp props; - cudaGetDeviceProperties(&props, 0); - - dim3 block(32, 4); - dim3 grid(16, 16); - int total_blocks = grid.x * grid.y; - - // allocate partial histogram - unsigned int *d_part_hist; - cudaMalloc(&d_part_hist, total_blocks * NUM_PARTS * sizeof(unsigned int)); - - dim3 block2(128); - dim3 grid2((3 * NUM_BINS + block.x - 1) / block.x); - - GpuTimer gpu_timer; - gpu_timer.Start(); - - histogram_gmem_atomics::histogram_gmem_atomics<<>>( - d_image, - width, - height, - d_part_hist); - - histogram_gmem_atomics::histogram_gmem_accum<<>>( - d_part_hist, - total_blocks, - d_hist); - - gpu_timer.Stop(); - float elapsed_millis = gpu_timer.ElapsedMillis(); - - cudaFree(d_part_hist); - - return elapsed_millis; -} - diff --git a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/async/sort.h b/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/async/sort.h deleted file mode 100644 index c3a83ad404f8943d52dbeeca9a183997d8dff7c3..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/async/sort.h +++ /dev/null @@ -1,34 +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. - */ - -// The purpose of this header is to #include the async/sort.h header of the -// sequential, host, and device systems. It should be #included in any code -// which uses ADL to dispatch async sort. - -#pragma once - -#include - -//#include - -//#define __THRUST_HOST_SYSTEM_ASYNC_SORT_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/async/sort.h> -//#include __THRUST_HOST_SYSTEM_ASYNC_SORT_HEADER -//#undef __THRUST_HOST_SYSTEM_ASYNC_SORT_HEADER - -#define __THRUST_DEVICE_SYSTEM_ASYNC_SORT_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/async/sort.h> -#include __THRUST_DEVICE_SYSTEM_ASYNC_SORT_HEADER -#undef __THRUST_DEVICE_SYSTEM_ASYNC_SORT_HEADER - diff --git a/spaces/mabusdogma/facerecognition/app.py b/spaces/mabusdogma/facerecognition/app.py deleted file mode 100644 index 53c7ac069df13c31ba8b8a8bbd5263323f289a39..0000000000000000000000000000000000000000 --- a/spaces/mabusdogma/facerecognition/app.py +++ /dev/null @@ -1,125 +0,0 @@ -import streamlit as st -import face_recognition -import cv2 -import numpy as np - -#Configuración inicial, esconde menu hamburguesa arriba a la derecha y publicidad debajo(footer) -st.set_page_config(page_title='Login', page_icon='friends.ico', layout="centered", menu_items=None) -hide_menu_style = """ - - """ -st.markdown(hide_menu_style, unsafe_allow_html=True) -#Quita el hueco en la parte superior -st.write('', unsafe_allow_html=True) -#esconde el primer radio button -st.markdown(""" """,unsafe_allow_html=True) - - # ------------- -window = st.image([]) #ventana de video -grabacion = cv2.VideoCapture(0) - -#personas y sus fotos -alicja_imagen = face_recognition.load_image_file("alicja.jpg") -alicja_codificacion = face_recognition.face_encodings(alicja_imagen)[0] - -salva_imagen = face_recognition.load_image_file("salva.jpg") -salva_codificacion = face_recognition.face_encodings(salva_imagen)[0] - -yassin_imagen = face_recognition.load_image_file("yassin.jpg") -yassin_codificacion = face_recognition.face_encodings(yassin_imagen)[0] - -zouhair_imagen = face_recognition.load_image_file("zouhair.jpg") -zouhair_codificacion = face_recognition.face_encodings(zouhair_imagen)[0] - -rosa_imagen = face_recognition.load_image_file("rosa.jpg") -rosa_codificacion = face_recognition.face_encodings(rosa_imagen)[0] - -awatef_imagen = face_recognition.load_image_file("awatef.jpg") -awatef_codificacion = face_recognition.face_encodings(awatef_imagen)[0] - - -# Create arrays of known face encodings and their names -codificar_caras = [ - alicja_codificacion, - salva_codificacion, - yassin_codificacion, - zouhair_codificacion, - rosa_codificacion, - awatef_codificacion -] -caras_conocidas = [ - "Alicja", - "Salvador", - "Yassin", - "Zouhair", - "Rosa", - "Awatef" -] - -# Initialize some variables -face_locations = [] -face_encodings = [] -face_names = [] -process_this_frame = True - -while True: - # Grab a single frame of video - ret, frame = grabacion.read() - - # Only process every other frame of video to save time - if process_this_frame: - st.write('frame: ',frame) - - # Resize frame of video to 1/4 size for faster face recognition processing - small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) - - # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) - rgb_small_frame = small_frame[:, :, ::-1] - - # Find all the faces and face encodings in the current frame of video - face_locations = face_recognition.face_locations(rgb_small_frame) - face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) - - face_names = [] - for face_encoding in face_encodings: - # See if the face is a match for the known face(s) - matches = face_recognition.compare_faces(codificar_caras, face_encoding) - name = "Otro(a)" - - #If a match was found in codificar_caras, just use the first one. - # if True in matches: - # first_match_index = matches.index(True) - # name = caras_conocidas[first_match_index] - - # Or instead, use the known face with the smallest distance to the new face - face_distances = face_recognition.face_distance(codificar_caras, face_encoding) - best_match_index = np.argmin(face_distances) - if matches[best_match_index]: - name = caras_conocidas[best_match_index] - - face_names.append(name) - porcentaje = str(100*face_distances)[1:3] - process_this_frame = not process_this_frame - - # Display the results - for (top, right, bottom, left), name in zip(face_locations, face_names): - # Scale back up face locations since the frame we detected in was scaled to 1/4 size - top *= 4 - right *= 4 - bottom *= 4 - left *= 4 - - # Draw a box around the face - cv2.rectangle(frame, (left, top), (right, bottom), (100, 255, 100), 1) - - # Draw a label with a name below the face - cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (100, 255, 100), cv2.FILLED) - font = cv2.FONT_HERSHEY_DUPLEX - cv2.putText(frame, (name+" "+porcentaje+"%"), (left + 6, bottom - 6), font, 0.7, (255, 255, 255), 1) - - - window.image(frame,channels="BGR") - cv2.waitKey() diff --git a/spaces/macaodha/batdetect2/bat_detect/detector/post_process.py b/spaces/macaodha/batdetect2/bat_detect/detector/post_process.py deleted file mode 100644 index 757831fbf761a34b6f0dcb3346deb369961ee49b..0000000000000000000000000000000000000000 --- a/spaces/macaodha/batdetect2/bat_detect/detector/post_process.py +++ /dev/null @@ -1,100 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -import numpy as np -np.seterr(divide='ignore', invalid='ignore') - - -def x_coords_to_time(x_pos, sampling_rate, fft_win_length, fft_overlap): - nfft = int(fft_win_length*sampling_rate) - noverlap = int(fft_overlap*nfft) - return ((x_pos*(nfft - noverlap)) + noverlap) / sampling_rate - #return (1.0 - fft_overlap) * fft_win_length * (x_pos + 0.5) # 0.5 is for center of temporal window - - -def overall_class_pred(det_prob, class_prob): - weighted_pred = (class_prob*det_prob).sum(1) - return weighted_pred / weighted_pred.sum() - - -def run_nms(outputs, params, sampling_rate): - - pred_det = outputs['pred_det'] # probability of box - pred_size = outputs['pred_size'] # box size - - pred_det_nms = non_max_suppression(pred_det, params['nms_kernel_size']) - freq_rescale = (params['max_freq'] - params['min_freq']) /pred_det.shape[-2] - - # NOTE there will be small differences depending on which sampling rate is chosen - # as we are choosing the same sampling rate for the entire batch - duration = x_coords_to_time(pred_det.shape[-1], sampling_rate[0].item(), - params['fft_win_length'], params['fft_overlap']) - top_k = int(duration * params['nms_top_k_per_sec']) - scores, y_pos, x_pos = get_topk_scores(pred_det_nms, top_k) - - # loop over batch to save outputs - preds = [] - feats = [] - for ii in range(pred_det_nms.shape[0]): - # get valid indices - inds_ord = torch.argsort(x_pos[ii, :]) - valid_inds = scores[ii, inds_ord] > params['detection_threshold'] - valid_inds = inds_ord[valid_inds] - - # create result dictionary - pred = {} - pred['det_probs'] = scores[ii, valid_inds] - pred['x_pos'] = x_pos[ii, valid_inds] - pred['y_pos'] = y_pos[ii, valid_inds] - pred['bb_width'] = pred_size[ii, 0, pred['y_pos'], pred['x_pos']] - pred['bb_height'] = pred_size[ii, 1, pred['y_pos'], pred['x_pos']] - pred['start_times'] = x_coords_to_time(pred['x_pos'].float() / params['resize_factor'], - sampling_rate[ii].item(), params['fft_win_length'], params['fft_overlap']) - pred['end_times'] = x_coords_to_time((pred['x_pos'].float()+pred['bb_width']) / params['resize_factor'], - sampling_rate[ii].item(), params['fft_win_length'], params['fft_overlap']) - pred['low_freqs'] = (pred_size[ii].shape[1] - pred['y_pos'].float())*freq_rescale + params['min_freq'] - pred['high_freqs'] = pred['low_freqs'] + pred['bb_height']*freq_rescale - - # extract the per class votes - if 'pred_class' in outputs: - pred['class_probs'] = outputs['pred_class'][ii, :, y_pos[ii, valid_inds], x_pos[ii, valid_inds]] - - # extract the model features - if 'features' in outputs: - feat = outputs['features'][ii, :, y_pos[ii, valid_inds], x_pos[ii, valid_inds]].transpose(0, 1) - feat = feat.cpu().numpy().astype(np.float32) - feats.append(feat) - - # convert to numpy - for kk in pred.keys(): - pred[kk] = pred[kk].cpu().numpy().astype(np.float32) - preds.append(pred) - - return preds, feats - - -def non_max_suppression(heat, kernel_size): - # kernel can be an int or list/tuple - if type(kernel_size) is int: - kernel_size_h = kernel_size - kernel_size_w = kernel_size - - pad_h = (kernel_size_h - 1) // 2 - pad_w = (kernel_size_w - 1) // 2 - - hmax = nn.functional.max_pool2d(heat, (kernel_size_h, kernel_size_w), stride=1, padding=(pad_h, pad_w)) - keep = (hmax == heat).float() - - return heat * keep - - -def get_topk_scores(scores, K): - # expects input of size: batch x 1 x height x width - batch, _, height, width = scores.size() - - topk_scores, topk_inds = torch.topk(scores.view(batch, -1), K) - topk_inds = topk_inds % (height * width) - topk_ys = torch.div(topk_inds, width, rounding_mode='floor').long() - topk_xs = (topk_inds % width).long() - - return topk_scores, topk_ys, topk_xs diff --git a/spaces/manavisrani07/gradio-lipsync-wav2lip/basicsr/models/realesrgan_model.py b/spaces/manavisrani07/gradio-lipsync-wav2lip/basicsr/models/realesrgan_model.py deleted file mode 100644 index c74b28fb1dc6a7f5c5ad3f7d8bb96c19c52ee92b..0000000000000000000000000000000000000000 --- a/spaces/manavisrani07/gradio-lipsync-wav2lip/basicsr/models/realesrgan_model.py +++ /dev/null @@ -1,267 +0,0 @@ -import numpy as np -import random -import torch -from collections import OrderedDict -from torch.nn import functional as F - -from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt -from basicsr.data.transforms import paired_random_crop -from basicsr.losses.loss_util import get_refined_artifact_map -from basicsr.models.srgan_model import SRGANModel -from basicsr.utils import DiffJPEG, USMSharp -from basicsr.utils.img_process_util import filter2D -from basicsr.utils.registry import MODEL_REGISTRY - - -@MODEL_REGISTRY.register(suffix='basicsr') -class RealESRGANModel(SRGANModel): - """RealESRGAN Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. - - It mainly performs: - 1. randomly synthesize LQ images in GPU tensors - 2. optimize the networks with GAN training. - """ - - def __init__(self, opt): - super(RealESRGANModel, self).__init__(opt) - self.jpeger = DiffJPEG(differentiable=False).cuda() # simulate JPEG compression artifacts - self.usm_sharpener = USMSharp().cuda() # do usm sharpening - self.queue_size = opt.get('queue_size', 180) - - @torch.no_grad() - def _dequeue_and_enqueue(self): - """It is the training pair pool for increasing the diversity in a batch. - - Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a - batch could not have different resize scaling factors. Therefore, we employ this training pair pool - to increase the degradation diversity in a batch. - """ - # initialize - b, c, h, w = self.lq.size() - if not hasattr(self, 'queue_lr'): - assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}' - self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() - _, c, h, w = self.gt.size() - self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() - self.queue_ptr = 0 - if self.queue_ptr == self.queue_size: # the pool is full - # do dequeue and enqueue - # shuffle - idx = torch.randperm(self.queue_size) - self.queue_lr = self.queue_lr[idx] - self.queue_gt = self.queue_gt[idx] - # get first b samples - lq_dequeue = self.queue_lr[0:b, :, :, :].clone() - gt_dequeue = self.queue_gt[0:b, :, :, :].clone() - # update the queue - self.queue_lr[0:b, :, :, :] = self.lq.clone() - self.queue_gt[0:b, :, :, :] = self.gt.clone() - - self.lq = lq_dequeue - self.gt = gt_dequeue - else: - # only do enqueue - self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone() - self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone() - self.queue_ptr = self.queue_ptr + b - - @torch.no_grad() - def feed_data(self, data): - """Accept data from dataloader, and then add two-order degradations to obtain LQ images. - """ - if self.is_train and self.opt.get('high_order_degradation', True): - # training data synthesis - self.gt = data['gt'].to(self.device) - self.gt_usm = self.usm_sharpener(self.gt) - - self.kernel1 = data['kernel1'].to(self.device) - self.kernel2 = data['kernel2'].to(self.device) - self.sinc_kernel = data['sinc_kernel'].to(self.device) - - ori_h, ori_w = self.gt.size()[2:4] - - # ----------------------- The first degradation process ----------------------- # - # blur - out = filter2D(self.gt_usm, self.kernel1) - # random resize - updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0] - if updown_type == 'up': - scale = np.random.uniform(1, self.opt['resize_range'][1]) - elif updown_type == 'down': - scale = np.random.uniform(self.opt['resize_range'][0], 1) - else: - scale = 1 - mode = random.choice(['area', 'bilinear', 'bicubic']) - out = F.interpolate(out, scale_factor=scale, mode=mode) - # add noise - gray_noise_prob = self.opt['gray_noise_prob'] - if np.random.uniform() < self.opt['gaussian_noise_prob']: - out = random_add_gaussian_noise_pt( - out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob) - else: - out = random_add_poisson_noise_pt( - out, - scale_range=self.opt['poisson_scale_range'], - gray_prob=gray_noise_prob, - clip=True, - rounds=False) - # JPEG compression - jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range']) - out = torch.clamp(out, 0, 1) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts - out = self.jpeger(out, quality=jpeg_p) - - # ----------------------- The second degradation process ----------------------- # - # blur - if np.random.uniform() < self.opt['second_blur_prob']: - out = filter2D(out, self.kernel2) - # random resize - updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0] - if updown_type == 'up': - scale = np.random.uniform(1, self.opt['resize_range2'][1]) - elif updown_type == 'down': - scale = np.random.uniform(self.opt['resize_range2'][0], 1) - else: - scale = 1 - mode = random.choice(['area', 'bilinear', 'bicubic']) - out = F.interpolate( - out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode) - # add noise - gray_noise_prob = self.opt['gray_noise_prob2'] - if np.random.uniform() < self.opt['gaussian_noise_prob2']: - out = random_add_gaussian_noise_pt( - out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob) - else: - out = random_add_poisson_noise_pt( - out, - scale_range=self.opt['poisson_scale_range2'], - gray_prob=gray_noise_prob, - clip=True, - rounds=False) - - # JPEG compression + the final sinc filter - # We also need to resize images to desired sizes. We group [resize back + sinc filter] together - # as one operation. - # We consider two orders: - # 1. [resize back + sinc filter] + JPEG compression - # 2. JPEG compression + [resize back + sinc filter] - # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. - if np.random.uniform() < 0.5: - # resize back + the final sinc filter - mode = random.choice(['area', 'bilinear', 'bicubic']) - out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) - out = filter2D(out, self.sinc_kernel) - # JPEG compression - jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) - out = torch.clamp(out, 0, 1) - out = self.jpeger(out, quality=jpeg_p) - else: - # JPEG compression - jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2']) - out = torch.clamp(out, 0, 1) - out = self.jpeger(out, quality=jpeg_p) - # resize back + the final sinc filter - mode = random.choice(['area', 'bilinear', 'bicubic']) - out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode) - out = filter2D(out, self.sinc_kernel) - - # clamp and round - self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255. - - # random crop - gt_size = self.opt['gt_size'] - (self.gt, self.gt_usm), self.lq = paired_random_crop([self.gt, self.gt_usm], self.lq, gt_size, - self.opt['scale']) - - # training pair pool - self._dequeue_and_enqueue() - # sharpen self.gt again, as we have changed the self.gt with self._dequeue_and_enqueue - self.gt_usm = self.usm_sharpener(self.gt) - self.lq = self.lq.contiguous() # for the warning: grad and param do not obey the gradient layout contract - else: - # for paired training or validation - self.lq = data['lq'].to(self.device) - if 'gt' in data: - self.gt = data['gt'].to(self.device) - self.gt_usm = self.usm_sharpener(self.gt) - - def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): - # do not use the synthetic process during validation - self.is_train = False - super(RealESRGANModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img) - self.is_train = True - - def optimize_parameters(self, current_iter): - # usm sharpening - l1_gt = self.gt_usm - percep_gt = self.gt_usm - gan_gt = self.gt_usm - if self.opt['l1_gt_usm'] is False: - l1_gt = self.gt - if self.opt['percep_gt_usm'] is False: - percep_gt = self.gt - if self.opt['gan_gt_usm'] is False: - gan_gt = self.gt - - # optimize net_g - for p in self.net_d.parameters(): - p.requires_grad = False - - self.optimizer_g.zero_grad() - self.output = self.net_g(self.lq) - if self.cri_ldl: - self.output_ema = self.net_g_ema(self.lq) - - l_g_total = 0 - loss_dict = OrderedDict() - if (current_iter % self.net_d_iters == 0 and current_iter > self.net_d_init_iters): - # pixel loss - if self.cri_pix: - l_g_pix = self.cri_pix(self.output, l1_gt) - l_g_total += l_g_pix - loss_dict['l_g_pix'] = l_g_pix - if self.cri_ldl: - pixel_weight = get_refined_artifact_map(self.gt, self.output, self.output_ema, 7) - l_g_ldl = self.cri_ldl(torch.mul(pixel_weight, self.output), torch.mul(pixel_weight, self.gt)) - l_g_total += l_g_ldl - loss_dict['l_g_ldl'] = l_g_ldl - # perceptual loss - if self.cri_perceptual: - l_g_percep, l_g_style = self.cri_perceptual(self.output, percep_gt) - if l_g_percep is not None: - l_g_total += l_g_percep - loss_dict['l_g_percep'] = l_g_percep - if l_g_style is not None: - l_g_total += l_g_style - loss_dict['l_g_style'] = l_g_style - # gan loss - fake_g_pred = self.net_d(self.output) - l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False) - l_g_total += l_g_gan - loss_dict['l_g_gan'] = l_g_gan - - l_g_total.backward() - self.optimizer_g.step() - - # optimize net_d - for p in self.net_d.parameters(): - p.requires_grad = True - - self.optimizer_d.zero_grad() - # real - real_d_pred = self.net_d(gan_gt) - l_d_real = self.cri_gan(real_d_pred, True, is_disc=True) - loss_dict['l_d_real'] = l_d_real - loss_dict['out_d_real'] = torch.mean(real_d_pred.detach()) - l_d_real.backward() - # fake - fake_d_pred = self.net_d(self.output.detach().clone()) # clone for pt1.9 - l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True) - loss_dict['l_d_fake'] = l_d_fake - loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach()) - l_d_fake.backward() - self.optimizer_d.step() - - if self.ema_decay > 0: - self.model_ema(decay=self.ema_decay) - - self.log_dict = self.reduce_loss_dict(loss_dict) diff --git a/spaces/mascIT/AgeGuesser/yolov5/utils/datasets.py b/spaces/mascIT/AgeGuesser/yolov5/utils/datasets.py deleted file mode 100644 index 453784132ca07d64b99eeec07285a1f1b352fd2f..0000000000000000000000000000000000000000 --- a/spaces/mascIT/AgeGuesser/yolov5/utils/datasets.py +++ /dev/null @@ -1,397 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Dataloaders and dataset utils -""" - -import glob -import hashlib -import json -import math -import os -import random -import shutil -import time -from itertools import repeat -from multiprocessing.pool import Pool, ThreadPool -from pathlib import Path -from threading import Thread -from zipfile import ZipFile - -import cv2 -import numpy as np -import torch -import torch.nn.functional as F -import yaml -from PIL import ExifTags, Image, ImageOps -from tqdm import tqdm - -from .augmentations import letterbox -from .general import (xyn2xy, xywh2xyxy, xywhn2xyxy) - -# Parameters -HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' -IMG_FORMATS = ['bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp'] # include image suffixes -VID_FORMATS = ['asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'wmv'] # include video suffixes - -# Get orientation exif tag -for orientation in ExifTags.TAGS.keys(): - if ExifTags.TAGS[orientation] == 'Orientation': - break - - -def get_hash(paths): - # Returns a single hash value of a list of paths (files or dirs) - size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes - h = hashlib.md5(str(size).encode()) # hash sizes - h.update(''.join(paths).encode()) # hash paths - return h.hexdigest() # return hash - - -def exif_size(img): - # Returns exif-corrected PIL size - s = img.size # (width, height) - try: - rotation = dict(img._getexif().items())[orientation] - if rotation == 6: # rotation 270 - s = (s[1], s[0]) - elif rotation == 8: # rotation 90 - s = (s[1], s[0]) - except: - pass - - return s - - -def exif_transpose(image): - """ - Transpose a PIL image accordingly if it has an EXIF Orientation tag. - Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose() - - :param image: The image to transpose. - :return: An image. - """ - exif = image.getexif() - orientation = exif.get(0x0112, 1) # default 1 - if orientation > 1: - method = {2: Image.FLIP_LEFT_RIGHT, - 3: Image.ROTATE_180, - 4: Image.FLIP_TOP_BOTTOM, - 5: Image.TRANSPOSE, - 6: Image.ROTATE_270, - 7: Image.TRANSVERSE, - 8: Image.ROTATE_90, - }.get(orientation) - if method is not None: - image = image.transpose(method) - del exif[0x0112] - image.info["exif"] = exif.tobytes() - return image - - -def pil_to_cv(pil_img, img_size=320, stride=32, auto=True): - np_img = np.array(pil_img) - - img0 = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR) - - img = letterbox(img0, img_size, stride=stride, auto=auto)[0] - img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB - img = np.ascontiguousarray(img) - - return img, img0 - - -class LoadImages: - # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4` - def __init__(self, path, img_size=640, stride=32, auto=True): - p = str(Path(path).resolve()) # os-agnostic absolute path - if '*' in p: - files = sorted(glob.glob(p, recursive=True)) # glob - elif os.path.isdir(p): - files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir - elif os.path.isfile(p): - files = [p] # files - else: - raise Exception(f'ERROR: {p} does not exist') - - images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS] - videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS] - ni, nv = len(images), len(videos) - - self.img_size = img_size - self.stride = stride - self.files = images + videos - self.nf = ni + nv # number of files - self.video_flag = [False] * ni + [True] * nv - self.mode = 'image' - self.auto = auto - if any(videos): - self.new_video(videos[0]) # new video - else: - self.cap = None - assert self.nf > 0, f'No images or videos found in {p}. ' \ - f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}' - - def __iter__(self): - self.count = 0 - return self - - def __next__(self): - if self.count == self.nf: - raise StopIteration - path = self.files[self.count] - - if self.video_flag[self.count]: - # Read video - self.mode = 'video' - ret_val, img0 = self.cap.read() - while not ret_val: - self.count += 1 - self.cap.release() - if self.count == self.nf: # last video - raise StopIteration - else: - path = self.files[self.count] - self.new_video(path) - ret_val, img0 = self.cap.read() - - self.frame += 1 - s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ' - - else: - # Read image - self.count += 1 - img0 = cv2.imread(path) # BGR - assert img0 is not None, f'Image Not Found {path}' - s = f'image {self.count}/{self.nf} {path}: ' - - # Padded resize - img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] - - # Convert - img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB - img = np.ascontiguousarray(img) - - return path, img, img0, self.cap, s - - def new_video(self, path): - self.frame = 0 - self.cap = cv2.VideoCapture(path) - self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) - - def __len__(self): - return self.nf # number of files - - -def img2label_paths(img_paths): - # Define label paths as a function of image paths - sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings - return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths] - - -# Ancillary functions -------------------------------------------------------------------------------------------------- -def load_image(self, i): - # loads 1 image from dataset index 'i', returns im, original hw, resized hw - im = self.imgs[i] - if im is None: # not cached in ram - npy = self.img_npy[i] - if npy and npy.exists(): # load npy - im = np.load(npy) - else: # read image - path = self.img_files[i] - im = cv2.imread(path) # BGR - assert im is not None, f'Image Not Found {path}' - h0, w0 = im.shape[:2] # orig hw - r = self.img_size / max(h0, w0) # ratio - if r != 1: # if sizes are not equal - im = cv2.resize(im, (int(w0 * r), int(h0 * r)), - interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR) - return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized - else: - return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized - - -def load_mosaic(self, index): - # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic - labels4, segments4 = [], [] - s = self.img_size - yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y - indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices - random.shuffle(indices) - for i, index in enumerate(indices): - # Load image - img, _, (h, w) = load_image(self, index) - - # place img in img4 - if i == 0: # top left - img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles - x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) - x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) - elif i == 1: # top right - x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc - x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h - elif i == 2: # bottom left - x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) - x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) - elif i == 3: # bottom right - x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) - x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) - - img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] - padw = x1a - x1b - padh = y1a - y1b - - # Labels - labels, segments = self.labels[index].copy(), self.segments[index].copy() - if labels.size: - labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format - segments = [xyn2xy(x, w, h, padw, padh) for x in segments] - labels4.append(labels) - segments4.extend(segments) - - # Concat/clip labels - labels4 = np.concatenate(labels4, 0) - for x in (labels4[:, 1:], *segments4): - np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() - # img4, labels4 = replicate(img4, labels4) # replicate - - return img4, labels4 - - -def load_mosaic9(self, index): - # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic - labels9, segments9 = [], [] - s = self.img_size - indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices - random.shuffle(indices) - for i, index in enumerate(indices): - # Load image - img, _, (h, w) = load_image(self, index) - - # place img in img9 - if i == 0: # center - img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles - h0, w0 = h, w - c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates - elif i == 1: # top - c = s, s - h, s + w, s - elif i == 2: # top right - c = s + wp, s - h, s + wp + w, s - elif i == 3: # right - c = s + w0, s, s + w0 + w, s + h - elif i == 4: # bottom right - c = s + w0, s + hp, s + w0 + w, s + hp + h - elif i == 5: # bottom - c = s + w0 - w, s + h0, s + w0, s + h0 + h - elif i == 6: # bottom left - c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h - elif i == 7: # left - c = s - w, s + h0 - h, s, s + h0 - elif i == 8: # top left - c = s - w, s + h0 - hp - h, s, s + h0 - hp - - padx, pady = c[:2] - x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords - - # Labels - labels, segments = self.labels[index].copy(), self.segments[index].copy() - if labels.size: - labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format - segments = [xyn2xy(x, w, h, padx, pady) for x in segments] - labels9.append(labels) - segments9.extend(segments) - - # Image - img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] - hp, wp = h, w # height, width previous - - # Offset - yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y - img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] - - # Concat/clip labels - labels9 = np.concatenate(labels9, 0) - labels9[:, [1, 3]] -= xc - labels9[:, [2, 4]] -= yc - c = np.array([xc, yc]) # centers - segments9 = [x - c for x in segments9] - - for x in (labels9[:, 1:], *segments9): - np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() - # img9, labels9 = replicate(img9, labels9) # replicate - - - return img9, labels9 - - -def create_folder(path='./new'): - # Create folder - if os.path.exists(path): - shutil.rmtree(path) # delete output folder - os.makedirs(path) # make new output folder - - -def flatten_recursive(path='../datasets/coco128'): - # Flatten a recursive directory by bringing all files to top level - new_path = Path(path + '_flat') - create_folder(new_path) - for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): - shutil.copyfile(file, new_path / Path(file).name) - - -def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes() - # Convert detection dataset into classification dataset, with one directory per class - path = Path(path) # images dir - shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing - files = list(path.rglob('*.*')) - n = len(files) # number of files - for im_file in tqdm(files, total=n): - if im_file.suffix[1:] in IMG_FORMATS: - # image - im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB - h, w = im.shape[:2] - - # labels - lb_file = Path(img2label_paths([str(im_file)])[0]) - if Path(lb_file).exists(): - with open(lb_file) as f: - lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels - - for j, x in enumerate(lb): - c = int(x[0]) # class - f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename - if not f.parent.is_dir(): - f.parent.mkdir(parents=True) - - b = x[1:] * [w, h, w, h] # box - # b[2:] = b[2:].max() # rectangle to square - b[2:] = b[2:] * 1.2 + 3 # pad - b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) - - b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image - b[[1, 3]] = np.clip(b[[1, 3]], 0, h) - assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' - - -def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): - """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files - Usage: from utils.datasets import *; autosplit() - Arguments - path: Path to images directory - weights: Train, val, test weights (list, tuple) - annotated_only: Only use images with an annotated txt file - """ - path = Path(path) # images dir - files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only - n = len(files) # number of files - random.seed(0) # for reproducibility - indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split - - txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files - [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing - - print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) - for i, img in tqdm(zip(indices, files), total=n): - if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label - with open(path.parent / txt[i], 'a') as f: - f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file - diff --git a/spaces/matthoffner/chatbot/CONTRIBUTING.md b/spaces/matthoffner/chatbot/CONTRIBUTING.md deleted file mode 100644 index 2fc863718e9eaa6d9d1a2f4f35c1319bd57366f9..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/chatbot/CONTRIBUTING.md +++ /dev/null @@ -1,45 +0,0 @@ -# Contributing Guidelines - -**Welcome to Chatbot UI!** - -We appreciate your interest in contributing to our project. - -Before you get started, please read our guidelines for contributing. - -## Types of Contributions - -We welcome the following types of contributions: - -- Bug fixes -- New features -- Documentation improvements -- Code optimizations -- Translations -- Tests - -## Getting Started - -To get started, fork the project on GitHub and clone it locally on your machine. Then, create a new branch to work on your changes. - -``` -git clone https://github.com/mckaywrigley/chatbot-ui.git -cd chatbot-ui -git checkout -b my-branch-name - -``` - -Before submitting your pull request, please make sure your changes pass our automated tests and adhere to our code style guidelines. - -## Pull Request Process - -1. Fork the project on GitHub. -2. Clone your forked repository locally on your machine. -3. Create a new branch from the main branch. -4. Make your changes on the new branch. -5. Ensure that your changes adhere to our code style guidelines and pass our automated tests. -6. Commit your changes and push them to your forked repository. -7. Submit a pull request to the main branch of the main repository. - -## Contact - -If you have any questions or need help getting started, feel free to reach out to me on [Twitter](https://twitter.com/mckaywrigley). diff --git a/spaces/matthoffner/web-llm-embed/src/prompt/index.ts b/spaces/matthoffner/web-llm-embed/src/prompt/index.ts deleted file mode 100644 index fd562dfdd5d98299581fd9e658b343998dc67f59..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/web-llm-embed/src/prompt/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const QA_PROMPT = ` -Your name is Ronnie C. -Use the following pieces of context to answer the users question. -If you don't know the answer, just say that you don't know, don't try to make up an answer. -Always answer from the perspective of being Ronnie C. ----------------- -{context} - -Question: {question} -Helpful Answer:` \ No newline at end of file diff --git a/spaces/maxmax20160403/sovits5.0/README.md b/spaces/maxmax20160403/sovits5.0/README.md deleted file mode 100644 index 64c94298b003f828aa3271360e799f732b6d3e60..0000000000000000000000000000000000000000 --- a/spaces/maxmax20160403/sovits5.0/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Sovits5.0 -emoji: 🏃 -colorFrom: pink -colorTo: blue -sdk: gradio -sdk_version: 3.28.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/mehdidc/text_to_image_ddgan/score_sde/models/layerspp.py b/spaces/mehdidc/text_to_image_ddgan/score_sde/models/layerspp.py deleted file mode 100644 index 3e54ee6b033e53040c418169fbd153834233df94..0000000000000000000000000000000000000000 --- a/spaces/mehdidc/text_to_image_ddgan/score_sde/models/layerspp.py +++ /dev/null @@ -1,408 +0,0 @@ -# --------------------------------------------------------------- -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# This file has been modified from a file in the Score SDE library -# which was released under the Apache License. -# -# Source: -# https://github.com/yang-song/score_sde_pytorch/blob/main/models/layerspp.py -# -# The license for the original version of this file can be -# found in this directory (LICENSE_Apache). The modifications -# to this file are subject to the same Apache License. -# --------------------------------------------------------------- - -# coding=utf-8 -# Copyright 2020 The Google Research 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. - -# pylint: skip-file - -from . import layers -from . import up_or_down_sampling, dense_layer -import torch.nn as nn -import torch -import torch.nn.functional as F -import numpy as np - - -conv1x1 = layers.ddpm_conv1x1 -conv3x3 = layers.ddpm_conv3x3 -NIN = layers.NIN -default_init = layers.default_init -dense = dense_layer.dense - -class AdaptiveGroupNorm(nn.Module): - def __init__(self, num_groups,in_channel, style_dim): - super().__init__() - - self.norm = nn.GroupNorm(num_groups, in_channel, affine=False, eps=1e-6) - self.style = dense(style_dim, in_channel * 2) - - self.style.bias.data[:in_channel] = 1 - self.style.bias.data[in_channel:] = 0 - - def forward(self, input, style): - style = self.style(style).unsqueeze(2).unsqueeze(3) - gamma, beta = style.chunk(2, 1) - - out = self.norm(input) - out = gamma * out + beta - - return out - -class GaussianFourierProjection(nn.Module): - """Gaussian Fourier embeddings for noise levels.""" - - def __init__(self, embedding_size=256, scale=1.0): - super().__init__() - self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False) - - def forward(self, x): - x_proj = x[:, None] * self.W[None, :] * 2 * np.pi - return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1) - - -class Combine(nn.Module): - """Combine information from skip connections.""" - - def __init__(self, dim1, dim2, method='cat'): - super().__init__() - self.Conv_0 = conv1x1(dim1, dim2) - self.method = method - - def forward(self, x, y): - h = self.Conv_0(x) - if self.method == 'cat': - return torch.cat([h, y], dim=1) - elif self.method == 'sum': - return h + y - else: - raise ValueError(f'Method {self.method} not recognized.') - - -class AttnBlockpp(nn.Module): - """Channel-wise self-attention block. Modified from DDPM.""" - - def __init__(self, channels, skip_rescale=False, init_scale=0.): - super().__init__() - self.GroupNorm_0 = nn.GroupNorm(num_groups=min(channels // 4, 32), num_channels=channels, - eps=1e-6) - self.NIN_0 = NIN(channels, channels) - self.NIN_1 = NIN(channels, channels) - self.NIN_2 = NIN(channels, channels) - self.NIN_3 = NIN(channels, channels, init_scale=init_scale) - self.skip_rescale = skip_rescale - - def forward(self, x): - B, C, H, W = x.shape - h = self.GroupNorm_0(x) - q = self.NIN_0(h) - k = self.NIN_1(h) - v = self.NIN_2(h) - - w = torch.einsum('bchw,bcij->bhwij', q, k) * (int(C) ** (-0.5)) - w = torch.reshape(w, (B, H, W, H * W)) - w = F.softmax(w, dim=-1) - w = torch.reshape(w, (B, H, W, H, W)) - h = torch.einsum('bhwij,bcij->bchw', w, v) - h = self.NIN_3(h) - if not self.skip_rescale: - return x + h - else: - return (x + h) / np.sqrt(2.) - -class AttnBlockppRaw(nn.Module): - """Channel-wise self-attention block. Modified from DDPM.""" - - def __init__(self, channels, skip_rescale=False, init_scale=0.): - super().__init__() - self.GroupNorm_0 = nn.GroupNorm(num_groups=min(channels // 4, 32), num_channels=channels, - eps=1e-6) - self.NIN_0 = NIN(channels, channels) - self.NIN_1 = NIN(channels, channels) - self.NIN_2 = NIN(channels, channels) - self.NIN_3 = NIN(channels, channels, init_scale=init_scale) - self.skip_rescale = skip_rescale - - def forward(self, x): - B, C, H, W = x.shape - h = self.GroupNorm_0(x) - q = self.NIN_0(h) - k = self.NIN_1(h) - v = self.NIN_2(h) - - w = torch.einsum('bchw,bcij->bhwij', q, k) * (int(C) ** (-0.5)) - w = torch.reshape(w, (B, H, W, H * W)) - w = F.softmax(w, dim=-1) - w = torch.reshape(w, (B, H, W, H, W)) - h = torch.einsum('bhwij,bcij->bchw', w, v) - h = self.NIN_3(h) - return h - - -class Upsample(nn.Module): - def __init__(self, in_ch=None, out_ch=None, with_conv=False, fir=False, - fir_kernel=(1, 3, 3, 1)): - super().__init__() - out_ch = out_ch if out_ch else in_ch - if not fir: - if with_conv: - self.Conv_0 = conv3x3(in_ch, out_ch) - else: - if with_conv: - self.Conv2d_0 = up_or_down_sampling.Conv2d(in_ch, out_ch, - kernel=3, up=True, - resample_kernel=fir_kernel, - use_bias=True, - kernel_init=default_init()) - self.fir = fir - self.with_conv = with_conv - self.fir_kernel = fir_kernel - self.out_ch = out_ch - - def forward(self, x): - B, C, H, W = x.shape - if not self.fir: - h = F.interpolate(x, (H * 2, W * 2), 'nearest') - if self.with_conv: - h = self.Conv_0(h) - else: - if not self.with_conv: - h = up_or_down_sampling.upsample_2d(x, self.fir_kernel, factor=2) - else: - h = self.Conv2d_0(x) - - return h - - -class Downsample(nn.Module): - def __init__(self, in_ch=None, out_ch=None, with_conv=False, fir=False, - fir_kernel=(1, 3, 3, 1)): - super().__init__() - out_ch = out_ch if out_ch else in_ch - if not fir: - if with_conv: - self.Conv_0 = conv3x3(in_ch, out_ch, stride=2, padding=0) - else: - if with_conv: - self.Conv2d_0 = up_or_down_sampling.Conv2d(in_ch, out_ch, - kernel=3, down=True, - resample_kernel=fir_kernel, - use_bias=True, - kernel_init=default_init()) - self.fir = fir - self.fir_kernel = fir_kernel - self.with_conv = with_conv - self.out_ch = out_ch - - def forward(self, x): - B, C, H, W = x.shape - if not self.fir: - if self.with_conv: - x = F.pad(x, (0, 1, 0, 1)) - x = self.Conv_0(x) - else: - x = F.avg_pool2d(x, 2, stride=2) - else: - if not self.with_conv: - x = up_or_down_sampling.downsample_2d(x, self.fir_kernel, factor=2) - else: - x = self.Conv2d_0(x) - - return x - - -class ResnetBlockDDPMpp_Adagn(nn.Module): - """ResBlock adapted from DDPM.""" - - def __init__(self, act, in_ch, out_ch=None, temb_dim=None, zemb_dim=None, conv_shortcut=False, - dropout=0.1, skip_rescale=False, init_scale=0.): - super().__init__() - out_ch = out_ch if out_ch else in_ch - self.GroupNorm_0 = AdaptiveGroupNorm(min(in_ch // 4, 32), in_ch, zemb_dim) - self.Conv_0 = conv3x3(in_ch, out_ch) - if temb_dim is not None: - self.Dense_0 = nn.Linear(temb_dim, out_ch) - self.Dense_0.weight.data = default_init()(self.Dense_0.weight.data.shape) - nn.init.zeros_(self.Dense_0.bias) - - - self.GroupNorm_1 = AdaptiveGroupNorm(min(out_ch // 4, 32), out_ch, zemb_dim) - self.Dropout_0 = nn.Dropout(dropout) - self.Conv_1 = conv3x3(out_ch, out_ch, init_scale=init_scale) - if in_ch != out_ch: - if conv_shortcut: - self.Conv_2 = conv3x3(in_ch, out_ch) - else: - self.NIN_0 = NIN(in_ch, out_ch) - - self.skip_rescale = skip_rescale - self.act = act - self.out_ch = out_ch - self.conv_shortcut = conv_shortcut - - def forward(self, x, temb=None, zemb=None): - h = self.act(self.GroupNorm_0(x, zemb)) - h = self.Conv_0(h) - if temb is not None: - h += self.Dense_0(self.act(temb))[:, :, None, None] - h = self.act(self.GroupNorm_1(h, zemb)) - h = self.Dropout_0(h) - h = self.Conv_1(h) - if x.shape[1] != self.out_ch: - if self.conv_shortcut: - x = self.Conv_2(x) - else: - x = self.NIN_0(x) - if not self.skip_rescale: - return x + h - else: - return (x + h) / np.sqrt(2.) - - -class ResnetBlockBigGANpp_Adagn(nn.Module): - def __init__(self, act, in_ch, out_ch=None, temb_dim=None, zemb_dim=None, up=False, down=False, - dropout=0.1, fir=False, fir_kernel=(1, 3, 3, 1), - skip_rescale=True, init_scale=0.): - super().__init__() - - out_ch = out_ch if out_ch else in_ch - self.GroupNorm_0 = AdaptiveGroupNorm(min(in_ch // 4, 32), in_ch, zemb_dim) - - self.up = up - self.down = down - self.fir = fir - self.fir_kernel = fir_kernel - - self.Conv_0 = conv3x3(in_ch, out_ch) - if temb_dim is not None: - self.Dense_0 = nn.Linear(temb_dim, out_ch) - self.Dense_0.weight.data = default_init()(self.Dense_0.weight.shape) - nn.init.zeros_(self.Dense_0.bias) - - self.GroupNorm_1 = AdaptiveGroupNorm(min(out_ch // 4, 32), out_ch, zemb_dim) - self.Dropout_0 = nn.Dropout(dropout) - self.Conv_1 = conv3x3(out_ch, out_ch, init_scale=init_scale) - if in_ch != out_ch or up or down: - self.Conv_2 = conv1x1(in_ch, out_ch) - - self.skip_rescale = skip_rescale - self.act = act - self.in_ch = in_ch - self.out_ch = out_ch - - def forward(self, x, temb=None, zemb=None): - h = self.act(self.GroupNorm_0(x, zemb)) - - if self.up: - if self.fir: - h = up_or_down_sampling.upsample_2d(h, self.fir_kernel, factor=2) - x = up_or_down_sampling.upsample_2d(x, self.fir_kernel, factor=2) - else: - h = up_or_down_sampling.naive_upsample_2d(h, factor=2) - x = up_or_down_sampling.naive_upsample_2d(x, factor=2) - elif self.down: - if self.fir: - h = up_or_down_sampling.downsample_2d(h, self.fir_kernel, factor=2) - x = up_or_down_sampling.downsample_2d(x, self.fir_kernel, factor=2) - else: - h = up_or_down_sampling.naive_downsample_2d(h, factor=2) - x = up_or_down_sampling.naive_downsample_2d(x, factor=2) - - h = self.Conv_0(h) - # Add bias to each feature map conditioned on the time embedding - if temb is not None: - h += self.Dense_0(self.act(temb))[:, :, None, None] - h = self.act(self.GroupNorm_1(h, zemb)) - h = self.Dropout_0(h) - h = self.Conv_1(h) - - if self.in_ch != self.out_ch or self.up or self.down: - x = self.Conv_2(x) - - if not self.skip_rescale: - return x + h - else: - return (x + h) / np.sqrt(2.) - - -class ResnetBlockBigGANpp_Adagn_one(nn.Module): - def __init__(self, act, in_ch, out_ch=None, temb_dim=None, zemb_dim=None, up=False, down=False, - dropout=0.1, fir=False, fir_kernel=(1, 3, 3, 1), - skip_rescale=True, init_scale=0.): - super().__init__() - - out_ch = out_ch if out_ch else in_ch - self.GroupNorm_0 = AdaptiveGroupNorm(min(in_ch // 4, 32), in_ch, zemb_dim) - - self.up = up - self.down = down - self.fir = fir - self.fir_kernel = fir_kernel - - self.Conv_0 = conv3x3(in_ch, out_ch) - if temb_dim is not None: - self.Dense_0 = nn.Linear(temb_dim, out_ch) - self.Dense_0.weight.data = default_init()(self.Dense_0.weight.shape) - nn.init.zeros_(self.Dense_0.bias) - - - self.GroupNorm_1 = nn.GroupNorm(num_groups=min(out_ch // 4, 32), num_channels=out_ch, eps=1e-6) - - self.Dropout_0 = nn.Dropout(dropout) - self.Conv_1 = conv3x3(out_ch, out_ch, init_scale=init_scale) - if in_ch != out_ch or up or down: - self.Conv_2 = conv1x1(in_ch, out_ch) - - self.skip_rescale = skip_rescale - self.act = act - self.in_ch = in_ch - self.out_ch = out_ch - - def forward(self, x, temb=None, zemb=None): - h = self.act(self.GroupNorm_0(x, zemb)) - - if self.up: - if self.fir: - h = up_or_down_sampling.upsample_2d(h, self.fir_kernel, factor=2) - x = up_or_down_sampling.upsample_2d(x, self.fir_kernel, factor=2) - else: - h = up_or_down_sampling.naive_upsample_2d(h, factor=2) - x = up_or_down_sampling.naive_upsample_2d(x, factor=2) - elif self.down: - if self.fir: - h = up_or_down_sampling.downsample_2d(h, self.fir_kernel, factor=2) - x = up_or_down_sampling.downsample_2d(x, self.fir_kernel, factor=2) - else: - h = up_or_down_sampling.naive_downsample_2d(h, factor=2) - x = up_or_down_sampling.naive_downsample_2d(x, factor=2) - - h = self.Conv_0(h) - # Add bias to each feature map conditioned on the time embedding - if temb is not None: - h += self.Dense_0(self.act(temb))[:, :, None, None] - h = self.act(self.GroupNorm_1(h)) - h = self.Dropout_0(h) - h = self.Conv_1(h) - - - if self.in_ch != self.out_ch or self.up or self.down: - x = self.Conv_2(x) - - if not self.skip_rescale: - return x + h - else: - return (x + h) / np.sqrt(2.) - diff --git a/spaces/meraGPT/meraKB/brain.py b/spaces/meraGPT/meraKB/brain.py deleted file mode 100644 index c7e5e4bab4137f98eae3432b2865c9a179cd54cc..0000000000000000000000000000000000000000 --- a/spaces/meraGPT/meraKB/brain.py +++ /dev/null @@ -1,40 +0,0 @@ -import numpy as np -import streamlit as st - - -def brain(supabase): - ## List all documents - response = supabase.table("documents").select("name:metadata->>file_name, size:metadata->>file_size", count="exact").filter('metadata->>user', 'eq', st.session_state["username"]).execute() - - documents = response.data # Access the data from the response - - # Convert each dictionary to a tuple of items, then to a set to remove duplicates, and then back to a dictionary - unique_data = [dict(t) for t in set(tuple(d.items()) for d in documents)] - - # Sort the list of documents by size in decreasing order - unique_data.sort(key=lambda x: int(x['size']), reverse=True) - - # Display some metrics at the top of the page - col1, col2 = st.columns(2) - col1.metric(label="Total Documents", value=len(unique_data)) - col2.metric(label="Total Size (bytes)", value=sum(int(doc['size']) for doc in unique_data)) - - for document in unique_data: - # Create a unique key for each button by using the document name - button_key = f"delete_{document['name']}" - - # Display the document name, size and the delete button on the same line - col1, col2, col3 = st.columns([3, 1, 1]) - col1.markdown(f"**{document['name']}** ({document['size']} bytes)") - - if col2.button('❌', key=button_key): - delete_document(supabase, document['name']) - -def delete_document(supabase, document_name): - # Delete the document from the database - response = supabase.table("documents").delete().match({"metadata->>file_name": document_name}).execute() - # Check if the deletion was successful - if len(response.data) > 0: - st.write(f"✂️ {document_name} was deleted.") - else: - st.write(f"❌ {document_name} was not deleted.") diff --git a/spaces/merve/anonymization/public/anonymization/init.js b/spaces/merve/anonymization/public/anonymization/init.js deleted file mode 100644 index 5e181d580ff878e75ebbd508b052866e42c2ac1a..0000000000000000000000000000000000000000 --- a/spaces/merve/anonymization/public/anonymization/init.js +++ /dev/null @@ -1,77 +0,0 @@ -d3.select('body').selectAppend('div.tooltip.tooltip-hidden') - -window.ages = '18 19 20 21 22'.split(' ') -window.states = 'RI NH NY CT VT'.split(' ') - -window.init = function(){ - // console.clear() - var graphSel = d3.select('#graph').html('').append('div') - window.c = d3.conventions({ - sel: graphSel, - width: 460, - height: 460, - }) - - function sizeGraphSel(){ - var clientWidth = d3.select('body').node().clientWidth - - window.scale = d3.clamp(1, (c.totalWidth + 35)/(clientWidth - 10), 2) // off by one, s is 35 - - graphSel.st({ - transform: `scale(${1/scale})`, - transformOrigin: `0px 0px`, - }) - - d3.select('#graph').st({height: scale == 1 ? 500 : 710}) - } - sizeGraphSel() - d3.select(window).on('resize', sizeGraphSel) - - - c.svg = c.svg.append('g').translate([.5, .5]) - - window.axii = makeAxii() - window.sliders = makeSliders() - window.students = makeStudents() - window.sel = makeSel() - window.slides = makeSlides() - window.estimates = makeEstimates() - - - - - var error = 0 - while (error < .02 || error > .05){ - estimates.flipCoin() - error = Math.abs(estimates.active.val - .5) - } - - makeGS() -} - -init() - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spaces/merve/gradio-analysis-dashboard/README.md b/spaces/merve/gradio-analysis-dashboard/README.md deleted file mode 100644 index 71148ffa6d68872abbbfcf0342c1a0f3b1f90061..0000000000000000000000000000000000000000 --- a/spaces/merve/gradio-analysis-dashboard/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Gradio Analysis Dashboard -emoji: 📈 -colorFrom: green -colorTo: red -sdk: gradio -sdk_version: 3.3 -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/metricspace/OcTra/app.py b/spaces/metricspace/OcTra/app.py deleted file mode 100644 index 4c03f448b0dbf95a067bc4738a463c9bd9c5a92c..0000000000000000000000000000000000000000 --- a/spaces/metricspace/OcTra/app.py +++ /dev/null @@ -1,317 +0,0 @@ - -# load the libraries for the application -# ------------------------------------------- -import os -import re -import nltk -import torch -import librosa -import tempfile -import subprocess - -import gradio as gr - -from scipy.io import wavfile -from nnet import utils, commons -from transformers import pipeline -from scipy.io.wavfile import write -from faster_whisper import WhisperModel -from nnet.models import SynthesizerTrn as vitsTRN -from nnet.models_vc import SynthesizerTrn as freeTRN -from nnet.mel_processing import mel_spectrogram_torch -from configurations.get_constants import constantConfig - -from speaker_encoder.voice_encoder import SpeakerEncoder - -from df_local.enhance import enhance, init_df, load_audio, save_audio -from configurations.get_hyperparameters import hyperparameterConfig -from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline - -nltk.download('punkt') -from nltk.tokenize import sent_tokenize - -# making the FreeVC function -# --------------------------------- -class FreeVCModel: - def __init__(self, config, ptfile, speaker_model, wavLM_model, device='cpu'): - self.hps = utils.get_hparams_from_file(config) - - self.net_g = freeTRN( - self.hps.data.filter_length // 2 + 1, - self.hps.train.segment_size // self.hps.data.hop_length, - **self.hps.model - ).to(hyperparameters.device) - _ = self.net_g.eval() - _ = utils.load_checkpoint(ptfile, self.net_g, None, True) - - self.cmodel = utils.get_cmodel(device, wavLM_model) - - if self.hps.model.use_spk: - self.smodel = SpeakerEncoder(speaker_model) - - def convert(self, src, tgt): - fs_src, src_audio = src - fs_tgt, tgt_audio = tgt - - src = f"{constants.temp_audio_folder}/src.wav" - tgt = f"{constants.temp_audio_folder}/tgt.wav" - out = f"{constants.temp_audio_folder}/cnvr.wav" - with torch.no_grad(): - wavfile.write(tgt, fs_tgt, tgt_audio) - wav_tgt, _ = librosa.load(tgt, sr=self.hps.data.sampling_rate) - wav_tgt, _ = librosa.effects.trim(wav_tgt, top_db=20) - if self.hps.model.use_spk: - g_tgt = self.smodel.embed_utterance(wav_tgt) - g_tgt = torch.from_numpy(g_tgt).unsqueeze(0).to(hyperparameters.device.type) - else: - wav_tgt = torch.from_numpy(wav_tgt).unsqueeze(0).to(hyperparameters.device.type) - mel_tgt = mel_spectrogram_torch( - wav_tgt, - self.hps.data.filter_length, - self.hps.data.n_mel_channels, - self.hps.data.sampling_rate, - self.hps.data.hop_length, - self.hps.data.win_length, - self.hps.data.mel_fmin, - self.hps.data.mel_fmax, - ) - wavfile.write(src, fs_src, src_audio) - wav_src, _ = librosa.load(src, sr=self.hps.data.sampling_rate) - wav_src = torch.from_numpy(wav_src).unsqueeze(0).to(hyperparameters.device.type) - c = utils.get_content(self.cmodel, wav_src) - - if self.hps.model.use_spk: - audio = self.net_g.infer(c, g=g_tgt) - else: - audio = self.net_g.infer(c, mel=mel_tgt) - audio = audio[0][0].data.cpu().float().numpy() - write(out, 24000, audio) - - return out - -# load the system configurations -constants = constantConfig() -hyperparameters = hyperparameterConfig() - -# load the models -model, df_state, _ = init_df(hyperparameters.voice_enhacing_model, config_allow_defaults=True) # voice enhancing model -stt_model = WhisperModel(hyperparameters.stt_model, device=hyperparameters.device.type, compute_type="float32") #speech to text model - -trans_model = AutoModelForSeq2SeqLM.from_pretrained(constants.model_name_dict[hyperparameters.nllb_model], torch_dtype=torch.bfloat16).to(hyperparameters.device) -trans_tokenizer = AutoTokenizer.from_pretrained(constants.model_name_dict[hyperparameters.nllb_model]) - -modelConvertSpeech = FreeVCModel(config=hyperparameters.text2speech_config, ptfile=hyperparameters.text2speech_model, - speaker_model=hyperparameters.text2speech_encoder, wavLM_model=hyperparameters.wavlm_model, - device=hyperparameters.device.type) - -# download the language model if doesn't existing -# ---------------------------------------------------- -def download(lang, lang_directory): - - if not os.path.exists(f"{lang_directory}/{lang}"): - cmd = ";".join([ - f"wget {constants.language_download_web}/{lang}.tar.gz -O {lang_directory}/{lang}.tar.gz", - f"tar zxvf {lang_directory}/{lang}.tar.gz -C {lang_directory}" - ]) - subprocess.check_output(cmd, shell=True) - try: - os.remove(f"{lang_directory}/{lang}.tar.gz") - except: - pass - return f"{lang_directory}/{lang}" - -def preprocess_char(text, lang=None): - """ - Special treatement of characters in certain languages - """ - if lang == 'ron': - text = text.replace("ț", "ţ") - return text - -def preprocess_text(txt, text_mapper, hps, uroman_dir=None, lang=None): - txt = preprocess_char(txt, lang=lang) - is_uroman = hps.data.training_files.split('.')[-1] == 'uroman' - if is_uroman: - txt = text_mapper.uromanize(txt, f'{uroman_dir}/bin/uroman.pl') - - txt = txt.lower() - txt = text_mapper.filter_oov(txt) - return txt - -def detect_language(text,LID): - predictions = LID.predict(text) - detected_lang_code = predictions[0][0].replace("__label__", "") - return detected_lang_code - -# text to speech -class TextMapper(object): - def __init__(self, vocab_file): - self.symbols = [x.replace("\n", "") for x in open(vocab_file, encoding="utf-8").readlines()] - self.SPACE_ID = self.symbols.index(" ") - self._symbol_to_id = {s: i for i, s in enumerate(self.symbols)} - self._id_to_symbol = {i: s for i, s in enumerate(self.symbols)} - - def text_to_sequence(self, text, cleaner_names): - '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. - Args: - text: string to convert to a sequence - cleaner_names: names of the cleaner functions to run the text through - Returns: - List of integers corresponding to the symbols in the text - ''' - sequence = [] - clean_text = text.strip() - for symbol in clean_text: - symbol_id = self._symbol_to_id[symbol] - sequence += [symbol_id] - return sequence - - def uromanize(self, text, uroman_pl): - with tempfile.NamedTemporaryFile() as tf, \ - tempfile.NamedTemporaryFile() as tf2: - with open(tf.name, "w") as f: - f.write("\n".join([text])) - cmd = f"perl " + uroman_pl - cmd += f" -l xxx " - cmd += f" < {tf.name} > {tf2.name}" - os.system(cmd) - outtexts = [] - with open(tf2.name) as f: - for line in f: - line = re.sub(r"\s+", " ", line).strip() - outtexts.append(line) - outtext = outtexts[0] - return outtext - - def get_text(self, text, hps): - text_norm = self.text_to_sequence(text, hps.data.text_cleaners) - if hps.data.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def filter_oov(self, text): - val_chars = self._symbol_to_id - txt_filt = "".join(list(filter(lambda x: x in val_chars, text))) - return txt_filt - -def speech_to_text(audio_file): - try: - fs, audio = audio_file - wavfile.write(constants.input_speech_file, fs, audio) - audio0, _ = load_audio(constants.input_speech_file, sr=df_state.sr()) - - # Enhance the SNR of the audio - enhanced = enhance(model, df_state, audio0) - save_audio(constants.enhanced_speech_file, enhanced, df_state.sr()) - - segments, info = stt_model.transcribe(constants.enhanced_speech_file) - - speech_text = '' - for segment in segments: - speech_text = f'{speech_text}{segment.text}' - try: - source_lang_nllb = [k for k, v in constants.flores_codes_to_tts_codes.items() if v[:2] == info.language][0] - except: - source_lang_nllb = 'language cant be determined, select manually' - - # text translation - return speech_text, gr.Dropdown.update(value=source_lang_nllb) - except: - return '', gr.Dropdown.update(value='English') - -# Text tp speech -def text_to_speech(text, target_lang): - txt = text - - # LANG = get_target_tts_lang(target_lang) - LANG = constants.flores_codes_to_tts_codes[target_lang] - ckpt_dir = download(LANG, lang_directory=constants.language_directory) - - vocab_file = f"{ckpt_dir}/{constants.language_vocab_text}" - config_file = f"{ckpt_dir}/{constants.language_vocab_configuration}" - hps = utils.get_hparams_from_file(config_file) - text_mapper = TextMapper(vocab_file) - net_g = vitsTRN( - len(text_mapper.symbols), - hps.data.filter_length // 2 + 1, - hps.train.segment_size // hps.data.hop_length, - **hps.model) - net_g.to(hyperparameters.device) - _ = net_g.eval() - - g_pth = f"{ckpt_dir}/{constants.language_vocab_model}" - - _ = utils.load_checkpoint(g_pth, net_g, None) - - txt = preprocess_text(txt, text_mapper, hps, lang=LANG, uroman_dir=constants.uroman_directory) - stn_tst = text_mapper.get_text(txt, hps) - with torch.no_grad(): - x_tst = stn_tst.unsqueeze(0).to(hyperparameters.device) - x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(hyperparameters.device) - hyp = net_g.infer( - x_tst, x_tst_lengths, noise_scale=.667, - noise_scale_w=0.8, length_scale=1.0 - )[0][0,0].cpu().float().numpy() - - return hps.data.sampling_rate, hyp - -def translation(audio, text, source_lang_nllb, target_code_nllb, output_type, sentence_mode): - target_code = constants.flores_codes[target_code_nllb] - translator = pipeline('translation', model=trans_model, tokenizer=trans_tokenizer, src_lang=source_lang_nllb, tgt_lang=target_code, device=hyperparameters.device) - - # output = translator(text, max_length=400)[0]['translation_text'] - if sentence_mode == "Sentence-wise": - sentences = sent_tokenize(text) - translated_sentences = [] - for sentence in sentences: - translated_sentence = translator(sentence, max_length=400)[0]['translation_text'] - translated_sentences.append(translated_sentence) - output = ' '.join(translated_sentences) - else: - output = translator(text, max_length=1024)[0]['translation_text'] - - # get the text to speech - fs_out, audio_out = text_to_speech(output, target_code_nllb) - - if output_type == 'own voice': - out_file = modelConvertSpeech.convert((fs_out, audio_out), audio) - return output, out_file - - wavfile.write(constants.text2speech_wavfile, fs_out, audio_out) - return output, constants.text2speech_wavfile - -with gr.Blocks(title = "Octopus Translation App") as octopus_translator: - with gr.Row(): - audio_file = gr.Audio(source="microphone") - - with gr.Row(): - input_text = gr.Textbox(label="Input text") - source_language = gr.Dropdown(list(constants.flores_codes.keys()), value='English', label='Source (Autoselected)', interactive=True) - - with gr.Row(): - output_text = gr.Textbox(label='Translated text') - target_language = gr.Dropdown(list(constants.flores_codes.keys()), value='German', label='Target', interactive=True) - - - with gr.Row(): - output_speech = gr.Audio(label='Translated speech') - translate_button = gr.Button('Translate') - - - with gr.Row(): - enhance_audio = gr.Radio(['yes', 'no'], value='yes', label='Enhance input voice', interactive=True) - input_type = gr.Radio(['Whole text', 'Sentence-wise'],value='Sentence-wise', label="Translation Mode", interactive=True) - output_audio_type = gr.Radio(['standard speaker', 'voice transfer'], value='voice transfer', label='Enhance output voice', interactive=True) - - audio_file.change(speech_to_text, - inputs=[audio_file], - outputs=[input_text, source_language]) - - translate_button.click(translation, - inputs=[audio_file, input_text, - source_language, target_language, - output_audio_type, input_type], - outputs=[output_text, output_speech]) - -octopus_translator.launch(share=False) diff --git a/spaces/mfrashad/CharacterGAN/netdissect/broden.py b/spaces/mfrashad/CharacterGAN/netdissect/broden.py deleted file mode 100644 index 854e87a46839c837b43cba5347967ce74ae4bf35..0000000000000000000000000000000000000000 --- a/spaces/mfrashad/CharacterGAN/netdissect/broden.py +++ /dev/null @@ -1,271 +0,0 @@ -import os, errno, numpy, torch, csv, re, shutil, os, zipfile -from collections import OrderedDict -from torchvision.datasets.folder import default_loader -from torchvision import transforms -from scipy import ndimage -from urllib.request import urlopen - -class BrodenDataset(torch.utils.data.Dataset): - ''' - A multicategory segmentation data set. - - Returns three streams: - (1) The image (3, h, w). - (2) The multicategory segmentation (labelcount, h, w). - (3) A bincount of pixels in the segmentation (labelcount). - - Net dissect also assumes that the dataset object has three properties - with human-readable labels: - - ds.labels = ['red', 'black', 'car', 'tree', 'grid', ...] - ds.categories = ['color', 'part', 'object', 'texture'] - ds.label_category = [0, 0, 2, 2, 3, ...] # The category for each label - ''' - def __init__(self, directory='dataset/broden', resolution=384, - split='train', categories=None, - transform=None, transform_segment=None, - download=False, size=None, include_bincount=True, - broden_version=1, max_segment_depth=6): - assert resolution in [224, 227, 384] - if download: - ensure_broden_downloaded(directory, resolution, broden_version) - self.directory = directory - self.resolution = resolution - self.resdir = os.path.join(directory, 'broden%d_%d' % - (broden_version, resolution)) - self.loader = default_loader - self.transform = transform - self.transform_segment = transform_segment - self.include_bincount = include_bincount - # The maximum number of multilabel layers that coexist at an image. - self.max_segment_depth = max_segment_depth - with open(os.path.join(self.resdir, 'category.csv'), - encoding='utf-8') as f: - self.category_info = OrderedDict() - for row in csv.DictReader(f): - self.category_info[row['name']] = row - if categories is not None: - # Filter out unused categories - categories = set([c for c in categories if c in self.category_info]) - for cat in list(self.category_info.keys()): - if cat not in categories: - del self.category_info[cat] - categories = list(self.category_info.keys()) - self.categories = categories - - # Filter out unneeded images. - with open(os.path.join(self.resdir, 'index.csv'), - encoding='utf-8') as f: - all_images = [decode_index_dict(r) for r in csv.DictReader(f)] - self.image = [row for row in all_images - if index_has_any_data(row, categories) and row['split'] == split] - if size is not None: - self.image = self.image[:size] - with open(os.path.join(self.resdir, 'label.csv'), - encoding='utf-8') as f: - self.label_info = build_dense_label_array([ - decode_label_dict(r) for r in csv.DictReader(f)]) - self.labels = [l['name'] for l in self.label_info] - # Build dense remapping arrays for labels, so that you can - # get dense ranges of labels for each category. - self.category_map = {} - self.category_unmap = {} - self.category_label = {} - for cat in self.categories: - with open(os.path.join(self.resdir, 'c_%s.csv' % cat), - encoding='utf-8') as f: - c_data = [decode_label_dict(r) for r in csv.DictReader(f)] - self.category_unmap[cat], self.category_map[cat] = ( - build_numpy_category_map(c_data)) - self.category_label[cat] = build_dense_label_array( - c_data, key='code') - self.num_labels = len(self.labels) - # Primary categories for each label is the category in which it - # appears with the maximum coverage. - self.label_category = numpy.zeros(self.num_labels, dtype=int) - for i in range(self.num_labels): - maxcoverage, self.label_category[i] = max( - (self.category_label[cat][self.category_map[cat][i]]['coverage'] - if i < len(self.category_map[cat]) - and self.category_map[cat][i] else 0, ic) - for ic, cat in enumerate(categories)) - - def __len__(self): - return len(self.image) - - def __getitem__(self, idx): - record = self.image[idx] - # example record: { - # 'image': 'opensurfaces/25605.jpg', 'split': 'train', - # 'ih': 384, 'iw': 384, 'sh': 192, 'sw': 192, - # 'color': ['opensurfaces/25605_color.png'], - # 'object': [], 'part': [], - # 'material': ['opensurfaces/25605_material.png'], - # 'scene': [], 'texture': []} - image = self.loader(os.path.join(self.resdir, 'images', - record['image'])) - segment = numpy.zeros(shape=(self.max_segment_depth, - record['sh'], record['sw']), dtype=int) - if self.include_bincount: - bincount = numpy.zeros(shape=(self.num_labels,), dtype=int) - depth = 0 - for cat in self.categories: - for layer in record[cat]: - if isinstance(layer, int): - segment[depth,:,:] = layer - if self.include_bincount: - bincount[layer] += segment.shape[1] * segment.shape[2] - else: - png = numpy.asarray(self.loader(os.path.join( - self.resdir, 'images', layer))) - segment[depth,:,:] = png[:,:,0] + png[:,:,1] * 256 - if self.include_bincount: - bincount += numpy.bincount(segment[depth,:,:].flatten(), - minlength=self.num_labels) - depth += 1 - if self.transform: - image = self.transform(image) - if self.transform_segment: - segment = self.transform_segment(segment) - if self.include_bincount: - bincount[0] = 0 - return (image, segment, bincount) - else: - return (image, segment) - -def build_dense_label_array(label_data, key='number', allow_none=False): - ''' - Input: set of rows with 'number' fields (or another field name key). - Output: array such that a[number] = the row with the given number. - ''' - result = [None] * (max([d[key] for d in label_data]) + 1) - for d in label_data: - result[d[key]] = d - # Fill in none - if not allow_none: - example = label_data[0] - def make_empty(k): - return dict((c, k if c is key else type(v)()) - for c, v in example.items()) - for i, d in enumerate(result): - if d is None: - result[i] = dict(make_empty(i)) - return result - -def build_numpy_category_map(map_data, key1='code', key2='number'): - ''' - Input: set of rows with 'number' fields (or another field name key). - Output: array such that a[number] = the row with the given number. - ''' - results = list(numpy.zeros((max([d[key] for d in map_data]) + 1), - dtype=numpy.int16) for key in (key1, key2)) - for d in map_data: - results[0][d[key1]] = d[key2] - results[1][d[key2]] = d[key1] - return results - -def index_has_any_data(row, categories): - for c in categories: - for data in row[c]: - if data: return True - return False - -def decode_label_dict(row): - result = {} - for key, val in row.items(): - if key == 'category': - result[key] = dict((c, int(n)) - for c, n in [re.match('^([^(]*)\(([^)]*)\)$', f).groups() - for f in val.split(';')]) - elif key == 'name': - result[key] = val - elif key == 'syns': - result[key] = val.split(';') - elif re.match('^\d+$', val): - result[key] = int(val) - elif re.match('^\d+\.\d*$', val): - result[key] = float(val) - else: - result[key] = val - return result - -def decode_index_dict(row): - result = {} - for key, val in row.items(): - if key in ['image', 'split']: - result[key] = val - elif key in ['sw', 'sh', 'iw', 'ih']: - result[key] = int(val) - else: - item = [s for s in val.split(';') if s] - for i, v in enumerate(item): - if re.match('^\d+$', v): - item[i] = int(v) - result[key] = item - return result - -class ScaleSegmentation: - ''' - Utility for scaling segmentations, using nearest-neighbor zooming. - ''' - def __init__(self, target_height, target_width): - self.target_height = target_height - self.target_width = target_width - def __call__(self, seg): - ratio = (1, self.target_height / float(seg.shape[1]), - self.target_width / float(seg.shape[2])) - return ndimage.zoom(seg, ratio, order=0) - -def scatter_batch(seg, num_labels, omit_zero=True, dtype=torch.uint8): - ''' - Utility for scattering semgentations into a one-hot representation. - ''' - result = torch.zeros(*((seg.shape[0], num_labels,) + seg.shape[2:]), - dtype=dtype, device=seg.device) - result.scatter_(1, seg, 1) - if omit_zero: - result[:,0] = 0 - return result - -def ensure_broden_downloaded(directory, resolution, broden_version=1): - assert resolution in [224, 227, 384] - baseurl = 'http://netdissect.csail.mit.edu/data/' - dirname = 'broden%d_%d' % (broden_version, resolution) - if os.path.isfile(os.path.join(directory, dirname, 'index.csv')): - return # Already downloaded - zipfilename = 'broden1_%d.zip' % resolution - download_dir = os.path.join(directory, 'download') - os.makedirs(download_dir, exist_ok=True) - full_zipfilename = os.path.join(download_dir, zipfilename) - if not os.path.exists(full_zipfilename): - url = '%s/%s' % (baseurl, zipfilename) - print('Downloading %s' % url) - data = urlopen(url) - with open(full_zipfilename, 'wb') as f: - f.write(data.read()) - print('Unzipping %s' % zipfilename) - with zipfile.ZipFile(full_zipfilename, 'r') as zip_ref: - zip_ref.extractall(directory) - assert os.path.isfile(os.path.join(directory, dirname, 'index.csv')) - -def test_broden_dataset(): - ''' - Testing code. - ''' - bds = BrodenDataset('dataset/broden', resolution=384, - transform=transforms.Compose([ - transforms.Resize(224), - transforms.ToTensor()]), - transform_segment=transforms.Compose([ - ScaleSegmentation(224, 224) - ]), - include_bincount=True) - loader = torch.utils.data.DataLoader(bds, batch_size=100, num_workers=24) - for i in range(1,20): - print(bds.label[i]['name'], - list(bds.category.keys())[bds.primary_category[i]]) - for i, (im, seg, bc) in enumerate(loader): - print(i, im.shape, seg.shape, seg.max(), bc.shape) - -if __name__ == '__main__': - test_broden_dataset() diff --git a/spaces/miaomiaoren/vits-uma-genshin-honkai/utils.py b/spaces/miaomiaoren/vits-uma-genshin-honkai/utils.py deleted file mode 100644 index ee4b01ddfbe8173965371b29f770f3e87615fe71..0000000000000000000000000000000000000000 --- a/spaces/miaomiaoren/vits-uma-genshin-honkai/utils.py +++ /dev/null @@ -1,225 +0,0 @@ -import os -import sys -import argparse -import logging -import json -import subprocess -import numpy as np -import librosa -import torch - -MATPLOTLIB_FLAG = False - -logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) -logger = logging - - -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']) - 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(): - 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 '{}' (iteration {})" .format( - checkpoint_path, iteration)) - return model, optimizer, learning_rate, iteration - - -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_audio_to_torch(full_path, target_sampling_rate): - audio, sampling_rate = librosa.load(full_path, sr=target_sampling_rate, mono=True) - return torch.FloatTensor(audio.astype(np.float32)) - - -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): - parser = argparse.ArgumentParser() - parser.add_argument('-c', '--config', type=str, default="./configs/base.json", - help='JSON file for configuration') - parser.add_argument('-m', '--model', type=str, required=True, - help='Model name') - - args = parser.parse_args() - model_dir = os.path.join("./logs", args.model) - - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - config_path = args.config - config_save_path = os.path.join(model_dir, "config.json") - if init: - with open(config_path, "r") as f: - data = f.read() - with open(config_save_path, "w") as f: - f.write(data) - else: - 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_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/mikeee/radiobee-aligner/docs/build/html/_static/css/badge_only.css b/spaces/mikeee/radiobee-aligner/docs/build/html/_static/css/badge_only.css deleted file mode 100644 index e380325bc6e273d9142c2369883d2a4b2a069cf1..0000000000000000000000000000000000000000 --- a/spaces/mikeee/radiobee-aligner/docs/build/html/_static/css/badge_only.css +++ /dev/null @@ -1 +0,0 @@ -.fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-style:normal;font-weight:400;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#FontAwesome) format("svg")}.fa:before{font-family:FontAwesome;font-style:normal;font-weight:400;line-height:1}.fa:before,a .fa{text-decoration:inherit}.fa:before,a .fa,li .fa{display:inline-block}li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before,.icon-book:before{content:"\f02d"}.fa-caret-down:before,.icon-caret-down:before{content:"\f0d7"}.fa-caret-up:before,.icon-caret-up:before{content:"\f0d8"}.fa-caret-left:before,.icon-caret-left:before{content:"\f0d9"}.fa-caret-right:before,.icon-caret-right:before{content:"\f0da"}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60}.rst-versions .rst-current-version:after{clear:both;content:"";display:block}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}} \ No newline at end of file diff --git a/spaces/mikeee/radiobee-aligner/tests/test_en_zh_short.py b/spaces/mikeee/radiobee-aligner/tests/test_en_zh_short.py deleted file mode 100644 index d344721865d9e1369b549aa63a1cdd23531226fc..0000000000000000000000000000000000000000 --- a/spaces/mikeee/radiobee-aligner/tests/test_en_zh_short.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Test loadtext.""" -# pylint: diable=invalid-name -import pytest - -from fastlid import fastlid - -from radiobee.loadtext import loadtext -from radiobee.files2df import files2df -from radiobee.file2text import file2text -from radiobee.lists2cmat import lists2cmat -from radiobee.cmat2tset import cmat2tset -from radiobee.gen_pset import gen_pset - -en = loadtext("data/en.txt") -zh = loadtext("data/zh.txt") -testen = loadtext("data/testen.txt") -testzh = loadtext("data/testzh.txt") - - -def test_en_zh_short1(): - """Test en_zh_short.""" - lst1 = [elm for elm in en.splitlines() if elm.strip()] - lst2 = [elm for elm in zh.splitlines() if elm.strip()] - - lang1, _ = fastlid(en) - lang2, _ = fastlid(zh) - - cmat0 = lists2cmat(lst1, lst2) - pset = gen_pset(cmat0) - - assert pset.__len__() > 2 - - -def test_en_zh_short2(): - """Test en_zh_short testen testzh.""" - # en = testen.copy() - # zh = testzh.copy() - lst1a = [elm for elm in testen.splitlines() if elm.strip()] - lst2a = [elm for elm in testzh.splitlines() if elm.strip()] - - lang1a, _ = fastlid(testen) - lang2a, _ = fastlid(testzh) - - cmat1 = lists2cmat(lst1a, lst2a) - pset = gen_pset(cmat1) - - assert pset.__len__() > 2 - - -_ = """ -import matplotlib -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd -import seaborn as sns - -sns.set() -sns.set_style("darkgrid") -cmap = "viridis_r" -plt.ion() - -eps = 6 -min_samples = 10 - - -tset = pd.DataFrame(cmat2tset(cmat)) -tset.columns = ["x", "y", "cos"] - -df_ = tset - -# """ diff --git a/spaces/mikeee/radiobee-aligner/tests/test_seg_text.py b/spaces/mikeee/radiobee-aligner/tests/test_seg_text.py deleted file mode 100644 index 38c989cd89ba843953f94eb96e1ed90de2eea130..0000000000000000000000000000000000000000 --- a/spaces/mikeee/radiobee-aligner/tests/test_seg_text.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Test seg_text.""" -import pytest -from radiobee.seg_text import seg_text - - -def test_seg_text1(): - """Test seg_text 1.""" - text = " text 1\n\n test 2. test 3" - _ = seg_text(text) - assert len(_) == 2 - - text = " text 1\n\n test 2. Test 3" - _ = seg_text(text) - assert len(_) == 3 - - -@pytest.mark.parametrize( - "test_input,expected", [ - ("", []), - (" ", []), - (" \n ", []), - ] -) -def test_seg_text_blanks(test_input, expected): - """Test blanks.""" - assert seg_text(test_input) == expected - - -def test_seg_text_semicolon(): - """Test semicolon.""" - text = """ “元宇宙”,英文為“Metaverse”。該詞出自1992年;的科幻小說《雪崩》。 """ - assert len(seg_text(text)) == 2 - assert len(seg_text(text, 'zh')) == 2 - assert len(seg_text(text, 'ja')) == 2 - assert len(seg_text(text, 'ko')) == 2 - assert len(seg_text(text, 'en')) == 1 - - -def test_seg_text_semicolon_extra(): - """Test semicolon.""" - extra = "[;;]" - text = """ “元宇宙”,英文為“Metaverse”。該詞出自1992年;的科幻小說《雪崩》。 """ - assert len(seg_text(text, extra=extra)) == 2 + 1 - assert len(seg_text(text, 'zh', extra=extra)) == 2 + 1 - assert len(seg_text(text, 'ja', extra=extra)) == 2 + 1 - assert len(seg_text(text, 'ko', extra=extra)) == 2 + 1 - assert len(seg_text(text, 'en', extra=extra)) == 1 + 1 diff --git a/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/modeling/backbone/swin.py b/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/modeling/backbone/swin.py deleted file mode 100644 index aa651bdab51bb353e3be4b5554f41e251803d5cb..0000000000000000000000000000000000000000 --- a/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/modeling/backbone/swin.py +++ /dev/null @@ -1,832 +0,0 @@ -# -------------------------------------------------------- -# Swin Transformer -# Copyright (c) 2021 Microsoft -# Licensed under The MIT License [see LICENSE for details] -# Written by Ze Liu, Yutong Lin, Yixuan Wei -# -------------------------------------------------------- - -# Copyright (c) Facebook, Inc. and its affiliates. -# Modified by Bowen Cheng from https://github.com/SwinTransformer/Swin-Transformer-Semantic-Segmentation/blob/main/mmseg/models/backbones/swin_transformer.py -# Copyright (c) Meta Platforms, Inc. All Rights Reserved - -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F -import torch.utils.checkpoint as checkpoint -from timm.models.layers import DropPath, to_2tuple, trunc_normal_ - -from detectron2.modeling import BACKBONE_REGISTRY, Backbone, ShapeSpec - - -class Mlp(nn.Module): - """Multilayer perceptron.""" - - def __init__( - self, - in_features, - hidden_features=None, - out_features=None, - act_layer=nn.GELU, - drop=0.0, - ): - super().__init__() - out_features = out_features or in_features - hidden_features = hidden_features or in_features - self.fc1 = nn.Linear(in_features, hidden_features) - self.act = act_layer() - self.fc2 = nn.Linear(hidden_features, out_features) - self.drop = nn.Dropout(drop) - - def forward(self, x): - x = self.fc1(x) - x = self.act(x) - x = self.drop(x) - x = self.fc2(x) - x = self.drop(x) - return x - - -def window_partition(x, window_size): - """ - Args: - x: (B, H, W, C) - window_size (int): window size - Returns: - windows: (num_windows*B, window_size, window_size, C) - """ - B, H, W, C = x.shape - x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) - windows = ( - x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) - ) - return windows - - -def window_reverse(windows, window_size, H, W): - """ - Args: - windows: (num_windows*B, window_size, window_size, C) - window_size (int): Window size - H (int): Height of image - W (int): Width of image - Returns: - x: (B, H, W, C) - """ - B = int(windows.shape[0] / (H * W / window_size / window_size)) - x = windows.view( - B, H // window_size, W // window_size, window_size, window_size, -1 - ) - x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) - return x - - -class WindowAttention(nn.Module): - """Window based multi-head self attention (W-MSA) module with relative position bias. - It supports both of shifted and non-shifted window. - Args: - dim (int): Number of input channels. - window_size (tuple[int]): The height and width of the window. - num_heads (int): Number of attention heads. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set - attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 - proj_drop (float, optional): Dropout ratio of output. Default: 0.0 - """ - - def __init__( - self, - dim, - window_size, - num_heads, - qkv_bias=True, - qk_scale=None, - attn_drop=0.0, - proj_drop=0.0, - ): - - super().__init__() - self.dim = dim - self.window_size = window_size # Wh, Ww - self.num_heads = num_heads - head_dim = dim // num_heads - self.scale = qk_scale or head_dim ** -0.5 - - # define a parameter table of relative position bias - self.relative_position_bias_table = nn.Parameter( - torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads) - ) # 2*Wh-1 * 2*Ww-1, nH - - # get pair-wise relative position index for each token inside the window - coords_h = torch.arange(self.window_size[0]) - coords_w = torch.arange(self.window_size[1]) - coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww - coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww - relative_coords = ( - coords_flatten[:, :, None] - coords_flatten[:, None, :] - ) # 2, Wh*Ww, Wh*Ww - relative_coords = relative_coords.permute( - 1, 2, 0 - ).contiguous() # Wh*Ww, Wh*Ww, 2 - relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 - relative_coords[:, :, 1] += self.window_size[1] - 1 - relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 - relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww - self.register_buffer("relative_position_index", relative_position_index) - - 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) - - trunc_normal_(self.relative_position_bias_table, std=0.02) - self.softmax = nn.Softmax(dim=-1) - - def forward(self, x, mask=None): - """Forward function. - Args: - x: input features with shape of (num_windows*B, N, C) - mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None - """ - 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) - - q = q * self.scale - attn = q @ k.transpose(-2, -1) - - relative_position_bias = self.relative_position_bias_table[ - self.relative_position_index.view(-1) - ].view( - self.window_size[0] * self.window_size[1], - self.window_size[0] * self.window_size[1], - -1, - ) # Wh*Ww,Wh*Ww,nH - relative_position_bias = relative_position_bias.permute( - 2, 0, 1 - ).contiguous() # nH, Wh*Ww, Wh*Ww - attn = attn + relative_position_bias.unsqueeze(0) - - if mask is not None: - nW = mask.shape[0] - attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze( - 1 - ).unsqueeze(0) - attn = attn.view(-1, self.num_heads, N, N) - attn = self.softmax(attn) - else: - attn = self.softmax(attn) - - 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 SwinTransformerBlock(nn.Module): - """Swin Transformer Block. - Args: - dim (int): Number of input channels. - num_heads (int): Number of attention heads. - window_size (int): Window size. - shift_size (int): Shift size for SW-MSA. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. - drop (float, optional): Dropout rate. Default: 0.0 - attn_drop (float, optional): Attention dropout rate. Default: 0.0 - drop_path (float, optional): Stochastic depth rate. Default: 0.0 - act_layer (nn.Module, optional): Activation layer. Default: nn.GELU - norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm - """ - - def __init__( - self, - dim, - num_heads, - window_size=7, - shift_size=0, - mlp_ratio=4.0, - qkv_bias=True, - qk_scale=None, - drop=0.0, - attn_drop=0.0, - drop_path=0.0, - act_layer=nn.GELU, - norm_layer=nn.LayerNorm, - ): - super().__init__() - self.dim = dim - self.num_heads = num_heads - self.window_size = window_size - self.shift_size = shift_size - self.mlp_ratio = mlp_ratio - assert ( - 0 <= self.shift_size < self.window_size - ), "shift_size must in 0-window_size" - - self.norm1 = norm_layer(dim) - self.attn = WindowAttention( - dim, - window_size=to_2tuple(self.window_size), - num_heads=num_heads, - qkv_bias=qkv_bias, - qk_scale=qk_scale, - attn_drop=attn_drop, - proj_drop=drop, - ) - - self.drop_path = DropPath(drop_path) if drop_path > 0.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, - ) - - self.H = None - self.W = None - - def forward(self, x, mask_matrix): - """Forward function. - Args: - x: Input feature, tensor size (B, H*W, C). - H, W: Spatial resolution of the input feature. - mask_matrix: Attention mask for cyclic shift. - """ - B, L, C = x.shape - H, W = self.H, self.W - assert L == H * W, "input feature has wrong size" - - shortcut = x - x = self.norm1(x) - x = x.view(B, H, W, C) - - # pad feature maps to multiples of window size - pad_l = pad_t = 0 - pad_r = (self.window_size - W % self.window_size) % self.window_size - pad_b = (self.window_size - H % self.window_size) % self.window_size - x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) - _, Hp, Wp, _ = x.shape - - # cyclic shift - if self.shift_size > 0: - shifted_x = torch.roll( - x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) - ) - attn_mask = mask_matrix - else: - shifted_x = x - attn_mask = None - - # partition windows - x_windows = window_partition( - shifted_x, self.window_size - ) # nW*B, window_size, window_size, C - x_windows = x_windows.view( - -1, self.window_size * self.window_size, C - ) # nW*B, window_size*window_size, C - - # W-MSA/SW-MSA - attn_windows = self.attn( - x_windows, mask=attn_mask - ) # nW*B, window_size*window_size, C - - # merge windows - attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) - shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C - - # reverse cyclic shift - if self.shift_size > 0: - x = torch.roll( - shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2) - ) - else: - x = shifted_x - - if pad_r > 0 or pad_b > 0: - x = x[:, :H, :W, :].contiguous() - - x = x.view(B, H * W, C) - - # FFN - x = shortcut + self.drop_path(x) - x = x + self.drop_path(self.mlp(self.norm2(x))) - - return x - - -class PatchMerging(nn.Module): - """Patch Merging Layer - Args: - dim (int): Number of input channels. - norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm - """ - - def __init__(self, dim, norm_layer=nn.LayerNorm): - super().__init__() - self.dim = dim - self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) - self.norm = norm_layer(4 * dim) - - def forward(self, x, H, W): - """Forward function. - Args: - x: Input feature, tensor size (B, H*W, C). - H, W: Spatial resolution of the input feature. - """ - B, L, C = x.shape - assert L == H * W, "input feature has wrong size" - - x = x.view(B, H, W, C) - - # padding - pad_input = (H % 2 == 1) or (W % 2 == 1) - if pad_input: - x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) - - x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C - x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C - x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C - x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C - x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C - x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C - - x = self.norm(x) - x = self.reduction(x) - - return x - - -class BasicLayer(nn.Module): - """A basic Swin Transformer layer for one stage. - Args: - dim (int): Number of feature channels - depth (int): Depths of this stage. - num_heads (int): Number of attention head. - window_size (int): Local window size. Default: 7. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. - qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True - qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. - drop (float, optional): Dropout rate. Default: 0.0 - attn_drop (float, optional): Attention dropout rate. Default: 0.0 - drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 - norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm - downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None - use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. - """ - - def __init__( - self, - dim, - depth, - num_heads, - window_size=7, - mlp_ratio=4.0, - qkv_bias=True, - qk_scale=None, - drop=0.0, - attn_drop=0.0, - drop_path=0.0, - norm_layer=nn.LayerNorm, - downsample=None, - use_checkpoint=False, - ): - super().__init__() - self.window_size = window_size - self.shift_size = window_size // 2 - self.depth = depth - self.use_checkpoint = use_checkpoint - - # build blocks - self.blocks = nn.ModuleList( - [ - SwinTransformerBlock( - dim=dim, - num_heads=num_heads, - window_size=window_size, - shift_size=0 if (i % 2 == 0) else window_size // 2, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, - qk_scale=qk_scale, - drop=drop, - attn_drop=attn_drop, - drop_path=drop_path[i] - if isinstance(drop_path, list) - else drop_path, - norm_layer=norm_layer, - ) - for i in range(depth) - ] - ) - - # patch merging layer - if downsample is not None: - self.downsample = downsample(dim=dim, norm_layer=norm_layer) - else: - self.downsample = None - - def forward(self, x, H, W): - """Forward function. - Args: - x: Input feature, tensor size (B, H*W, C). - H, W: Spatial resolution of the input feature. - """ - - # calculate attention mask for SW-MSA - Hp = int(np.ceil(H / self.window_size)) * self.window_size - Wp = int(np.ceil(W / self.window_size)) * self.window_size - img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 - h_slices = ( - slice(0, -self.window_size), - slice(-self.window_size, -self.shift_size), - slice(-self.shift_size, None), - ) - w_slices = ( - slice(0, -self.window_size), - slice(-self.window_size, -self.shift_size), - slice(-self.shift_size, None), - ) - cnt = 0 - for h in h_slices: - for w in w_slices: - img_mask[:, h, w, :] = cnt - cnt += 1 - - mask_windows = window_partition( - img_mask, self.window_size - ) # nW, window_size, window_size, 1 - mask_windows = mask_windows.view(-1, self.window_size * self.window_size) - attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) - attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( - attn_mask == 0, float(0.0) - ) - - for blk in self.blocks: - blk.H, blk.W = H, W - if self.use_checkpoint: - x = checkpoint.checkpoint(blk, x, attn_mask) - else: - x = blk(x, attn_mask) - if self.downsample is not None: - x_down = self.downsample(x, H, W) - Wh, Ww = (H + 1) // 2, (W + 1) // 2 - return x, H, W, x_down, Wh, Ww - else: - return x, H, W, x, H, W - - -class PatchEmbed(nn.Module): - """Image to Patch Embedding - Args: - patch_size (int): Patch token size. Default: 4. - in_chans (int): Number of input image channels. Default: 3. - embed_dim (int): Number of linear projection output channels. Default: 96. - norm_layer (nn.Module, optional): Normalization layer. Default: None - """ - - def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): - super().__init__() - patch_size = to_2tuple(patch_size) - self.patch_size = patch_size - - self.in_chans = in_chans - self.embed_dim = embed_dim - - self.proj = nn.Conv2d( - in_chans, embed_dim, kernel_size=patch_size, stride=patch_size - ) - if norm_layer is not None: - self.norm = norm_layer(embed_dim) - else: - self.norm = None - - def forward(self, x): - """Forward function.""" - # padding - _, _, H, W = x.size() - if W % self.patch_size[1] != 0: - x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) - if H % self.patch_size[0] != 0: - x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0])) - - x = self.proj(x) # B C Wh Ww - if self.norm is not None: - Wh, Ww = x.size(2), x.size(3) - x = x.flatten(2).transpose(1, 2) - x = self.norm(x) - x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww) - - return x - - -class SwinTransformer(nn.Module): - """Swin Transformer backbone. - A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - - https://arxiv.org/pdf/2103.14030 - Args: - pretrain_img_size (int): Input image size for training the pretrained model, - used in absolute postion embedding. Default 224. - patch_size (int | tuple(int)): Patch size. Default: 4. - in_chans (int): Number of input image channels. Default: 3. - embed_dim (int): Number of linear projection output channels. Default: 96. - depths (tuple[int]): Depths of each Swin Transformer stage. - num_heads (tuple[int]): Number of attention head of each stage. - window_size (int): Window size. Default: 7. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. - qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True - qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. - drop_rate (float): Dropout rate. - attn_drop_rate (float): Attention dropout rate. Default: 0. - drop_path_rate (float): Stochastic depth rate. Default: 0.2. - norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. - ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. - patch_norm (bool): If True, add normalization after patch embedding. Default: True. - out_indices (Sequence[int]): Output from which stages. - frozen_stages (int): Stages to be frozen (stop grad and set eval mode). - -1 means not freezing any parameters. - use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. - """ - - def __init__( - self, - pretrain_img_size=224, - patch_size=4, - in_chans=3, - embed_dim=96, - depths=[2, 2, 6, 2], - num_heads=[3, 6, 12, 24], - window_size=7, - mlp_ratio=4.0, - qkv_bias=True, - qk_scale=None, - drop_rate=0.0, - attn_drop_rate=0.0, - drop_path_rate=0.2, - norm_layer=nn.LayerNorm, - ape=False, - patch_norm=True, - out_indices=(0, 1, 2, 3), - norm_indices=None, - frozen_stages=-1, - use_checkpoint=False, - projection=False, - project_dim=256, - ): - super().__init__() - - self.pretrain_img_size = pretrain_img_size - self.num_layers = len(depths) - self.embed_dim = embed_dim - self.ape = ape - self.patch_norm = patch_norm - self.out_indices = out_indices - self.norm_indices = norm_indices if norm_indices is not None else out_indices - self.frozen_stages = frozen_stages - - # split image into non-overlapping patches - self.patch_embed = PatchEmbed( - patch_size=patch_size, - in_chans=in_chans, - embed_dim=embed_dim, - norm_layer=norm_layer if self.patch_norm else None, - ) - - # absolute position embedding - if self.ape: - pretrain_img_size = to_2tuple(pretrain_img_size) - patch_size = to_2tuple(patch_size) - patches_resolution = [ - pretrain_img_size[0] // patch_size[0], - pretrain_img_size[1] // patch_size[1], - ] - - self.absolute_pos_embed = nn.Parameter( - torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]) - ) - trunc_normal_(self.absolute_pos_embed, std=0.02) - - self.pos_drop = nn.Dropout(p=drop_rate) - - # stochastic depth - dpr = [ - x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) - ] # stochastic depth decay rule - - # build layers - self.layers = nn.ModuleList() - for i_layer in range(self.num_layers): - layer = BasicLayer( - dim=int(embed_dim * 2 ** i_layer), - depth=depths[i_layer], - num_heads=num_heads[i_layer], - window_size=window_size, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, - qk_scale=qk_scale, - drop=drop_rate, - attn_drop=attn_drop_rate, - drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], - norm_layer=norm_layer, - downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, - use_checkpoint=use_checkpoint, - ) - self.layers.append(layer) - - num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] - self.num_features = num_features - - # add a norm layer for each output - for i_layer in self.norm_indices: - if i_layer >= len(self.num_features): - continue - layer = norm_layer(num_features[i_layer]) - layer_name = f"norm{i_layer}" - self.add_module(layer_name, layer) - # add projector head - self.projection = projection - if projection: - self.project_dim = project_dim - self.norm = norm_layer(self.num_features[-1]) - self.projector = nn.Linear(self.num_features[-1], project_dim, bias=False) - self._freeze_stages() - - def _freeze_stages(self): - if self.frozen_stages >= 0: - self.patch_embed.eval() - for param in self.patch_embed.parameters(): - param.requires_grad = False - - if self.frozen_stages >= 1 and self.ape: - self.absolute_pos_embed.requires_grad = False - - if self.frozen_stages >= 2: - self.pos_drop.eval() - for i in range(0, self.frozen_stages - 1): - m = self.layers[i] - m.eval() - for param in m.parameters(): - param.requires_grad = False - - def init_weights(self, pretrained=None): - """Initialize the weights in backbone. - Args: - pretrained (str, optional): Path to pre-trained weights. - Defaults to None. - """ - - def _init_weights(m): - if isinstance(m, nn.Linear): - trunc_normal_(m.weight, std=0.02) - if isinstance(m, nn.Linear) and m.bias is not None: - nn.init.constant_(m.bias, 0) - elif isinstance(m, nn.LayerNorm): - nn.init.constant_(m.bias, 0) - nn.init.constant_(m.weight, 1.0) - - def forward(self, x): - """Forward function.""" - x = self.patch_embed(x) - - Wh, Ww = x.size(2), x.size(3) - if self.ape: - # interpolate the position embedding to the corresponding size - absolute_pos_embed = F.interpolate( - self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic" - ) - x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C - else: - x = x.flatten(2).transpose(1, 2) - x = self.pos_drop(x) - - outs = {} - for i in range(self.num_layers): - layer = self.layers[i] - x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww) - - if i in self.out_indices: - if i in self.norm_indices: - norm_layer = getattr(self, f"norm{i}") - x_out = norm_layer(x_out) - out = ( - x_out.view(-1, H, W, self.num_features[i]) - .permute(0, 3, 1, 2) - .contiguous() - ) - outs["res{}".format(i + 2)] = out - if self.projection: - x_out = self.norm(x_out) - x_out = x_out.view(-1, H, W, self.num_features[-1]).contiguous() - outs["fc"] = self.projector(x_out).permute(0, 3, 1, 2) - - return outs - - def train(self, mode=True): - """Convert the model into training mode while keep layers freezed.""" - super(SwinTransformer, self).train(mode) - self._freeze_stages() - - -@BACKBONE_REGISTRY.register() -class D2SwinTransformer(SwinTransformer, Backbone): - def __init__(self, cfg, input_shape): - - pretrain_img_size = cfg.MODEL.SWIN.PRETRAIN_IMG_SIZE - patch_size = cfg.MODEL.SWIN.PATCH_SIZE - in_chans = 3 - embed_dim = cfg.MODEL.SWIN.EMBED_DIM - depths = cfg.MODEL.SWIN.DEPTHS - num_heads = cfg.MODEL.SWIN.NUM_HEADS - window_size = cfg.MODEL.SWIN.WINDOW_SIZE - mlp_ratio = cfg.MODEL.SWIN.MLP_RATIO - qkv_bias = cfg.MODEL.SWIN.QKV_BIAS - qk_scale = cfg.MODEL.SWIN.QK_SCALE - drop_rate = cfg.MODEL.SWIN.DROP_RATE - attn_drop_rate = cfg.MODEL.SWIN.ATTN_DROP_RATE - drop_path_rate = cfg.MODEL.SWIN.DROP_PATH_RATE - norm_layer = nn.LayerNorm - ape = cfg.MODEL.SWIN.APE - patch_norm = cfg.MODEL.SWIN.PATCH_NORM - norm_indices = cfg.MODEL.SWIN.NORM_INDICES - projection = cfg.MODEL.SWIN.PROJECTION - project_dim = cfg.MODEL.SWIN.PROJECT_DIM - super().__init__( - pretrain_img_size, - patch_size, - in_chans, - embed_dim, - depths, - num_heads, - window_size, - mlp_ratio, - qkv_bias, - qk_scale, - drop_rate, - attn_drop_rate, - drop_path_rate, - norm_layer, - ape, - patch_norm, - norm_indices=norm_indices, - projection=projection, - project_dim=project_dim, - ) - - self._out_features = cfg.MODEL.SWIN.OUT_FEATURES - - self._out_feature_strides = { - "res2": 4, - "res3": 8, - "res4": 16, - "res5": 32, - "fc": 32, - } - self._out_feature_channels = { - "res2": self.num_features[0], - "res3": self.num_features[1], - "res4": self.num_features[2], - "res5": self.num_features[3], - "fc": self.num_features[3], - } - - def forward(self, x): - """ - Args: - x: Tensor of shape (N,C,H,W). H, W must be a multiple of ``self.size_divisibility``. - Returns: - dict[str->Tensor]: names and the corresponding features - """ - assert ( - x.dim() == 4 - ), f"SwinTransformer takes an input of shape (N, C, H, W). Got {x.shape} instead!" - outputs = {} - y = super().forward(x) - for k in y.keys(): - if k in self._out_features: - outputs[k] = y[k] - return outputs - - def output_shape(self): - return { - name: ShapeSpec( - channels=self._out_feature_channels[name], - stride=self._out_feature_strides[name], - ) - for name in self._out_features - } - - @property - def size_divisibility(self): - return 32 diff --git a/spaces/mohsenfayyaz/DecompX/DecompX/README.md b/spaces/mohsenfayyaz/DecompX/DecompX/README.md deleted file mode 100644 index 6b637d149896c0129532d49a03de22db31b3aebc..0000000000000000000000000000000000000000 --- a/spaces/mohsenfayyaz/DecompX/DecompX/README.md +++ /dev/null @@ -1 +0,0 @@ -# DecompX \ No newline at end of file diff --git a/spaces/mshkdm/VToonify/vtoonify/model/encoder/align_all_parallel.py b/spaces/mshkdm/VToonify/vtoonify/model/encoder/align_all_parallel.py deleted file mode 100644 index 05b520cd6590dc02ee533d3f0d69e6a364447d9f..0000000000000000000000000000000000000000 --- a/spaces/mshkdm/VToonify/vtoonify/model/encoder/align_all_parallel.py +++ /dev/null @@ -1,217 +0,0 @@ -""" -brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset) -author: lzhbrian (https://lzhbrian.me) -date: 2020.1.5 -note: code is heavily borrowed from - https://github.com/NVlabs/ffhq-dataset - http://dlib.net/face_landmark_detection.py.html - -requirements: - apt install cmake - conda install Pillow numpy scipy - pip install dlib - # download face landmark model from: - # http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 -""" -from argparse import ArgumentParser -import time -import numpy as np -import PIL -import PIL.Image -import os -import scipy -import scipy.ndimage -import dlib -import multiprocessing as mp -import math - -#from configs.paths_config import model_paths -SHAPE_PREDICTOR_PATH = 'shape_predictor_68_face_landmarks.dat'#model_paths["shape_predictor"] - - -def get_landmark(filepath, predictor): - """get landmark with dlib - :return: np.array shape=(68, 2) - """ - detector = dlib.get_frontal_face_detector() - if type(filepath) == str: - img = dlib.load_rgb_image(filepath) - else: - img = filepath - dets = detector(img, 1) - - if len(dets) == 0: - print('Error: no face detected!') - return None - - shape = None - for k, d in enumerate(dets): - shape = predictor(img, d) - - if shape is None: - print('Error: No face detected! If you are sure there are faces in your input, you may rerun the code several times until the face is detected. Sometimes the detector is unstable.') - t = list(shape.parts()) - a = [] - for tt in t: - a.append([tt.x, tt.y]) - lm = np.array(a) - return lm - - -def align_face(filepath, predictor): - """ - :param filepath: str - :return: PIL Image - """ - - lm = get_landmark(filepath, predictor) - if lm is None: - return None - - lm_chin = lm[0: 17] # left-right - lm_eyebrow_left = lm[17: 22] # left-right - lm_eyebrow_right = lm[22: 27] # left-right - lm_nose = lm[27: 31] # top-down - lm_nostrils = lm[31: 36] # top-down - lm_eye_left = lm[36: 42] # left-clockwise - lm_eye_right = lm[42: 48] # left-clockwise - lm_mouth_outer = lm[48: 60] # left-clockwise - lm_mouth_inner = lm[60: 68] # left-clockwise - - # Calculate auxiliary vectors. - eye_left = np.mean(lm_eye_left, axis=0) - eye_right = np.mean(lm_eye_right, axis=0) - eye_avg = (eye_left + eye_right) * 0.5 - eye_to_eye = eye_right - eye_left - mouth_left = lm_mouth_outer[0] - mouth_right = lm_mouth_outer[6] - mouth_avg = (mouth_left + mouth_right) * 0.5 - eye_to_mouth = mouth_avg - eye_avg - - # Choose oriented crop rectangle. - x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1] - x /= np.hypot(*x) - x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8) - y = np.flipud(x) * [-1, 1] - c = eye_avg + eye_to_mouth * 0.1 - quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y]) - qsize = np.hypot(*x) * 2 - - # read image - if type(filepath) == str: - img = PIL.Image.open(filepath) - else: - img = PIL.Image.fromarray(filepath) - - output_size = 256 - transform_size = 256 - enable_padding = True - - # Shrink. - shrink = int(np.floor(qsize / output_size * 0.5)) - if shrink > 1: - rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink))) - img = img.resize(rsize, PIL.Image.ANTIALIAS) - quad /= shrink - qsize /= shrink - - # Crop. - border = max(int(np.rint(qsize * 0.1)), 3) - crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), - int(np.ceil(max(quad[:, 1])))) - crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), - min(crop[3] + border, img.size[1])) - if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]: - img = img.crop(crop) - quad -= crop[0:2] - - # Pad. - pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), - int(np.ceil(max(quad[:, 1])))) - pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), - max(pad[3] - img.size[1] + border, 0)) - if enable_padding and max(pad) > border - 4: - pad = np.maximum(pad, int(np.rint(qsize * 0.3))) - img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect') - h, w, _ = img.shape - y, x, _ = np.ogrid[:h, :w, :1] - mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]), - 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3])) - blur = qsize * 0.02 - img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0) - img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0) - img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB') - quad += pad[:2] - - # Transform. - img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR) - if output_size < transform_size: - img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS) - - # Save aligned image. - return img - - -def chunks(lst, n): - """Yield successive n-sized chunks from lst.""" - for i in range(0, len(lst), n): - yield lst[i:i + n] - - -def extract_on_paths(file_paths): - predictor = dlib.shape_predictor(SHAPE_PREDICTOR_PATH) - pid = mp.current_process().name - print('\t{} is starting to extract on #{} images'.format(pid, len(file_paths))) - tot_count = len(file_paths) - count = 0 - for file_path, res_path in file_paths: - count += 1 - if count % 100 == 0: - print('{} done with {}/{}'.format(pid, count, tot_count)) - try: - res = align_face(file_path, predictor) - res = res.convert('RGB') - os.makedirs(os.path.dirname(res_path), exist_ok=True) - res.save(res_path) - except Exception: - continue - print('\tDone!') - - -def parse_args(): - parser = ArgumentParser(add_help=False) - parser.add_argument('--num_threads', type=int, default=1) - parser.add_argument('--root_path', type=str, default='') - args = parser.parse_args() - return args - - -def run(args): - root_path = args.root_path - out_crops_path = root_path + '_crops' - if not os.path.exists(out_crops_path): - os.makedirs(out_crops_path, exist_ok=True) - - file_paths = [] - for root, dirs, files in os.walk(root_path): - for file in files: - file_path = os.path.join(root, file) - fname = os.path.join(out_crops_path, os.path.relpath(file_path, root_path)) - res_path = '{}.jpg'.format(os.path.splitext(fname)[0]) - if os.path.splitext(file_path)[1] == '.txt' or os.path.exists(res_path): - continue - file_paths.append((file_path, res_path)) - - file_chunks = list(chunks(file_paths, int(math.ceil(len(file_paths) / args.num_threads)))) - print(len(file_chunks)) - pool = mp.Pool(args.num_threads) - print('Running on {} paths\nHere we goooo'.format(len(file_paths))) - tic = time.time() - pool.map(extract_on_paths, file_chunks) - toc = time.time() - print('Mischief managed in {}s'.format(toc - tic)) - - -if __name__ == '__main__': - args = parse_args() - run(args) diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/models/fairseq_model.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/models/fairseq_model.py deleted file mode 100644 index e55c7ba1ad90f4e2f12db6c814d04a90c4e3b77c..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/models/fairseq_model.py +++ /dev/null @@ -1,569 +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. -""" -Base classes for various fairseq models. -""" - -import logging -from argparse import Namespace -from typing import Dict, List, Optional, Tuple - -import torch -import torch.nn as nn -import torch.nn.functional as F -from fairseq import utils -from fairseq.data import Dictionary -from fairseq.dataclass.utils import ( - convert_namespace_to_omegaconf, - gen_parser_from_dataclass, -) -from fairseq.models import FairseqDecoder, FairseqEncoder -from omegaconf import DictConfig -from torch import Tensor - - -logger = logging.getLogger(__name__) - - -def check_type(module, expected_type): - if hasattr(module, "unwrapped_module"): - assert isinstance(module.unwrapped_module, expected_type), \ - f"{type(module.unwrapped_module)} != {expected_type}" - else: - assert isinstance(module, expected_type), f"{type(module)} != {expected_type}" - - -class BaseFairseqModel(nn.Module): - """Base class for fairseq models.""" - - def __init__(self): - super().__init__() - self._is_generation_fast = False - - @classmethod - def add_args(cls, parser): - """Add model-specific arguments to the parser.""" - dc = getattr(cls, "__dataclass", None) - if dc is not None: - # do not set defaults so that settings defaults from various architectures still works - gen_parser_from_dataclass(parser, dc(), delete_default=True) - - @classmethod - def build_model(cls, args, task): - """Build a new model instance.""" - raise NotImplementedError("Model must implement the build_model method") - - def get_targets(self, sample, net_output): - """Get targets from either the sample or the net's output.""" - return sample["target"] - - def get_normalized_probs( - self, - net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], - log_probs: bool, - sample: Optional[Dict[str, Tensor]] = None, - ): - """Get normalized probabilities (or log probs) from a net's output.""" - return self.get_normalized_probs_scriptable(net_output, log_probs, sample) - - # TorchScript doesn't support super() method so that the scriptable Subclass - # can't access the base class model in Torchscript. - # Current workaround is to add a helper function with different name and - # call the helper function from scriptable Subclass. - def get_normalized_probs_scriptable( - self, - net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], - log_probs: bool, - sample: Optional[Dict[str, Tensor]] = None, - ): - """Scriptable helper function for get_normalized_probs in ~BaseFairseqModel""" - if hasattr(self, "decoder"): - return self.decoder.get_normalized_probs(net_output, log_probs, sample) - elif torch.is_tensor(net_output): - # syntactic sugar for simple models which don't have a decoder - # (e.g., the classification tutorial) - logits = net_output.float() - if log_probs: - return F.log_softmax(logits, dim=-1) - else: - return F.softmax(logits, dim=-1) - raise NotImplementedError - - def extract_features(self, *args, **kwargs): - """Similar to *forward* but only return features.""" - return self(*args, **kwargs) - - def max_positions(self): - """Maximum length supported by the model.""" - return None - - def load_state_dict( - self, - state_dict, - strict=True, - model_cfg: Optional[DictConfig] = None, - args: Optional[Namespace] = None, - ): - """Copies parameters and buffers from *state_dict* into this module and - its descendants. - - Overrides the method in :class:`nn.Module`. Compared with that method - this additionally "upgrades" *state_dicts* from old checkpoints. - """ - - if model_cfg is None and args is not None: - logger.warn("using 'args' is deprecated, please update your code to use dataclass config") - model_cfg = convert_namespace_to_omegaconf(args).model - - self.upgrade_state_dict(state_dict) - - from fairseq.checkpoint_utils import prune_state_dict - - new_state_dict = prune_state_dict(state_dict, model_cfg) - return super().load_state_dict(new_state_dict, strict) - - def upgrade_state_dict(self, state_dict): - """Upgrade old state dicts to work with newer code.""" - self.upgrade_state_dict_named(state_dict, "") - - def upgrade_state_dict_named(self, state_dict, name): - """Upgrade old state dicts to work with newer code. - - Args: - state_dict (dict): state dictionary to upgrade, in place - name (str): the state dict key corresponding to the current module - """ - assert state_dict is not None - - def do_upgrade(m, prefix): - if len(prefix) > 0: - prefix += "." - - for n, c in m.named_children(): - name = prefix + n - if hasattr(c, "upgrade_state_dict_named"): - c.upgrade_state_dict_named(state_dict, name) - elif hasattr(c, "upgrade_state_dict"): - c.upgrade_state_dict(state_dict) - do_upgrade(c, name) - - do_upgrade(self, name) - - def set_num_updates(self, num_updates): - """State from trainer to pass along to model at every update.""" - for m in self.modules(): - if hasattr(m, "set_num_updates") and m != self: - m.set_num_updates(num_updates) - - def prepare_for_inference_(self, cfg: DictConfig): - """Prepare model for inference.""" - kwargs = {} - kwargs["beamable_mm_beam_size"] = ( - None - if getattr(cfg.generation, "no_beamable_mm", False) - else getattr(cfg.generation, "beam", 5) - ) - kwargs["need_attn"] = getattr(cfg.generation, "print_alignment", False) - if getattr(cfg.generation, "retain_dropout", False): - kwargs["retain_dropout"] = cfg.generation.retain_dropout - kwargs["retain_dropout_modules"] = cfg.generation.retain_dropout_modules - self.make_generation_fast_(**kwargs) - - def make_generation_fast_(self, **kwargs): - """ - Legacy entry point to optimize model for faster generation. - Prefer prepare_for_inference_. - """ - if self._is_generation_fast: - return # only apply once - self._is_generation_fast = True - - # remove weight norm from all modules in the network - def apply_remove_weight_norm(module): - try: - nn.utils.remove_weight_norm(module) - except (AttributeError, ValueError): # this module didn't have weight norm - return - - self.apply(apply_remove_weight_norm) - - def apply_make_generation_fast_(module, prefix): - if len(prefix) > 0: - prefix += "." - - base_func = BaseFairseqModel.make_generation_fast_ - for n, m in module.named_modules(): - if ( - m != self - and hasattr(m, "make_generation_fast_") - # don't call this implementation again, e.g., if - # children modules also inherit from BaseFairseqModel - and m.make_generation_fast_.__func__ is not base_func - ): - name = prefix + n - m.make_generation_fast_(name=name, **kwargs) - - apply_make_generation_fast_(self, "") - - def train(mode=True): - if mode: - raise RuntimeError("cannot train after make_generation_fast") - - # this model should no longer be used for training - self.eval() - self.train = train - - def prepare_for_onnx_export_(self, **kwargs): - """Make model exportable via ONNX trace.""" - seen = set() - - def apply_prepare_for_onnx_export_(module): - if ( - module != self - and hasattr(module, "prepare_for_onnx_export_") - and module not in seen - ): - seen.add(module) - module.prepare_for_onnx_export_(**kwargs) - - self.apply(apply_prepare_for_onnx_export_) - - @classmethod - def from_pretrained( - cls, - model_name_or_path, - checkpoint_file="model.pt", - data_name_or_path=".", - **kwargs, - ): - """ - Load a :class:`~fairseq.models.FairseqModel` from a pre-trained model - file. Downloads and caches the pre-trained model file if needed. - - The base implementation returns a - :class:`~fairseq.hub_utils.GeneratorHubInterface`, which can be used to - generate translations or sample from language models. The underlying - :class:`~fairseq.models.FairseqModel` can be accessed via the - *generator.models* attribute. - - Other models may override this to implement custom hub interfaces. - - Args: - model_name_or_path (str): either the name of a pre-trained model to - load or a path/URL to a pre-trained model state dict - checkpoint_file (str, optional): colon-separated list of checkpoint - files in the model archive to ensemble (default: 'model.pt') - data_name_or_path (str, optional): point args.data to the archive - at the given path/URL. Can start with '.' or './' to reuse the - model archive path. - """ - from fairseq import hub_utils - - x = hub_utils.from_pretrained( - model_name_or_path, - checkpoint_file, - data_name_or_path, - archive_map=cls.hub_models(), - **kwargs, - ) - logger.info(x["args"]) - return hub_utils.GeneratorHubInterface(x["args"], x["task"], x["models"]) - - @classmethod - def hub_models(cls): - return {} - - -class FairseqEncoderDecoderModel(BaseFairseqModel): - """Base class for encoder-decoder models. - - Args: - encoder (FairseqEncoder): the encoder - decoder (FairseqDecoder): the decoder - """ - - def __init__(self, encoder, decoder): - super().__init__() - - self.encoder = encoder - self.decoder = decoder - - check_type(self.encoder, FairseqEncoder) - check_type(self.decoder, FairseqDecoder) - - def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): - """ - Run the forward pass for an encoder-decoder model. - - First feed a batch of source tokens through the encoder. Then, feed the - encoder output and previous decoder outputs (i.e., teacher forcing) to - the decoder to produce the next outputs:: - - encoder_out = self.encoder(src_tokens, src_lengths) - return self.decoder(prev_output_tokens, encoder_out) - - Args: - src_tokens (LongTensor): tokens in the source language of shape - `(batch, src_len)` - src_lengths (LongTensor): source sentence lengths of shape `(batch)` - prev_output_tokens (LongTensor): previous decoder outputs of shape - `(batch, tgt_len)`, for teacher forcing - - Returns: - tuple: - - the decoder's output of shape `(batch, tgt_len, vocab)` - - a dictionary with any model-specific outputs - """ - encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) - decoder_out = self.decoder( - prev_output_tokens, encoder_out=encoder_out, **kwargs - ) - return decoder_out - - def forward_decoder(self, prev_output_tokens, **kwargs): - return self.decoder(prev_output_tokens, **kwargs) - - def extract_features(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): - """ - Similar to *forward* but only return features. - - Returns: - tuple: - - the decoder's features of shape `(batch, tgt_len, embed_dim)` - - a dictionary with any model-specific outputs - """ - encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs) - features = self.decoder.extract_features( - prev_output_tokens, encoder_out=encoder_out, **kwargs - ) - return features - - def output_layer(self, features, **kwargs): - """Project features to the default output size (typically vocabulary size).""" - return self.decoder.output_layer(features, **kwargs) - - def max_positions(self): - """Maximum length supported by the model.""" - return (self.encoder.max_positions(), self.decoder.max_positions()) - - def max_decoder_positions(self): - """Maximum length supported by the decoder.""" - return self.decoder.max_positions() - - -class FairseqModel(FairseqEncoderDecoderModel): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - utils.deprecation_warning( - "FairseqModel is deprecated, please use FairseqEncoderDecoderModel " - "or BaseFairseqModel instead", - stacklevel=4, - ) - - -class FairseqMultiModel(BaseFairseqModel): - """Base class for combining multiple encoder-decoder models.""" - - def __init__(self, encoders, decoders): - super().__init__() - assert encoders.keys() == decoders.keys() - self.keys = list(encoders.keys()) - for key in self.keys: - check_type(encoders[key], FairseqEncoder) - check_type(decoders[key], FairseqDecoder) - - self.models = nn.ModuleDict( - { - key: FairseqEncoderDecoderModel(encoders[key], decoders[key]) - for key in self.keys - } - ) - - @staticmethod - def build_shared_embeddings( - dicts: Dict[str, Dictionary], - langs: List[str], - embed_dim: int, - build_embedding: callable, - pretrained_embed_path: Optional[str] = None, - ): - """ - Helper function to build shared embeddings for a set of languages after - checking that all dicts corresponding to those languages are equivalent. - - Args: - dicts: Dict of lang_id to its corresponding Dictionary - langs: languages that we want to share embeddings for - embed_dim: embedding dimension - build_embedding: callable function to actually build the embedding - pretrained_embed_path: Optional path to load pretrained embeddings - """ - shared_dict = dicts[langs[0]] - if any(dicts[lang] != shared_dict for lang in langs): - raise ValueError( - "--share-*-embeddings requires a joined dictionary: " - "--share-encoder-embeddings requires a joined source " - "dictionary, --share-decoder-embeddings requires a joined " - "target dictionary, and --share-all-embeddings requires a " - "joint source + target dictionary." - ) - return build_embedding(shared_dict, embed_dim, pretrained_embed_path) - - def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): - raise NotImplementedError - - def max_positions(self): - """Maximum length supported by the model.""" - return { - key: ( - self.models[key].encoder.max_positions(), - self.models[key].decoder.max_positions(), - ) - for key in self.keys - } - - def max_decoder_positions(self): - """Maximum length supported by the decoder.""" - return min(model.decoder.max_positions() for model in self.models.values()) - - @property - def encoder(self): - return self.models[self.keys[0]].encoder - - @property - def decoder(self): - return self.models[self.keys[0]].decoder - - def forward_decoder(self, prev_output_tokens, **kwargs): - return self.decoder(prev_output_tokens, **kwargs) - - def load_state_dict( - self, - state_dict, - strict=True, - model_cfg=None, - args: Optional[Namespace] = None, - ): - """Copies parameters and buffers from *state_dict* into this module and - its descendants. - - Overrides the method in :class:`nn.Module`. Compared with that method - this additionally "upgrades" *state_dicts* from old checkpoints. - """ - - if model_cfg is None and args is not None: - logger.warn("using 'args' is deprecated, please update your code to use dataclass config") - model_cfg = convert_namespace_to_omegaconf(args).model - - self.upgrade_state_dict(state_dict) - - from fairseq.checkpoint_utils import prune_state_dict - - new_state_dict = prune_state_dict(state_dict, model_cfg) - return super().load_state_dict(new_state_dict, strict) - - -class FairseqLanguageModel(BaseFairseqModel): - """Base class for decoder-only models. - - Args: - decoder (FairseqDecoder): the decoder - """ - - def __init__(self, decoder): - super().__init__() - self.decoder = decoder - check_type(self.decoder, FairseqDecoder) - - def forward(self, src_tokens, **kwargs): - """ - Run the forward pass for a decoder-only model. - - Feeds a batch of tokens through the decoder to predict the next tokens. - - Args: - src_tokens (LongTensor): tokens on which to condition the decoder, - of shape `(batch, tgt_len)` - src_lengths (LongTensor): source sentence lengths of shape `(batch)` - - Returns: - tuple: - - the decoder's output of shape `(batch, seq_len, vocab)` - - a dictionary with any model-specific outputs - """ - return self.decoder(src_tokens, **kwargs) - - def forward_decoder(self, prev_output_tokens, **kwargs): - return self.decoder(prev_output_tokens, **kwargs) - - def extract_features(self, src_tokens, **kwargs): - """ - Similar to *forward* but only return features. - - Returns: - tuple: - - the decoder's features of shape `(batch, seq_len, embed_dim)` - - a dictionary with any model-specific outputs - """ - return self.decoder.extract_features(src_tokens, **kwargs) - - def output_layer(self, features, **kwargs): - """Project features to the default output size (typically vocabulary size).""" - return self.decoder.output_layer(features, **kwargs) - - def max_positions(self): - """Maximum length supported by the model.""" - return self.decoder.max_positions() - - def max_decoder_positions(self): - """Maximum length supported by the decoder.""" - return self.decoder.max_positions() - - @property - def supported_targets(self): - return {"future"} - - -class FairseqEncoderModel(BaseFairseqModel): - """Base class for encoder-only models. - - Args: - encoder (FairseqEncoder): the encoder - """ - - def __init__(self, encoder): - super().__init__() - self.encoder = encoder - check_type(self.encoder, FairseqEncoder) - - def forward(self, src_tokens, src_lengths, **kwargs): - """ - Run the forward pass for a encoder-only model. - - Feeds a batch of tokens through the encoder to generate features. - - Args: - src_tokens (LongTensor): input tokens of shape `(batch, src_len)` - src_lengths (LongTensor): source sentence lengths of shape `(batch)` - - Returns: - the encoder's output, typically of shape `(batch, src_len, features)` - """ - return self.encoder(src_tokens, src_lengths, **kwargs) - - def get_normalized_probs(self, net_output, log_probs, sample=None): - """Get normalized probabilities (or log probs) from a net's output.""" - encoder_out = net_output["encoder_out"] - if torch.is_tensor(encoder_out): - logits = encoder_out.float() - if log_probs: - return F.log_softmax(logits, dim=-1) - else: - return F.softmax(logits, dim=-1) - raise NotImplementedError - - def max_positions(self): - """Maximum length supported by the model.""" - return self.encoder.max_positions() diff --git a/spaces/mthsk/sovits-models-misc/modules/__init__.py b/spaces/mthsk/sovits-models-misc/modules/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/muLoo/dis-background-removal/app.py b/spaces/muLoo/dis-background-removal/app.py deleted file mode 100644 index 6024d1ab45b920e43cb502e7a7de52ffea2150e7..0000000000000000000000000000000000000000 --- a/spaces/muLoo/dis-background-removal/app.py +++ /dev/null @@ -1,154 +0,0 @@ -import cv2 -import gradio as gr -import os -from PIL import Image -import numpy as np -import torch -from torch.autograd import Variable -from torchvision import transforms -import torch.nn.functional as F -import gdown -import matplotlib.pyplot as plt -import warnings -warnings.filterwarnings("ignore") - -os.system("git clone https://github.com/xuebinqin/DIS") -os.system("mv DIS/IS-Net/* .") - -# project imports -from data_loader_cache import normalize, im_reader, im_preprocess -from models import * - -#Helpers -device = 'cuda' if torch.cuda.is_available() else 'cpu' - -# Download official weights -if not os.path.exists("saved_models"): - os.mkdir("saved_models") - MODEL_PATH_URL = "https://drive.google.com/uc?id=1KyMpRjewZdyYfxHPYcd-ZbanIXtin0Sn" - gdown.download(MODEL_PATH_URL, "saved_models/isnet.pth", use_cookies=False) - -class GOSNormalize(object): - ''' - Normalize the Image using torch.transforms - ''' - def __init__(self, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]): - self.mean = mean - self.std = std - - def __call__(self,image): - image = normalize(image,self.mean,self.std) - return image - - -transform = transforms.Compose([GOSNormalize([0.5,0.5,0.5],[1.0,1.0,1.0])]) - -def load_image(im_path, hypar): - im = im_reader(im_path) - im, im_shp = im_preprocess(im, hypar["cache_size"]) - im = torch.divide(im,255.0) - shape = torch.from_numpy(np.array(im_shp)) - return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape - - -def build_model(hypar,device): - net = hypar["model"]#GOSNETINC(3,1) - - # convert to half precision - if(hypar["model_digit"]=="half"): - net.half() - for layer in net.modules(): - if isinstance(layer, nn.BatchNorm2d): - layer.float() - - net.to(device) - - if(hypar["restore_model"]!=""): - net.load_state_dict(torch.load(hypar["model_path"]+"/"+hypar["restore_model"], map_location=device)) - net.to(device) - net.eval() - return net - - -def predict(net, inputs_val, shapes_val, hypar, device): - ''' - Given an Image, predict the mask - ''' - net.eval() - - if(hypar["model_digit"]=="full"): - inputs_val = inputs_val.type(torch.FloatTensor) - else: - inputs_val = inputs_val.type(torch.HalfTensor) - - - inputs_val_v = Variable(inputs_val, requires_grad=False).to(device) # wrap inputs in Variable - - ds_val = net(inputs_val_v)[0] # list of 6 results - - pred_val = ds_val[0][0,:,:,:] # B x 1 x H x W # we want the first one which is the most accurate prediction - - ## recover the prediction spatial size to the orignal image size - pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),(shapes_val[0][0],shapes_val[0][1]),mode='bilinear')) - - ma = torch.max(pred_val) - mi = torch.min(pred_val) - pred_val = (pred_val-mi)/(ma-mi) # max = 1 - - if device == 'cuda': torch.cuda.empty_cache() - return (pred_val.detach().cpu().numpy()*255).astype(np.uint8) # it is the mask we need - -# Set Parameters -hypar = {} # paramters for inferencing - - -hypar["model_path"] ="./saved_models" ## load trained weights from this path -hypar["restore_model"] = "isnet.pth" ## name of the to-be-loaded weights -hypar["interm_sup"] = False ## indicate if activate intermediate feature supervision - -## choose floating point accuracy -- -hypar["model_digit"] = "full" ## indicates "half" or "full" accuracy of float number -hypar["seed"] = 0 - -hypar["cache_size"] = [1024, 1024] ## cached input spatial resolution, can be configured into different size - -## data augmentation parameters --- -hypar["input_size"] = [1024, 1024] ## mdoel input spatial size, usually use the same value hypar["cache_size"], which means we don't further resize the images -hypar["crop_size"] = [1024, 1024] ## random crop size from the input, it is usually set as smaller than hypar["cache_size"], e.g., [920,920] for data augmentation - -hypar["model"] = ISNetDIS() - - # Build Model -net = build_model(hypar, device) - - -def inference(image): - image_path = image - - image_tensor, orig_size = load_image(image_path, hypar) - mask = predict(net, image_tensor, orig_size, hypar, device) - - pil_mask = Image.fromarray(mask).convert('L') - im_rgb = Image.open(image).convert("RGB") - - im_rgba = im_rgb.copy() - im_rgba.putalpha(pil_mask) - - return [im_rgba, pil_mask] - - -title = "Highly Accurate Dichotomous Image Segmentation" -description = "This is an unofficial demo for DIS, a model that can remove the background from a given image. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below.
    GitHub: https://github.com/xuebinqin/DIS
    Telegram bot: https://t.me/restoration_photo_bot
    [![](https://img.shields.io/twitter/follow/DoEvent?label=@DoEvent&style=social)](https://twitter.com/DoEvent)" -article = "
    visitor badge
    " - -interface = gr.Interface( - fn=inference, - inputs=gr.Image(type='filepath'), - outputs=["image", "image"], - examples=[['robot.png'], ['ship.png']], - title=title, - description=description, - article=article, - allow_flagging='never', - cache_examples=False, - ).queue(concurrency_count=1, api_open=True).launch(show_api=True, show_error=True) diff --git a/spaces/mueller-franzes/medfusion-app/scripts/helpers/sample_dataset.py b/spaces/mueller-franzes/medfusion-app/scripts/helpers/sample_dataset.py deleted file mode 100644 index a8c3c7754838646e600c7541a93a28a5a5ebfc6e..0000000000000000000000000000000000000000 --- a/spaces/mueller-franzes/medfusion-app/scripts/helpers/sample_dataset.py +++ /dev/null @@ -1,57 +0,0 @@ - -from pathlib import Path -import torch -from torchvision import utils -import math -from medical_diffusion.models.pipelines import DiffusionPipeline -import numpy as np -from PIL import Image -import time - -def chunks(lst, n): - """Yield successive n-sized chunks from lst.""" - for i in range(0, len(lst), n): - yield lst[i:i + n] - -# ------------ Load Model ------------ -device = torch.device('cuda') -# pipeline = DiffusionPipeline.load_best_checkpoint(path_run_dir) -pipeline = DiffusionPipeline.load_from_checkpoint('runs/2022_12_12_171357_chest_diffusion/last.ckpt') -pipeline.to(device) - -if __name__ == "__main__": - # {'NRG':0, 'RG':1} 3270, {'MSIH':0, 'nonMSIH':1} :9979 {'No_Cardiomegaly':0, 'Cardiomegaly':1} 7869 - for steps in [50, 100, 150, 200, 250]: - for name, label in {'No_Cardiomegaly':0, 'Cardiomegaly':1}.items(): - n_samples = 7869 - sample_batch = 200 - cfg = 1 - - # path_out = Path(f'/mnt/hdd/datasets/pathology/kather_msi_mss_2/synthetic_data/diffusion2_{steps}/')/name - path_out = Path(f'/mnt/hdd/datasets/chest/CheXpert/ChecXpert-v10/generated_diffusion3_{steps}')/name - # path_out = Path('/mnt/hdd/datasets/eye/AIROGS/data_generated_diffusion')/name - path_out.mkdir(parents=True, exist_ok=True) - - # --------- Generate Samples ------------------- - torch.manual_seed(0) - counter = 0 - for chunk in chunks(list(range(n_samples)), sample_batch): - condition = torch.tensor([label]*len(chunk), device=device) if label is not None else None - un_cond = torch.tensor([1-label]*len(chunk), device=device) if label is not None else None # Might be None, or 1-condition or specific label - results = pipeline.sample(len(chunk), (8, 32, 32), guidance_scale=cfg, condition=condition, un_cond=un_cond, steps=steps) - # results = pipeline.sample(len(chunk), (4, 64, 64), guidance_scale=cfg, condition=condition, un_cond=un_cond, steps=steps ) - - results = results.cpu().numpy() - # --------- Save result ---------------- - for image in results: - image = image.clip(-1, 1) # or (image-image.min())/(image.max()-image.min()) - image = (image+1)/2*255 # Transform from [-1, 1] to [0, 1] to [0, 255] - image = np.moveaxis(image, 0, -1) - image = image.astype(np.uint8) - image = np.squeeze(image, axis=-1) if image.shape[-1]==1 else image - Image.fromarray(image).convert("RGB").save(path_out/f'fake_{counter}.png') - counter += 1 - - - torch.cuda.empty_cache() - time.sleep(3) diff --git a/spaces/multimodalart/stable-diffusion-inpainting/clipseg/models/vitseg.py b/spaces/multimodalart/stable-diffusion-inpainting/clipseg/models/vitseg.py deleted file mode 100644 index ed621431ddf930fcfa27b5929999776b96fede63..0000000000000000000000000000000000000000 --- a/spaces/multimodalart/stable-diffusion-inpainting/clipseg/models/vitseg.py +++ /dev/null @@ -1,286 +0,0 @@ -import math -from posixpath import basename, dirname, join -# import clip -from clip.model import convert_weights -import torch -import json -from torch import nn -from torch.nn import functional as nnf -from torch.nn.modules import activation -from torch.nn.modules.activation import ReLU -from torchvision import transforms - -normalize = transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)) - -from torchvision.models import ResNet - - -def process_prompts(conditional, prompt_list, conditional_map): - # DEPRECATED - - # randomly sample a synonym - words = [conditional_map[int(i)] for i in conditional] - words = [syns[torch.multinomial(torch.ones(len(syns)), 1, replacement=True).item()] for syns in words] - words = [w.replace('_', ' ') for w in words] - - if prompt_list is not None: - prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True) - prompts = [prompt_list[i] for i in prompt_indices] - else: - prompts = ['a photo of {}'] * (len(words)) - - return [promt.format(w) for promt, w in zip(prompts, words)] - - -class VITDenseBase(nn.Module): - - def rescaled_pos_emb(self, new_size): - assert len(new_size) == 2 - - a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape) - b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T - return torch.cat([self.model.positional_embedding[:1], b]) - - def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None): - - with torch.no_grad(): - - x_inp = nnf.interpolate(x_inp, (384, 384)) - - x = self.model.patch_embed(x_inp) - cls_token = self.model.cls_token.expand(x.shape[0], -1, -1) # stole cls_tokens impl from Phil Wang, thanks - if self.model.dist_token is None: - x = torch.cat((cls_token, x), dim=1) - else: - x = torch.cat((cls_token, self.model.dist_token.expand(x.shape[0], -1, -1), x), dim=1) - x = self.model.pos_drop(x + self.model.pos_embed) - - activations = [] - for i, block in enumerate(self.model.blocks): - x = block(x) - - if i in extract_layers: - # permute to be compatible with CLIP - activations += [x.permute(1,0,2)] - - x = self.model.norm(x) - x = self.model.head(self.model.pre_logits(x[:, 0])) - - # again for CLIP compatibility - # x = x.permute(1, 0, 2) - - return x, activations, None - - def sample_prompts(self, words, prompt_list=None): - - prompt_list = prompt_list if prompt_list is not None else self.prompt_list - - prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True) - prompts = [prompt_list[i] for i in prompt_indices] - return [promt.format(w) for promt, w in zip(prompts, words)] - - def get_cond_vec(self, conditional, batch_size): - # compute conditional from a single string - if conditional is not None and type(conditional) == str: - cond = self.compute_conditional(conditional) - cond = cond.repeat(batch_size, 1) - - # compute conditional from string list/tuple - elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str: - assert len(conditional) == batch_size - cond = self.compute_conditional(conditional) - - # use conditional directly - elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2: - cond = conditional - - # compute conditional from image - elif conditional is not None and type(conditional) == torch.Tensor: - with torch.no_grad(): - cond, _, _ = self.visual_forward(conditional) - else: - raise ValueError('invalid conditional') - return cond - - def compute_conditional(self, conditional): - import clip - - dev = next(self.parameters()).device - - if type(conditional) in {list, tuple}: - text_tokens = clip.tokenize(conditional).to(dev) - cond = self.clip_model.encode_text(text_tokens) - else: - if conditional in self.precomputed_prompts: - cond = self.precomputed_prompts[conditional].float().to(dev) - else: - text_tokens = clip.tokenize([conditional]).to(dev) - cond = self.clip_model.encode_text(text_tokens)[0] - - return cond - - -class VITDensePredT(VITDenseBase): - - def __init__(self, extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed', - depth=3, extra_blocks=0, reduce_cond=None, fix_shift=False, - learn_trans_conv_only=False, refine=None, limit_to_clip_only=False, upsample=False, - add_calibration=False, process_cond=None, not_pretrained=False): - super().__init__() - # device = 'cpu' - - self.extract_layers = extract_layers - self.cond_layer = cond_layer - self.limit_to_clip_only = limit_to_clip_only - self.process_cond = None - - if add_calibration: - self.calibration_conds = 1 - - self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None - - self.add_activation1 = True - - import timm - self.model = timm.create_model('vit_base_patch16_384', pretrained=True) - self.model.head = nn.Linear(768, 512 if reduce_cond is None else reduce_cond) - - for p in self.model.parameters(): - p.requires_grad_(False) - - import clip - self.clip_model, _ = clip.load('ViT-B/16', device='cpu', jit=False) - # del self.clip_model.visual - - - self.token_shape = (14, 14) - - # conditional - if reduce_cond is not None: - self.reduce_cond = nn.Linear(512, reduce_cond) - for p in self.reduce_cond.parameters(): - p.requires_grad_(False) - else: - self.reduce_cond = None - - # self.film = AVAILABLE_BLOCKS['film'](512, 128) - self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim) - self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim) - - # DEPRECATED - # self.conditional_map = {c['id']: c['synonyms'] for c in json.load(open(cond_map))} - - assert len(self.extract_layers) == depth - - self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)]) - self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))]) - self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)]) - - trans_conv_ks = (16, 16) - self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks) - - # refinement and trans conv - - if learn_trans_conv_only: - for p in self.parameters(): - p.requires_grad_(False) - - for p in self.trans_conv.parameters(): - p.requires_grad_(True) - - if prompt == 'fixed': - self.prompt_list = ['a photo of a {}.'] - elif prompt == 'shuffle': - self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.'] - elif prompt == 'shuffle+': - self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.', - 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.', - 'a bad photo of a {}.', 'a photo of the {}.'] - elif prompt == 'shuffle_clip': - from models.clip_prompts import imagenet_templates - self.prompt_list = imagenet_templates - - if process_cond is not None: - if process_cond == 'clamp' or process_cond[0] == 'clamp': - - val = process_cond[1] if type(process_cond) in {list, tuple} else 0.2 - - def clamp_vec(x): - return torch.clamp(x, -val, val) - - self.process_cond = clamp_vec - - elif process_cond.endswith('.pth'): - - shift = torch.load(process_cond) - def add_shift(x): - return x + shift.to(x.device) - - self.process_cond = add_shift - - import pickle - precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb')) - self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()} - - - def forward(self, inp_image, conditional=None, return_features=False, mask=None): - - assert type(return_features) == bool - - # inp_image = inp_image.to(self.model.positional_embedding.device) - - if mask is not None: - raise ValueError('mask not supported') - - # x_inp = normalize(inp_image) - x_inp = inp_image - - bs, dev = inp_image.shape[0], x_inp.device - - inp_image_size = inp_image.shape[2:] - - cond = self.get_cond_vec(conditional, bs) - - visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers)) - - activation1 = activations[0] - activations = activations[1:] - - a = None - for i, (activation, block, reduce) in enumerate(zip(activations[::-1], self.blocks, self.reduces)): - - if a is not None: - a = reduce(activation) + a - else: - a = reduce(activation) - - if i == self.cond_layer: - if self.reduce_cond is not None: - cond = self.reduce_cond(cond) - - a = self.film_mul(cond) * a + self.film_add(cond) - - a = block(a) - - for block in self.extra_blocks: - a = a + block(a) - - a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens - - size = int(math.sqrt(a.shape[2])) - - a = a.view(bs, a.shape[1], size, size) - - if self.trans_conv is not None: - a = self.trans_conv(a) - - if self.upsample_proj is not None: - a = self.upsample_proj(a) - a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear') - - a = nnf.interpolate(a, inp_image_size) - - if return_features: - return a, visual_q, cond, [activation1] + activations - else: - return a, diff --git a/spaces/mygyasir/deep-voice-cloning/build/lib/deep_voice_cloning/cloning/model.py b/spaces/mygyasir/deep-voice-cloning/build/lib/deep_voice_cloning/cloning/model.py deleted file mode 100644 index dd9a545d9c3bc6be07deded08fc4645879c917e9..0000000000000000000000000000000000000000 --- a/spaces/mygyasir/deep-voice-cloning/build/lib/deep_voice_cloning/cloning/model.py +++ /dev/null @@ -1,57 +0,0 @@ -import os -import json -from typing import Dict -from pathlib import Path - -import numpy as np -import torch -from speechbrain.pretrained import EncoderClassifier -from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan - - -class CloningModel: - def __init__(self, config: Dict[str, Dict[str, str]] = None, lang: str = 'en'): - super(CloningModel, self).__init__() - if config is None: - self.speaker_embedding = None - with open(os.path.join(os.path.dirname(__file__), 'config.json')) as f: - self.config = json.load(f)[lang] - else: - self.config = config - self.speaker_embedding = torch.load(Path(self.config['model_path']) / "speaker_embedding.pt")[0] - self.processor = SpeechT5Processor.from_pretrained(self.config['model_path']) - self.model = SpeechT5ForTextToSpeech.from_pretrained(self.config['model_path']) - self.vocoder = SpeechT5HifiGan.from_pretrained(self.config['vocoder_name']) - self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - self.speaker_model = EncoderClassifier.from_hparams(source=self.config['speaker_model_name']) - self.to(self.device) - - - - def to(self, device: torch.device): - self.model = self.model.to(device) - self.vocoder = self.vocoder.to(device) - - def save_pretrained(self, save_directory: str): - self.model.save_pretrained(save_directory) - self.processor.save_pretrained(save_directory) - torch.save(self.speaker_embedding, Path(save_directory) / "speaker_embedding.pt") - - def forward(self, text: str) -> np.array: - # tokenize text - inputs = self.processor(text=text, return_tensors="pt") - # generate spectrogram using backbone model - spectrogram = self.model.generate_speech(inputs["input_ids"].to(self.device), - self.speaker_embedding.to(self.device)) - # decode spectrogram into waveform using vocoder - with torch.no_grad(): - waveform_array = self.vocoder(spectrogram).detach().cpu().numpy() - return waveform_array - - def create_speaker_embedding(self, waveform: torch.tensor) -> torch.tensor: - with torch.no_grad(): - speaker_embeddings = self.speaker_model.encode_batch(waveform) - speaker_embeddings = torch.nn.functional.normalize(speaker_embeddings, dim=2) - self.speaker_embedding = speaker_embeddings - speaker_embeddings = speaker_embeddings.squeeze() - return speaker_embeddings diff --git a/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/debug/analyze_overlapping_masks.sh b/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/debug/analyze_overlapping_masks.sh deleted file mode 100644 index 4a4727b0129007d9b0eed3fc25780adb565965a2..0000000000000000000000000000000000000000 --- a/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/debug/analyze_overlapping_masks.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -BASEDIR="$(dirname $0)" - -# paths are valid for mml7 - -# select images -#ls /data/inpainting/work/data/train | shuf | head -2000 | xargs -n1 -I{} cp {} /data/inpainting/mask_analysis/src - -# generate masks -#"$BASEDIR/../gen_debug_mask_dataset.py" \ -# "$BASEDIR/../../configs/debug_mask_gen.yaml" \ -# "/data/inpainting/mask_analysis/src" \ -# "/data/inpainting/mask_analysis/generated" - -# predict -#"$BASEDIR/../predict.py" \ -# model.path="simple_pix2pix2_gap_sdpl_novgg_large_b18_ffc075_batch8x15/saved_checkpoint/r.suvorov_2021-04-30_14-41-12_train_simple_pix2pix2_gap_sdpl_novgg_large_b18_ffc075_batch8x15_epoch22-step-574999" \ -# indir="/data/inpainting/mask_analysis/generated" \ -# outdir="/data/inpainting/mask_analysis/predicted" \ -# dataset.img_suffix=.jpg \ -# +out_ext=.jpg - -# analyze good and bad samples -"$BASEDIR/../analyze_errors.py" \ - --only-report \ - --n-jobs 8 \ - "$BASEDIR/../../configs/analyze_mask_errors.yaml" \ - "/data/inpainting/mask_analysis/small/generated" \ - "/data/inpainting/mask_analysis/small/predicted" \ - "/data/inpainting/mask_analysis/small/report" diff --git a/spaces/nakamura196/yolov5-kunshujo/README.md b/spaces/nakamura196/yolov5-kunshujo/README.md deleted file mode 100644 index ca29fdbac0c72d2d4390fa72f0ba03bd84399fdb..0000000000000000000000000000000000000000 --- a/spaces/nakamura196/yolov5-kunshujo/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Yolov5 Kunshujo -emoji: 🌍 -colorFrom: gray -colorTo: red -sdk: gradio -sdk_version: 3.1.3 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/nakas/MusicGenDemucs/audiocraft/modules/seanet.py b/spaces/nakas/MusicGenDemucs/audiocraft/modules/seanet.py deleted file mode 100644 index 3e5998e9153afb6e68ea410d565e00ea835db248..0000000000000000000000000000000000000000 --- a/spaces/nakas/MusicGenDemucs/audiocraft/modules/seanet.py +++ /dev/null @@ -1,258 +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 typing as tp - -import numpy as np -import torch.nn as nn - -from .conv import StreamableConv1d, StreamableConvTranspose1d -from .lstm import StreamableLSTM - - -class SEANetResnetBlock(nn.Module): - """Residual block from SEANet model. - - Args: - dim (int): Dimension of the input/output. - kernel_sizes (list): List of kernel sizes for the convolutions. - dilations (list): List of dilations for the convolutions. - activation (str): Activation function. - activation_params (dict): Parameters to provide to the activation function. - norm (str): Normalization method. - norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution. - causal (bool): Whether to use fully causal convolution. - pad_mode (str): Padding mode for the convolutions. - compress (int): Reduced dimensionality in residual branches (from Demucs v3). - true_skip (bool): Whether to use true skip connection or a simple - (streamable) convolution as the skip connection. - """ - def __init__(self, dim: int, kernel_sizes: tp.List[int] = [3, 1], dilations: tp.List[int] = [1, 1], - activation: str = 'ELU', activation_params: dict = {'alpha': 1.0}, - norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, causal: bool = False, - pad_mode: str = 'reflect', compress: int = 2, true_skip: bool = True): - super().__init__() - assert len(kernel_sizes) == len(dilations), 'Number of kernel sizes should match number of dilations' - act = getattr(nn, activation) - hidden = dim // compress - block = [] - for i, (kernel_size, dilation) in enumerate(zip(kernel_sizes, dilations)): - in_chs = dim if i == 0 else hidden - out_chs = dim if i == len(kernel_sizes) - 1 else hidden - block += [ - act(**activation_params), - StreamableConv1d(in_chs, out_chs, kernel_size=kernel_size, dilation=dilation, - norm=norm, norm_kwargs=norm_params, - causal=causal, pad_mode=pad_mode), - ] - self.block = nn.Sequential(*block) - self.shortcut: nn.Module - if true_skip: - self.shortcut = nn.Identity() - else: - self.shortcut = StreamableConv1d(dim, dim, kernel_size=1, norm=norm, norm_kwargs=norm_params, - causal=causal, pad_mode=pad_mode) - - def forward(self, x): - return self.shortcut(x) + self.block(x) - - -class SEANetEncoder(nn.Module): - """SEANet encoder. - - Args: - channels (int): Audio channels. - dimension (int): Intermediate representation dimension. - n_filters (int): Base width for the model. - n_residual_layers (int): nb of residual layers. - ratios (Sequence[int]): kernel size and stride ratios. The encoder uses downsampling ratios instead of - upsampling ratios, hence it will use the ratios in the reverse order to the ones specified here - that must match the decoder order. We use the decoder order as some models may only employ the decoder. - activation (str): Activation function. - activation_params (dict): Parameters to provide to the activation function. - norm (str): Normalization method. - norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution. - kernel_size (int): Kernel size for the initial convolution. - last_kernel_size (int): Kernel size for the initial convolution. - residual_kernel_size (int): Kernel size for the residual layers. - dilation_base (int): How much to increase the dilation with each layer. - causal (bool): Whether to use fully causal convolution. - pad_mode (str): Padding mode for the convolutions. - true_skip (bool): Whether to use true skip connection or a simple - (streamable) convolution as the skip connection in the residual network blocks. - compress (int): Reduced dimensionality in residual branches (from Demucs v3). - lstm (int): Number of LSTM layers at the end of the encoder. - disable_norm_outer_blocks (int): Number of blocks for which we don't apply norm. - For the encoder, it corresponds to the N first blocks. - """ - def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 3, - ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0}, - norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7, - last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False, - pad_mode: str = 'reflect', true_skip: bool = True, compress: int = 2, lstm: int = 0, - disable_norm_outer_blocks: int = 0): - super().__init__() - self.channels = channels - self.dimension = dimension - self.n_filters = n_filters - self.ratios = list(reversed(ratios)) - del ratios - self.n_residual_layers = n_residual_layers - self.hop_length = np.prod(self.ratios) - self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks - self.disable_norm_outer_blocks = disable_norm_outer_blocks - assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \ - "Number of blocks for which to disable norm is invalid." \ - "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0." - - act = getattr(nn, activation) - mult = 1 - model: tp.List[nn.Module] = [ - StreamableConv1d(channels, mult * n_filters, kernel_size, - norm='none' if self.disable_norm_outer_blocks >= 1 else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - # Downsample to raw audio scale - for i, ratio in enumerate(self.ratios): - block_norm = 'none' if self.disable_norm_outer_blocks >= i + 2 else norm - # Add residual layers - for j in range(n_residual_layers): - model += [ - SEANetResnetBlock(mult * n_filters, kernel_sizes=[residual_kernel_size, 1], - dilations=[dilation_base ** j, 1], - norm=block_norm, norm_params=norm_params, - activation=activation, activation_params=activation_params, - causal=causal, pad_mode=pad_mode, compress=compress, true_skip=true_skip)] - - # Add downsampling layers - model += [ - act(**activation_params), - StreamableConv1d(mult * n_filters, mult * n_filters * 2, - kernel_size=ratio * 2, stride=ratio, - norm=block_norm, norm_kwargs=norm_params, - causal=causal, pad_mode=pad_mode), - ] - mult *= 2 - - if lstm: - model += [StreamableLSTM(mult * n_filters, num_layers=lstm)] - - model += [ - act(**activation_params), - StreamableConv1d(mult * n_filters, dimension, last_kernel_size, - norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - - self.model = nn.Sequential(*model) - - def forward(self, x): - return self.model(x) - - -class SEANetDecoder(nn.Module): - """SEANet decoder. - - Args: - channels (int): Audio channels. - dimension (int): Intermediate representation dimension. - n_filters (int): Base width for the model. - n_residual_layers (int): nb of residual layers. - ratios (Sequence[int]): kernel size and stride ratios. - activation (str): Activation function. - activation_params (dict): Parameters to provide to the activation function. - final_activation (str): Final activation function after all convolutions. - final_activation_params (dict): Parameters to provide to the activation function. - norm (str): Normalization method. - norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution. - kernel_size (int): Kernel size for the initial convolution. - last_kernel_size (int): Kernel size for the initial convolution. - residual_kernel_size (int): Kernel size for the residual layers. - dilation_base (int): How much to increase the dilation with each layer. - causal (bool): Whether to use fully causal convolution. - pad_mode (str): Padding mode for the convolutions. - true_skip (bool): Whether to use true skip connection or a simple. - (streamable) convolution as the skip connection in the residual network blocks. - compress (int): Reduced dimensionality in residual branches (from Demucs v3). - lstm (int): Number of LSTM layers at the end of the encoder. - disable_norm_outer_blocks (int): Number of blocks for which we don't apply norm. - For the decoder, it corresponds to the N last blocks. - trim_right_ratio (float): Ratio for trimming at the right of the transposed convolution under the causal setup. - If equal to 1.0, it means that all the trimming is done at the right. - """ - def __init__(self, channels: int = 1, dimension: int = 128, n_filters: int = 32, n_residual_layers: int = 3, - ratios: tp.List[int] = [8, 5, 4, 2], activation: str = 'ELU', activation_params: dict = {'alpha': 1.0}, - final_activation: tp.Optional[str] = None, final_activation_params: tp.Optional[dict] = None, - norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, kernel_size: int = 7, - last_kernel_size: int = 7, residual_kernel_size: int = 3, dilation_base: int = 2, causal: bool = False, - pad_mode: str = 'reflect', true_skip: bool = True, compress: int = 2, lstm: int = 0, - disable_norm_outer_blocks: int = 0, trim_right_ratio: float = 1.0): - super().__init__() - self.dimension = dimension - self.channels = channels - self.n_filters = n_filters - self.ratios = ratios - del ratios - self.n_residual_layers = n_residual_layers - self.hop_length = np.prod(self.ratios) - self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks - self.disable_norm_outer_blocks = disable_norm_outer_blocks - assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \ - "Number of blocks for which to disable norm is invalid." \ - "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0." - - act = getattr(nn, activation) - mult = int(2 ** len(self.ratios)) - model: tp.List[nn.Module] = [ - StreamableConv1d(dimension, mult * n_filters, kernel_size, - norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - - if lstm: - model += [StreamableLSTM(mult * n_filters, num_layers=lstm)] - - # Upsample to raw audio scale - for i, ratio in enumerate(self.ratios): - block_norm = 'none' if self.disable_norm_outer_blocks >= self.n_blocks - (i + 1) else norm - # Add upsampling layers - model += [ - act(**activation_params), - StreamableConvTranspose1d(mult * n_filters, mult * n_filters // 2, - kernel_size=ratio * 2, stride=ratio, - norm=block_norm, norm_kwargs=norm_params, - causal=causal, trim_right_ratio=trim_right_ratio), - ] - # Add residual layers - for j in range(n_residual_layers): - model += [ - SEANetResnetBlock(mult * n_filters // 2, kernel_sizes=[residual_kernel_size, 1], - dilations=[dilation_base ** j, 1], - activation=activation, activation_params=activation_params, - norm=block_norm, norm_params=norm_params, causal=causal, - pad_mode=pad_mode, compress=compress, true_skip=true_skip)] - - mult //= 2 - - # Add final layers - model += [ - act(**activation_params), - StreamableConv1d(n_filters, channels, last_kernel_size, - norm='none' if self.disable_norm_outer_blocks >= 1 else norm, - norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode) - ] - # Add optional final activation to decoder (eg. tanh) - if final_activation is not None: - final_act = getattr(nn, final_activation) - final_activation_params = final_activation_params or {} - model += [ - final_act(**final_activation_params) - ] - self.model = nn.Sequential(*model) - - def forward(self, z): - y = self.model(z) - return y diff --git a/spaces/nateraw/dino-clips/dino/eval_copy_detection.py b/spaces/nateraw/dino-clips/dino/eval_copy_detection.py deleted file mode 100644 index 73dcd507893f204a47a5036cc61bd65b30cf1ead..0000000000000000000000000000000000000000 --- a/spaces/nateraw/dino-clips/dino/eval_copy_detection.py +++ /dev/null @@ -1,301 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# 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 os -import sys -import pickle -import argparse - -import torch -from torch import nn -import torch.distributed as dist -import torch.backends.cudnn as cudnn -from torchvision import models as torchvision_models -from torchvision import transforms as pth_transforms -from PIL import Image, ImageFile -import numpy as np - -import utils -import vision_transformer as vits -from eval_knn import extract_features - - -class CopydaysDataset(): - def __init__(self, basedir): - self.basedir = basedir - self.block_names = ( - ['original', 'strong'] + - ['jpegqual/%d' % i for i in - [3, 5, 8, 10, 15, 20, 30, 50, 75]] + - ['crops/%d' % i for i in - [10, 15, 20, 30, 40, 50, 60, 70, 80]]) - self.nblocks = len(self.block_names) - - self.query_blocks = range(self.nblocks) - self.q_block_sizes = np.ones(self.nblocks, dtype=int) * 157 - self.q_block_sizes[1] = 229 - # search only among originals - self.database_blocks = [0] - - def get_block(self, i): - dirname = self.basedir + '/' + self.block_names[i] - fnames = [dirname + '/' + fname - for fname in sorted(os.listdir(dirname)) - if fname.endswith('.jpg')] - return fnames - - def get_block_filenames(self, subdir_name): - dirname = self.basedir + '/' + subdir_name - return [fname - for fname in sorted(os.listdir(dirname)) - if fname.endswith('.jpg')] - - def eval_result(self, ids, distances): - j0 = 0 - for i in range(self.nblocks): - j1 = j0 + self.q_block_sizes[i] - block_name = self.block_names[i] - I = ids[j0:j1] # block size - sum_AP = 0 - if block_name != 'strong': - # 1:1 mapping of files to names - positives_per_query = [[i] for i in range(j1 - j0)] - else: - originals = self.get_block_filenames('original') - strongs = self.get_block_filenames('strong') - - # check if prefixes match - positives_per_query = [ - [j for j, bname in enumerate(originals) - if bname[:4] == qname[:4]] - for qname in strongs] - - for qno, Iline in enumerate(I): - positives = positives_per_query[qno] - ranks = [] - for rank, bno in enumerate(Iline): - if bno in positives: - ranks.append(rank) - sum_AP += score_ap_from_ranks_1(ranks, len(positives)) - - print("eval on %s mAP=%.3f" % ( - block_name, sum_AP / (j1 - j0))) - j0 = j1 - - -# from the Holidays evaluation package -def score_ap_from_ranks_1(ranks, nres): - """ Compute the average precision of one search. - ranks = ordered list of ranks of true positives - nres = total number of positives in dataset - """ - - # accumulate trapezoids in PR-plot - ap = 0.0 - - # All have an x-size of: - recall_step = 1.0 / nres - - for ntp, rank in enumerate(ranks): - - # y-size on left side of trapezoid: - # ntp = nb of true positives so far - # rank = nb of retrieved items so far - if rank == 0: - precision_0 = 1.0 - else: - precision_0 = ntp / float(rank) - - # y-size on right side of trapezoid: - # ntp and rank are increased by one - precision_1 = (ntp + 1) / float(rank + 1) - - ap += (precision_1 + precision_0) * recall_step / 2.0 - - return ap - - -class ImgListDataset(torch.utils.data.Dataset): - def __init__(self, img_list, transform=None): - self.samples = img_list - self.transform = transform - - def __getitem__(self, i): - with open(self.samples[i], 'rb') as f: - img = Image.open(f) - img = img.convert('RGB') - if self.transform is not None: - img = self.transform(img) - return img, i - - def __len__(self): - return len(self.samples) - - -def is_image_file(s): - ext = s.split(".")[-1] - if ext in ['jpg', 'jpeg', 'png', 'ppm', 'bmp', 'pgm', 'tif', 'tiff', 'webp']: - return True - return False - - -@torch.no_grad() -def extract_features(image_list, model, args): - transform = pth_transforms.Compose([ - pth_transforms.Resize((args.imsize, args.imsize), interpolation=3), - pth_transforms.ToTensor(), - pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), - ]) - tempdataset = ImgListDataset(image_list, transform=transform) - data_loader = torch.utils.data.DataLoader(tempdataset, batch_size=args.batch_size_per_gpu, - num_workers=args.num_workers, drop_last=False, - sampler=torch.utils.data.DistributedSampler(tempdataset, shuffle=False)) - features = None - for samples, index in utils.MetricLogger(delimiter=" ").log_every(data_loader, 10): - samples, index = samples.cuda(non_blocking=True), index.cuda(non_blocking=True) - feats = model.get_intermediate_layers(samples, n=1)[0].clone() - - cls_output_token = feats[:, 0, :] # [CLS] token - # GeM with exponent 4 for output patch tokens - b, h, w, d = len(samples), int(samples.shape[-2] / model.patch_embed.patch_size), int(samples.shape[-1] / model.patch_embed.patch_size), feats.shape[-1] - feats = feats[:, 1:, :].reshape(b, h, w, d) - feats = feats.clamp(min=1e-6).permute(0, 3, 1, 2) - feats = nn.functional.avg_pool2d(feats.pow(4), (h, w)).pow(1. / 4).reshape(b, -1) - # concatenate [CLS] token and GeM pooled patch tokens - feats = torch.cat((cls_output_token, feats), dim=1) - - # init storage feature matrix - if dist.get_rank() == 0 and features is None: - features = torch.zeros(len(data_loader.dataset), feats.shape[-1]) - if args.use_cuda: - features = features.cuda(non_blocking=True) - - # get indexes from all processes - y_all = torch.empty(dist.get_world_size(), index.size(0), dtype=index.dtype, device=index.device) - y_l = list(y_all.unbind(0)) - y_all_reduce = torch.distributed.all_gather(y_l, index, async_op=True) - y_all_reduce.wait() - index_all = torch.cat(y_l) - - # share features between processes - feats_all = torch.empty(dist.get_world_size(), feats.size(0), feats.size(1), - dtype=feats.dtype, device=feats.device) - output_l = list(feats_all.unbind(0)) - output_all_reduce = torch.distributed.all_gather(output_l, feats, async_op=True) - output_all_reduce.wait() - - # update storage feature matrix - if dist.get_rank() == 0: - if args.use_cuda: - features.index_copy_(0, index_all, torch.cat(output_l)) - else: - features.index_copy_(0, index_all.cpu(), torch.cat(output_l).cpu()) - return features # features is still None for every rank which is not 0 (main) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser('Copy detection on Copydays') - parser.add_argument('--data_path', default='/path/to/copydays/', type=str, - help="See https://lear.inrialpes.fr/~jegou/data.php#copydays") - parser.add_argument('--whitening_path', default='/path/to/whitening_data/', type=str, - help="""Path to directory with images used for computing the whitening operator. - In our paper, we use 20k random images from YFCC100M.""") - parser.add_argument('--distractors_path', default='/path/to/distractors/', type=str, - help="Path to directory with distractors images. In our paper, we use 10k random images from YFCC100M.") - parser.add_argument('--imsize', default=320, type=int, help='Image size (square image)') - parser.add_argument('--batch_size_per_gpu', default=16, type=int, help='Per-GPU batch-size') - parser.add_argument('--pretrained_weights', default='', type=str, help="Path to pretrained weights to evaluate.") - parser.add_argument('--use_cuda', default=True, type=utils.bool_flag) - parser.add_argument('--arch', default='vit_base', type=str, help='Architecture') - parser.add_argument('--patch_size', default=8, type=int, help='Patch resolution of the model.') - parser.add_argument("--checkpoint_key", default="teacher", type=str, - help='Key to use in the checkpoint (example: "teacher")') - parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.') - parser.add_argument("--dist_url", default="env://", type=str, help="""url used to set up - distributed training; see https://pytorch.org/docs/stable/distributed.html""") - parser.add_argument("--local_rank", default=0, type=int, help="Please ignore and do not set this argument.") - args = parser.parse_args() - - utils.init_distributed_mode(args) - print("git:\n {}\n".format(utils.get_sha())) - print("\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items()))) - cudnn.benchmark = True - - # ============ building network ... ============ - if "vit" in args.arch: - model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0) - print(f"Model {args.arch} {args.patch_size}x{args.patch_size} built.") - else: - print(f"Architecture {args.arch} non supported") - sys.exit(1) - if args.use_cuda: - model.cuda() - model.eval() - utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size) - - dataset = CopydaysDataset(args.data_path) - - # ============ Extract features ... ============ - # extract features for queries - queries = [] - for q in dataset.query_blocks: - queries.append(extract_features(dataset.get_block(q), model, args)) - if utils.get_rank() == 0: - queries = torch.cat(queries) - print(f"Extraction of queries features done. Shape: {queries.shape}") - - # extract features for database - database = [] - for b in dataset.database_blocks: - database.append(extract_features(dataset.get_block(b), model, args)) - - # extract features for distractors - if os.path.isdir(args.distractors_path): - print("Using distractors...") - list_distractors = [os.path.join(args.distractors_path, s) for s in os.listdir(args.distractors_path) if is_image_file(s)] - database.append(extract_features(list_distractors, model, args)) - if utils.get_rank() == 0: - database = torch.cat(database) - print(f"Extraction of database and distractors features done. Shape: {database.shape}") - - # ============ Whitening ... ============ - if os.path.isdir(args.whitening_path): - print(f"Extracting features on images from {args.whitening_path} for learning the whitening operator.") - list_whit = [os.path.join(args.whitening_path, s) for s in os.listdir(args.whitening_path) if is_image_file(s)] - features_for_whitening = extract_features(list_whit, model, args) - if utils.get_rank() == 0: - # center - mean_feature = torch.mean(features_for_whitening, dim=0) - database -= mean_feature - queries -= mean_feature - pca = utils.PCA(dim=database.shape[-1], whit=0.5) - # compute covariance - cov = torch.mm(features_for_whitening.T, features_for_whitening) / features_for_whitening.shape[0] - pca.train_pca(cov.cpu().numpy()) - database = pca.apply(database) - queries = pca.apply(queries) - - # ============ Copy detection ... ============ - if utils.get_rank() == 0: - # l2 normalize the features - database = nn.functional.normalize(database, dim=1, p=2) - queries = nn.functional.normalize(queries, dim=1, p=2) - - # similarity - similarity = torch.mm(queries, database.T) - distances, indices = similarity.topk(20, largest=True, sorted=True) - - # evaluate - retrieved = dataset.eval_result(indices, distances) - dist.barrier() - diff --git a/spaces/nikitaPDL2023/assignment4/detectron2/INSTALL.md b/spaces/nikitaPDL2023/assignment4/detectron2/INSTALL.md deleted file mode 100644 index f522e6f624372f39ee5366f5b032c0cd1ebcf5c8..0000000000000000000000000000000000000000 --- a/spaces/nikitaPDL2023/assignment4/detectron2/INSTALL.md +++ /dev/null @@ -1,261 +0,0 @@ -## Installation - -### Requirements -- Linux or macOS with Python ≥ 3.7 -- PyTorch ≥ 1.8 and [torchvision](https://github.com/pytorch/vision/) that matches the PyTorch installation. - Install them together at [pytorch.org](https://pytorch.org) to make sure of this -- OpenCV is optional but needed by demo and visualization - - -### Build Detectron2 from Source - -gcc & g++ ≥ 5.4 are required. [ninja](https://ninja-build.org/) is optional but recommended for faster build. -After having them, run: -``` -python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' -# (add --user if you don't have permission) - -# Or, to install it from a local clone: -git clone https://github.com/facebookresearch/detectron2.git -python -m pip install -e detectron2 - -# On macOS, you may need to prepend the above commands with a few environment variables: -CC=clang CXX=clang++ ARCHFLAGS="-arch x86_64" python -m pip install ... -``` - -To __rebuild__ detectron2 that's built from a local clone, use `rm -rf build/ **/*.so` to clean the -old build first. You often need to rebuild detectron2 after reinstalling PyTorch. - -### Install Pre-Built Detectron2 (Linux only) - -Choose from this table to install [v0.6 (Oct 2021)](https://github.com/facebookresearch/detectron2/releases): - -
    CUDA torch 1.10torch 1.9torch 1.8
    11.3
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu113/torch1.10/index.html
    -
    11.1
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/index.html
    -
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.9/index.html
    -
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.8/index.html
    -
    10.2
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu102/torch1.10/index.html
    -
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu102/torch1.9/index.html
    -
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu102/torch1.8/index.html
    -
    10.1
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.8/index.html
    -
    cpu
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cpu/torch1.10/index.html
    -
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cpu/torch1.9/index.html
    -
    install
    python -m pip install detectron2 -f \
    -  https://dl.fbaipublicfiles.com/detectron2/wheels/cpu/torch1.8/index.html
    -
    - -Note that: -1. The pre-built packages have to be used with corresponding version of CUDA and the official package of PyTorch. - Otherwise, please build detectron2 from source. -2. New packages are released every few months. Therefore, packages may not contain latest features in the main - branch and may not be compatible with the main branch of a research project that uses detectron2 - (e.g. those in [projects](projects)). - -### Common Installation Issues - -Click each issue for its solutions: - -
    - -Undefined symbols that looks like "TH..","at::Tensor...","torch..." - -
    - -This usually happens when detectron2 or torchvision is not -compiled with the version of PyTorch you're running. - -If the error comes from a pre-built torchvision, uninstall torchvision and pytorch and reinstall them -following [pytorch.org](http://pytorch.org). So the versions will match. - -If the error comes from a pre-built detectron2, check [release notes](https://github.com/facebookresearch/detectron2/releases), -uninstall and reinstall the correct pre-built detectron2 that matches pytorch version. - -If the error comes from detectron2 or torchvision that you built manually from source, -remove files you built (`build/`, `**/*.so`) and rebuild it so it can pick up the version of pytorch currently in your environment. - -If the above instructions do not resolve this problem, please provide an environment (e.g. a dockerfile) that can reproduce the issue. -
    - -
    - -Missing torch dynamic libraries, OR segmentation fault immediately when using detectron2. - -This usually happens when detectron2 or torchvision is not -compiled with the version of PyTorch you're running. See the previous common issue for the solution. -
    - -
    - -Undefined C++ symbols (e.g. "GLIBCXX..") or C++ symbols not found. - -
    -Usually it's because the library is compiled with a newer C++ compiler but run with an old C++ runtime. - -This often happens with old anaconda. -It may help to run `conda update libgcc` to upgrade its runtime. - -The fundamental solution is to avoid the mismatch, either by compiling using older version of C++ -compiler, or run the code with proper C++ runtime. -To run the code with a specific C++ runtime, you can use environment variable `LD_PRELOAD=/path/to/libstdc++.so`. - -
    - -
    - -"nvcc not found" or "Not compiled with GPU support" or "Detectron2 CUDA Compiler: not available". - -
    -CUDA is not found when building detectron2. -You should make sure - -``` -python -c 'import torch; from torch.utils.cpp_extension import CUDA_HOME; print(torch.cuda.is_available(), CUDA_HOME)' -``` - -print `(True, a directory with cuda)` at the time you build detectron2. - -Most models can run inference (but not training) without GPU support. To use CPUs, set `MODEL.DEVICE='cpu'` in the config. -
    - -
    - -"invalid device function" or "no kernel image is available for execution". - -
    -Two possibilities: - -* You build detectron2 with one version of CUDA but run it with a different version. - - To check whether it is the case, - use `python -m detectron2.utils.collect_env` to find out inconsistent CUDA versions. - In the output of this command, you should expect "Detectron2 CUDA Compiler", "CUDA_HOME", "PyTorch built with - CUDA" - to contain cuda libraries of the same version. - - When they are inconsistent, - you need to either install a different build of PyTorch (or build by yourself) - to match your local CUDA installation, or install a different version of CUDA to match PyTorch. - -* PyTorch/torchvision/Detectron2 is not built for the correct GPU SM architecture (aka. compute capability). - - The architecture included by PyTorch/detectron2/torchvision is available in the "architecture flags" in - `python -m detectron2.utils.collect_env`. It must include - the architecture of your GPU, which can be found at [developer.nvidia.com/cuda-gpus](https://developer.nvidia.com/cuda-gpus). - - If you're using pre-built PyTorch/detectron2/torchvision, they have included support for most popular GPUs already. - If not supported, you need to build them from source. - - When building detectron2/torchvision from source, they detect the GPU device and build for only the device. - This means the compiled code may not work on a different GPU device. - To recompile them for the correct architecture, remove all installed/compiled files, - and rebuild them with the `TORCH_CUDA_ARCH_LIST` environment variable set properly. - For example, `export TORCH_CUDA_ARCH_LIST="6.0;7.0"` makes it compile for both P100s and V100s. -
    - -
    - -Undefined CUDA symbols; Cannot open libcudart.so - -
    -The version of NVCC you use to build detectron2 or torchvision does -not match the version of CUDA you are running with. -This often happens when using anaconda's CUDA runtime. - -Use `python -m detectron2.utils.collect_env` to find out inconsistent CUDA versions. -In the output of this command, you should expect "Detectron2 CUDA Compiler", "CUDA_HOME", "PyTorch built with - CUDA" -to contain cuda libraries of the same version. - -When they are inconsistent, -you need to either install a different build of PyTorch (or build by yourself) -to match your local CUDA installation, or install a different version of CUDA to match PyTorch. -
    - - -
    - -C++ compilation errors from NVCC / NVRTC, or "Unsupported gpu architecture" - -
    -A few possibilities: - -1. Local CUDA/NVCC version has to match the CUDA version of your PyTorch. Both can be found in `python collect_env.py` - (download from [here](./detectron2/utils/collect_env.py)). - When they are inconsistent, you need to either install a different build of PyTorch (or build by yourself) - to match your local CUDA installation, or install a different version of CUDA to match PyTorch. - -2. Local CUDA/NVCC version shall support the SM architecture (a.k.a. compute capability) of your GPU. - The capability of your GPU can be found at [developer.nvidia.com/cuda-gpus](https://developer.nvidia.com/cuda-gpus). - The capability supported by NVCC is listed at [here](https://gist.github.com/ax3l/9489132). - If your NVCC version is too old, this can be workaround by setting environment variable - `TORCH_CUDA_ARCH_LIST` to a lower, supported capability. - -3. The combination of NVCC and GCC you use is incompatible. You need to change one of their versions. - See [here](https://gist.github.com/ax3l/9489132) for some valid combinations. - Notably, CUDA<=10.1.105 doesn't support GCC>7.3. - - The CUDA/GCC version used by PyTorch can be found by `print(torch.__config__.show())`. - -
    - - -
    - -"ImportError: cannot import name '_C'". - -
    -Please build and install detectron2 following the instructions above. - -Or, if you are running code from detectron2's root directory, `cd` to a different one. -Otherwise you may not import the code that you installed. -
    - - -
    - -Any issue on windows. - -
    - -Detectron2 is continuously built on windows with [CircleCI](https://app.circleci.com/pipelines/github/facebookresearch/detectron2?branch=main). -However we do not provide official support for it. -PRs that improves code compatibility on windows are welcome. -
    - -
    - -ONNX conversion segfault after some "TraceWarning". - -
    -The ONNX package is compiled with a too old compiler. - -Please build and install ONNX from its source code using a compiler -whose version is closer to what's used by PyTorch (available in `torch.__config__.show()`). -
    - - -
    - -"library not found for -lstdc++" on older version of MacOS - -
    - -See [this stackoverflow answer](https://stackoverflow.com/questions/56083725/macos-build-issues-lstdc-not-found-while-building-python-package). - -
    - - -### Installation inside specific environments: - -* __Colab__: see our [Colab Tutorial](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5) - which has step-by-step instructions. - -* __Docker__: The official [Dockerfile](docker) installs detectron2 with a few simple commands. diff --git a/spaces/nomic-ai/facebook_winoground/style.css b/spaces/nomic-ai/facebook_winoground/style.css deleted file mode 100644 index 114adf441e9032febb46bc056b2a8bb651075f0d..0000000000000000000000000000000000000000 --- a/spaces/nomic-ai/facebook_winoground/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/olanigan/YoutubeAssistant/app.py b/spaces/olanigan/YoutubeAssistant/app.py deleted file mode 100644 index eaab309f5b5d330923e65f9e46fb9c25833a69a7..0000000000000000000000000000000000000000 --- a/spaces/olanigan/YoutubeAssistant/app.py +++ /dev/null @@ -1,138 +0,0 @@ -import streamlit as st -import os -import subprocess -import whisper - -URL = 'URL' -TEXT = 'TEXT' -TITLE = 'TITLE' - -PROCESSING = 'PROCESSING' -AUDIO_EXISTS = "AUDIO_EXISTS" -TRANSCRIPT_EXISTS = "TRANSCRIPT_EXISTS" -STATES = [ TEXT, TITLE] -BOOL_STATES = [ AUDIO_EXISTS, TRANSCRIPT_EXISTS, PROCESSING] -AUDIO_FILE = "audio.mp3" -TRANSCRIPT = "transcript.txt" - -model = '' - -st.title('Youtube Assistant') - -def init_state(): - # print("Page refreshed") - for state in STATES: - if state not in st.session_state: - st.session_state[state] = '' - - for state in BOOL_STATES: - if state not in st.session_state: - st.session_state[state] = False - - -def clear_old_files(): - print("Clearing old files") - for file in os.listdir(): - if file.endswith(".mp3") or file == TRANSCRIPT: - os.remove(file) - print(f"Removed old files::{file}") - #Refresh audio state - check_audio() - -@st.cache_data -def load_whisper(): - check_audio() - model = whisper.load_model("small") - print('Loaded Whisper Medium model') - return model - -def transcribe(): - if st.session_state[AUDIO_EXISTS]: - model = load_whisper() - result = model.transcribe("audio.mp3") - text = result["text"] - - st.session_state[TEXT] = text - print(f"Start - { text[:100]}") - print(f"End - { text[-100:]}") - write_file(text, "transcript.txt") - check_audio() - write_file(str(result["segments"]), "segments.txt") - return text - -def check_audio(): - st.session_state[AUDIO_EXISTS] = os.path.exists(AUDIO_FILE) - st.session_state[TRANSCRIPT_EXISTS] = os.path.exists(TRANSCRIPT) - -def load_audio(): - if AUDIO_EXISTS in st.session_state and st.session_state[AUDIO_EXISTS]: - audio_file = open(AUDIO_FILE, 'rb') - audio_bytes = audio_file.read() - st.audio(audio_bytes, format="audio/mp3") - -def display(): - check_audio() - container = st.container() - text_container = st.container() - - with container: - with st.form(key='input_form', clear_on_submit=False): - user_input = st.text_input("Youtube URL:", placeholder="https://www.youtube.com", key=URL) - input_submit_button = st.form_submit_button(label='Send') - - if input_submit_button and user_input: - st.session_state[PROCESSING] = True - clear_old_files() - with st.spinner('Downloading Audio...'): - download() - load_audio() - with st.spinner('Transcribing Audio...'): - transcribe() - st.session_state[PROCESSING] = False - - with text_container: - st.text_area(label=f"Youtube Transcript: {st.session_state[TITLE]}", - height=200, - value=st.session_state[TEXT], - ) - - #Download Button section - col1, col2 = st.columns(2) - with col1: - if AUDIO_EXISTS in st.session_state and st.session_state[AUDIO_EXISTS]: - with open("audio.mp3", "rb") as f: - data = f.read() - st.download_button('Download MP3', data,"audio.mp3", key="mp3") - with col2: - if st.session_state[TRANSCRIPT_EXISTS]: - if st.session_state[TEXT] == '': - with open(TRANSCRIPT, "rb") as f: - data = f.read() - # convert bytes to utf-8 string - data = data.decode("utf-8") - st.session_state[TEXT] = data - - st.download_button("Download Transcript",st.session_state[TEXT],"transcript.txt", key="transcript") - - -def download(): - #Get youtube title - text = subprocess.run(["yt-dlp", "--get-title", st.session_state[URL]], capture_output=True) - st.session_state[TITLE] = text.stdout.decode("utf-8").strip() - # Download and convert audio - command = [f"yt-dlp --no-config -v --extract-audio --audio-format mp3 {st.session_state[URL]} -o audio.mp3"] - print(command) - subprocess.run(command, shell=True) - check_audio() - -def write_file(text, filename): - with open(filename, "w") as f: - f.write(text) - -def main(): - init_state() - display() - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/spaces/ondrejbiza/isa/invariant_slot_attention/configs/objects_room/equiv_transl_scale.py b/spaces/ondrejbiza/isa/invariant_slot_attention/configs/objects_room/equiv_transl_scale.py deleted file mode 100644 index da1a093a0f8cb9bfeec4df54cefba1e3d5e9081d..0000000000000000000000000000000000000000 --- a/spaces/ondrejbiza/isa/invariant_slot_attention/configs/objects_room/equiv_transl_scale.py +++ /dev/null @@ -1,202 +0,0 @@ -# coding=utf-8 -# Copyright 2023 The Google Research 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. - -r"""Config for unsupervised training on objects_room.""" - -import ml_collections - - -def get_config(): - """Get the default hyperparameter configuration.""" - config = ml_collections.ConfigDict() - - config.seed = 42 - config.seed_data = True - - config.batch_size = 64 - config.num_train_steps = 500000 # from the original Slot Attention - config.init_checkpoint = ml_collections.ConfigDict() - config.init_checkpoint.xid = 0 # Disabled by default. - config.init_checkpoint.wid = 1 - - config.optimizer_configs = ml_collections.ConfigDict() - config.optimizer_configs.optimizer = "adam" - - config.optimizer_configs.grad_clip = ml_collections.ConfigDict() - config.optimizer_configs.grad_clip.clip_method = "clip_by_global_norm" - config.optimizer_configs.grad_clip.clip_value = 0.05 - - config.lr_configs = ml_collections.ConfigDict() - config.lr_configs.learning_rate_schedule = "compound" - config.lr_configs.factors = "constant * cosine_decay * linear_warmup" - config.lr_configs.warmup_steps = 10000 # from the original Slot Attention - config.lr_configs.steps_per_cycle = config.get_ref("num_train_steps") - # from the original Slot Attention - config.lr_configs.base_learning_rate = 4e-4 - - # TODO(obvis): Implement masked evaluation. - config.eval_pad_last_batch = False # True - config.log_loss_every_steps = 50 - config.eval_every_steps = 5000 - config.checkpoint_every_steps = 5000 - - config.train_metrics_spec = { - "loss": "loss", - "ari": "ari", - "ari_nobg": "ari_nobg", - } - config.eval_metrics_spec = { - "eval_loss": "loss", - "eval_ari": "ari", - "eval_ari_nobg": "ari_nobg", - } - - config.data = ml_collections.ConfigDict({ - "dataset_name": "objects_room", - "shuffle_buffer_size": config.batch_size * 8, - "resolution": (64, 64) - }) - - config.max_instances = 11 - config.num_slots = config.max_instances # Only used for metrics. - config.logging_min_n_colors = config.max_instances - - config.preproc_train = [ - "tfds_image_to_tfds_video", - "video_from_tfds", - "sparse_to_dense_annotation(max_instances=10)", - ] - - config.preproc_eval = [ - "tfds_image_to_tfds_video", - "video_from_tfds", - "sparse_to_dense_annotation(max_instances=10)", - ] - - config.eval_slice_size = 1 - config.eval_slice_keys = ["video", "segmentations_video"] - - # Dictionary of targets and corresponding channels. Losses need to match. - targets = {"video": 3} - config.losses = {"recon": {"targets": list(targets)}} - config.losses = ml_collections.ConfigDict({ - f"recon_{target}": {"loss_type": "recon", "key": target} - for target in targets}) - - config.model = ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.SAVi", - - # Encoder. - "encoder": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.FrameEncoder", - "reduction": "spatial_flatten", - "backbone": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.SimpleCNN", - "features": [64, 64, 64, 64], - "kernel_size": [(5, 5), (5, 5), (5, 5), (5, 5)], - "strides": [(2, 2), (2, 2), (1, 1), (1, 1)] - }), - "pos_emb": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.PositionEmbedding", - "embedding_type": "linear", - "update_type": "concat" - }), - }), - - # Corrector. - "corrector": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.SlotAttentionTranslScaleEquiv", # pylint: disable=line-too-long - "num_iterations": 3, - "qkv_size": 64, - "mlp_size": 128, - "grid_encoder": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.MLP", - "hidden_size": 128, - "layernorm": "pre" - }), - "add_rel_pos_to_values": True, # V3 - "zero_position_init": False, # Random positions. - "init_with_fixed_scale": None, # Random scales. - "scales_factor": 5.0, - }), - - # Predictor. - # Removed since we are running a single frame. - "predictor": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.Identity" - }), - - # Initializer. - "initializer": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.ParamStateInitRandomPositionsScales", # pylint: disable=line-too-long - "shape": (11, 64), # (num_slots, slot_size) - }), - - # Decoder. - "decoder": ml_collections.ConfigDict({ - "module": - "invariant_slot_attention.modules.SiameseSpatialBroadcastDecoder", - "resolution": (16, 16), # Update if data resolution or strides change - "backbone": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.CNN", - "features": [64, 64, 64, 64, 64], - "kernel_size": [(5, 5), (5, 5), (5, 5), (5, 5), (5, 5)], - "strides": [(2, 2), (2, 2), (1, 1), (1, 1), (1, 1)], - "max_pool_strides": [(1, 1), (1, 1), (1, 1), (1, 1), (1, 1)], - "layer_transpose": [True, True, False, False, False] - }), - "target_readout": ml_collections.ConfigDict({ - "module": "invariant_slot_attention.modules.Readout", - "keys": list(targets), - "readout_modules": [ml_collections.ConfigDict({ # pylint: disable=g-complex-comprehension - "module": "invariant_slot_attention.modules.MLP", - "num_hidden_layers": 0, - "hidden_size": 0, - "output_size": targets[k]}) for k in targets], - }), - "relative_positions_and_scales": True, - "pos_emb": ml_collections.ConfigDict({ - "module": - "invariant_slot_attention.modules.RelativePositionEmbedding", - "embedding_type": - "linear", - "update_type": - "project_add", - "scales_factor": - 5.0, - }), - }), - "decode_corrected": True, - "decode_predicted": False, - }) - - # Which video-shaped variables to visualize. - config.debug_var_video_paths = { - "recon_masks": "decoder/alphas_softmaxed/__call__/0", # pylint: disable=line-too-long - } - - # Define which attention matrices to log/visualize. - config.debug_var_attn_paths = { - "corrector_attn": "corrector/InvertedDotProductAttentionKeyPerQuery_0/attn" # pylint: disable=line-too-long - } - - # Widths of attention matrices (for reshaping to image grid). - config.debug_var_attn_widths = { - "corrector_attn": 16, - } - - return config - - diff --git a/spaces/open-spaced-repetition/fsrs4anki_app/app.py b/spaces/open-spaced-repetition/fsrs4anki_app/app.py deleted file mode 100644 index 962b93101a129dfe1b5f21ef1f784e331f9e64e1..0000000000000000000000000000000000000000 --- a/spaces/open-spaced-repetition/fsrs4anki_app/app.py +++ /dev/null @@ -1,182 +0,0 @@ -import gradio as gr -import pytz -import os -import shutil -import re -import matplotlib.pyplot as plt -from datetime import datetime -from markdown import instructions_markdown, faq_markdown -from fsrs_optimizer import Optimizer -from pathlib import Path -from utilities import cleanup - -with open("./requirements.txt", "r") as f: - txt = f.read().strip() - version = re.search(r"FSRS-Optimizer==(.*)", txt).group(1) - -home_path = os.getcwd() - - -def get_w_markdown(w): - return f""" - # Updated Parameters - Copy and paste these as shown in step 5 of the instructions: - - `{w}` - - Check out the Analysis tab for more detailed information. - - **Note**: These values should be used with FSRS scheduler v4.0.0 or above. - """ - - -def optimizer( - file: gr.File, - timezone, - next_day_starts_at, - revlog_start_date, - filter_out_suspended_cards, - requestRetention, - progress=gr.Progress(track_tqdm=True), -): - os.chdir(home_path) - if file is None: - raise ValueError("Please upload a deck/collection/csv file.") - if file.name.endswith(".apkg") or file.name.endswith(".colpkg"): - mode = "anki" - elif file.name.endswith(".csv"): - mode = "csv" - else: - raise ValueError( - "File must be an Anki deck/collection file (.apkg or .colpkg) or a csv file." - ) - if timezone == "": - raise ValueError("Please select a timezone.") - now = datetime.now() - files = [ - "prediction.tsv", - "revlog.csv", - "revlog_history.tsv", - "stability_for_analysis.tsv", - "expected_time.csv", - "evaluation.tsv", - ] - prefix = now.strftime(f"%Y_%m_%d_%H_%M_%S") - suffix = file.name.split("/")[-1].replace(".", "_").replace("@", "_") - proj_dir = Path(f"projects/{prefix}/{suffix}") - proj_dir.mkdir(parents=True, exist_ok=True) - os.chdir(proj_dir) - optimizer = Optimizer() - if mode == "anki": - optimizer.anki_extract(file.name, filter_out_suspended_cards) - else: - print(file.name) - shutil.copyfile(file.name, "./revlog.csv") - analysis_markdown = optimizer.create_time_series( - timezone, revlog_start_date, next_day_starts_at - ).replace("\n", "\n\n") - optimizer.define_model() - optimizer.pretrain(verbose=False) - optimizer.train(verbose=False) - print(optimizer.w) - w_markdown = get_w_markdown(optimizer.w) - optimizer.predict_memory_states() - difficulty_distribution = optimizer.difficulty_distribution.to_string().replace( - "\n", "\n\n" - ) - plot_output = optimizer.find_optimal_retention()[0] - suggested_retention_markdown = ( - f"""# Suggested Retention: `{optimizer.optimal_retention:.2f}`""" - ) - rating_markdown = optimizer.preview(requestRetention).replace("\n", "\n\n") - loss_before, loss_after = optimizer.evaluate() - loss_markdown = f""" -**Loss before training**: {loss_before} - -**Loss after training**: {loss_after} - """ - # optimizer.calibration_graph() - # optimizer.compare_with_sm2() - markdown_out = f"""{suggested_retention_markdown} - -# Loss Information -{loss_markdown} - -# Difficulty Distribution -{difficulty_distribution} - -# Ratings -{rating_markdown} -""" - os.chdir(home_path) - files_out = [proj_dir / file for file in files if (proj_dir / file).exists()] - cleanup(proj_dir, files) - plt.close("all") - return w_markdown, markdown_out, plot_output, files_out - - -description = f""" -# FSRS Optimizer - v{version} -Based on the [tutorial](https://medium.com/@JarrettYe/how-to-use-the-next-generation-spaced-repetition-algorithm-fsrs-on-anki-5a591ca562e2) -of [Jarrett Ye](https://github.com/L-M-Sherlock). This application can give you personalized anki parameters without having to code. - -Read the `Instructions` if its your first time using the app. -""" - -with gr.Blocks() as demo: - with gr.Tab("FSRS Optimizer"): - with gr.Box(): - gr.Markdown(description) - with gr.Box(): - with gr.Row(): - with gr.Column(): - file = gr.File(label="Review Logs (Step 1)") - with gr.Column(): - next_day_starts_at = gr.Number( - value=4, label="Next Day Starts at (Step 2)", precision=0 - ) - timezone = gr.Dropdown( - label="Timezone (Step 3.1)", choices=pytz.all_timezones - ) - filter_out_suspended_cards = gr.Checkbox( - value=False, label="Filter out suspended cards" - ) - with gr.Accordion(label="Advanced Settings (Step 3.2)", open=False): - requestRetention = gr.Number( - value=0.9, - label="Desired Retention: Recommended to set between 0.8 0.9", - ) - revlog_start_date = gr.Textbox( - value="2006-10-05", - label="Revlog Start Date: Optimize review logs after this date.", - ) - with gr.Row(): - btn_plot = gr.Button("Optimize!") - with gr.Row(): - w_output = gr.Markdown() - with gr.Tab("Instructions"): - with gr.Box(): - gr.Markdown(instructions_markdown) - with gr.Tab("Analysis"): - with gr.Row(): - markdown_output = gr.Markdown() - with gr.Column(): - plot_output = gr.Plot() - files_output = gr.Files(label="Analysis Files") - with gr.Tab("FAQ"): - gr.Markdown(faq_markdown) - - btn_plot.click( - optimizer, - inputs=[ - file, - timezone, - next_day_starts_at, - revlog_start_date, - filter_out_suspended_cards, - requestRetention, - ], - outputs=[w_output, markdown_output, plot_output, files_output], - ) - -demo.queue().launch(show_error=True) diff --git a/spaces/osanseviero/my-own-falcon/README.md b/spaces/osanseviero/my-own-falcon/README.md deleted file mode 100644 index 8936dea47ba363c737d8348383e5809f781bc5fd..0000000000000000000000000000000000000000 --- a/spaces/osanseviero/my-own-falcon/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Chat Ui Template -emoji: 🚀 -colorFrom: indigo -colorTo: blue -sdk: docker -pinned: false -app_port: 3000 -suggested_hardware: a10g-small -duplicated_from: huggingchat/chat-ui-template ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/docs/source/en/api/pipelines/cycle_diffusion.md b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/docs/source/en/api/pipelines/cycle_diffusion.md deleted file mode 100644 index 3ff0d768879a5b073c6e987e6e9eb5e5d8fe3742..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/docs/source/en/api/pipelines/cycle_diffusion.md +++ /dev/null @@ -1,33 +0,0 @@ - - -# Cycle Diffusion - -Cycle Diffusion is a text guided image-to-image generation model proposed in [Unifying Diffusion Models' Latent Space, with Applications to CycleDiffusion and Guidance](https://huggingface.co/papers/2210.05559) by Chen Henry Wu, Fernando De la Torre. - -The abstract from the paper is: - -*Diffusion models have achieved unprecedented performance in generative modeling. The commonly-adopted formulation of the latent code of diffusion models is a sequence of gradually denoised samples, as opposed to the simpler (e.g., Gaussian) latent space of GANs, VAEs, and normalizing flows. This paper provides an alternative, Gaussian formulation of the latent space of various diffusion models, as well as an invertible DPM-Encoder that maps images into the latent space. While our formulation is purely based on the definition of diffusion models, we demonstrate several intriguing consequences. (1) Empirically, we observe that a common latent space emerges from two diffusion models trained independently on related domains. In light of this finding, we propose CycleDiffusion, which uses DPM-Encoder for unpaired image-to-image translation. Furthermore, applying CycleDiffusion to text-to-image diffusion models, we show that large-scale text-to-image diffusion models can be used as zero-shot image-to-image editors. (2) One can guide pre-trained diffusion models and GANs by controlling the latent codes in a unified, plug-and-play formulation based on energy-based models. Using the CLIP model and a face recognition model as guidance, we demonstrate that diffusion models have better coverage of low-density sub-populations and individuals than GANs.* - - - -Make sure to check out the Schedulers [guide](/using-diffusers/schedulers) to learn how to explore the tradeoff between scheduler speed and quality, and see the [reuse components across pipelines](/using-diffusers/loading#reuse-components-across-pipelines) section to learn how to efficiently load the same components into multiple pipelines. - - - -## CycleDiffusionPipeline -[[autodoc]] CycleDiffusionPipeline - - all - - __call__ - -## StableDiffusionPiplineOutput -[[autodoc]] pipelines.stable_diffusion.StableDiffusionPipelineOutput \ No newline at end of file diff --git a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/chardet/charsetprober.py b/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/chardet/charsetprober.py deleted file mode 100644 index a103ca11356606402c03b320a4fcdb8635051623..0000000000000000000000000000000000000000 --- a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/chardet/charsetprober.py +++ /dev/null @@ -1,147 +0,0 @@ -######################## BEGIN LICENSE BLOCK ######################## -# The Original Code is Mozilla Universal charset detector code. -# -# The Initial Developer of the Original Code is -# Netscape Communications Corporation. -# Portions created by the Initial Developer are Copyright (C) 2001 -# the Initial Developer. All Rights Reserved. -# -# Contributor(s): -# Mark Pilgrim - port to Python -# Shy Shalom - original C code -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -# 02110-1301 USA -######################### END LICENSE BLOCK ######################### - -import logging -import re -from typing import Optional, Union - -from .enums import LanguageFilter, ProbingState - -INTERNATIONAL_WORDS_PATTERN = re.compile( - b"[a-zA-Z]*[\x80-\xFF]+[a-zA-Z]*[^a-zA-Z\x80-\xFF]?" -) - - -class CharSetProber: - - SHORTCUT_THRESHOLD = 0.95 - - def __init__(self, lang_filter: LanguageFilter = LanguageFilter.NONE) -> None: - self._state = ProbingState.DETECTING - self.active = True - self.lang_filter = lang_filter - self.logger = logging.getLogger(__name__) - - def reset(self) -> None: - self._state = ProbingState.DETECTING - - @property - def charset_name(self) -> Optional[str]: - return None - - @property - def language(self) -> Optional[str]: - raise NotImplementedError - - def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState: - raise NotImplementedError - - @property - def state(self) -> ProbingState: - return self._state - - def get_confidence(self) -> float: - return 0.0 - - @staticmethod - def filter_high_byte_only(buf: Union[bytes, bytearray]) -> bytes: - buf = re.sub(b"([\x00-\x7F])+", b" ", buf) - return buf - - @staticmethod - def filter_international_words(buf: Union[bytes, bytearray]) -> bytearray: - """ - We define three types of bytes: - alphabet: english alphabets [a-zA-Z] - international: international characters [\x80-\xFF] - marker: everything else [^a-zA-Z\x80-\xFF] - The input buffer can be thought to contain a series of words delimited - by markers. This function works to filter all words that contain at - least one international character. All contiguous sequences of markers - are replaced by a single space ascii character. - This filter applies to all scripts which do not use English characters. - """ - filtered = bytearray() - - # This regex expression filters out only words that have at-least one - # international character. The word may include one marker character at - # the end. - words = INTERNATIONAL_WORDS_PATTERN.findall(buf) - - for word in words: - filtered.extend(word[:-1]) - - # If the last character in the word is a marker, replace it with a - # space as markers shouldn't affect our analysis (they are used - # similarly across all languages and may thus have similar - # frequencies). - last_char = word[-1:] - if not last_char.isalpha() and last_char < b"\x80": - last_char = b" " - filtered.extend(last_char) - - return filtered - - @staticmethod - def remove_xml_tags(buf: Union[bytes, bytearray]) -> bytes: - """ - Returns a copy of ``buf`` that retains only the sequences of English - alphabet and high byte characters that are not between <> characters. - This filter can be applied to all scripts which contain both English - characters and extended ASCII characters, but is currently only used by - ``Latin1Prober``. - """ - filtered = bytearray() - in_tag = False - prev = 0 - buf = memoryview(buf).cast("c") - - for curr, buf_char in enumerate(buf): - # Check if we're coming out of or entering an XML tag - - # https://github.com/python/typeshed/issues/8182 - if buf_char == b">": # type: ignore[comparison-overlap] - prev = curr + 1 - in_tag = False - # https://github.com/python/typeshed/issues/8182 - elif buf_char == b"<": # type: ignore[comparison-overlap] - if curr > prev and not in_tag: - # Keep everything after last non-extended-ASCII, - # non-alphabetic character - filtered.extend(buf[prev:curr]) - # Output a space to delimit stretch we kept - filtered.extend(b" ") - in_tag = True - - # If we're not in a tag... - if not in_tag: - # Keep everything after last non-extended-ASCII, non-alphabetic - # character - filtered.extend(buf[prev:]) - - return filtered diff --git a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/idna/compat.py b/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/idna/compat.py deleted file mode 100644 index 786e6bda63699b72d588ba91dd73df017570aee5..0000000000000000000000000000000000000000 --- a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/idna/compat.py +++ /dev/null @@ -1,13 +0,0 @@ -from .core import * -from .codec import * -from typing import Any, Union - -def ToASCII(label: str) -> bytes: - return encode(label) - -def ToUnicode(label: Union[bytes, bytearray]) -> str: - return decode(label) - -def nameprep(s: Any) -> None: - raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol') - diff --git a/spaces/ploybtt/ploybtt/README.md b/spaces/ploybtt/ploybtt/README.md deleted file mode 100644 index d806f9480d4d66dd6f310883bf460ea60b78e2fb..0000000000000000000000000000000000000000 --- a/spaces/ploybtt/ploybtt/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Ploybx -emoji: 📊 -colorFrom: yellow -colorTo: gray -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/plzdontcry/dakubettergpt/src/components/Chat/Chat.tsx b/spaces/plzdontcry/dakubettergpt/src/components/Chat/Chat.tsx deleted file mode 100644 index 7ec9c865035a04d46da14beb19a54a01acd217a3..0000000000000000000000000000000000000000 --- a/spaces/plzdontcry/dakubettergpt/src/components/Chat/Chat.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import React from 'react'; -import useStore from '@store/store'; - -import ChatContent from './ChatContent'; -import MobileBar from '../MobileBar'; -import StopGeneratingButton from '@components/StopGeneratingButton/StopGeneratingButton'; - -const Chat = () => { - const hideSideMenu = useStore((state) => state.hideSideMenu); - - return ( -
    - -
    - - -
    -
    - ); -}; - -export default Chat; diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/cdn/assets/Index-e24fc675.css b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/cdn/assets/Index-e24fc675.css deleted file mode 100644 index df50826e3be6b232e0cdd096afc4a71bee8b3422..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/cdn/assets/Index-e24fc675.css +++ /dev/null @@ -1 +0,0 @@ -.container.svelte-ju12zg.svelte-ju12zg{display:flex;flex-direction:column;gap:var(--spacing-sm);padding:var(--block-padding)}.hl.svelte-ju12zg+.hl.svelte-ju12zg{margin-left:var(--size-1)}.textspan.svelte-ju12zg:last-child>.label.svelte-ju12zg{margin-right:0}.category-legend.svelte-ju12zg.svelte-ju12zg{display:flex;flex-wrap:wrap;gap:var(--spacing-sm);color:#000}.category-label.svelte-ju12zg.svelte-ju12zg{cursor:pointer;border-radius:var(--radius-xs);padding-right:var(--size-2);padding-left:var(--size-2);font-weight:var(--weight-semibold)}.color-legend.svelte-ju12zg.svelte-ju12zg{display:flex;justify-content:space-between;border-radius:var(--radius-xs);background:linear-gradient(to right,var(--color-purple),rgba(255,255,255,0),var(--color-red));padding:var(--size-1) var(--size-2);font-weight:var(--weight-semibold)}.textfield.svelte-ju12zg.svelte-ju12zg{box-sizing:border-box;border-radius:var(--radius-xs);background:var(--background-fill-primary);background-color:transparent;max-width:var(--size-full);line-height:var(--scale-4);word-break:break-all}.textspan.svelte-ju12zg.svelte-ju12zg{transition:.15s;border-radius:var(--radius-xs);padding-top:2.5px;padding-right:var(--size-1);padding-bottom:3.5px;padding-left:var(--size-1);color:#000}.label.svelte-ju12zg.svelte-ju12zg{transition:.15s;margin-top:1px;border-radius:var(--radius-xs);padding:1px 5px;color:var(--body-text-color);color:#fff;font-weight:var(--weight-bold);font-size:var(--text-sm);text-transform:uppercase}.text.svelte-ju12zg.svelte-ju12zg{color:#000;white-space:pre-wrap}.score-text.svelte-ju12zg .text.svelte-ju12zg{color:var(--body-text-color)}.score-text.svelte-ju12zg.svelte-ju12zg{margin-right:var(--size-1);padding:var(--size-1)}.no-cat.svelte-ju12zg.svelte-ju12zg,.no-label.svelte-ju12zg.svelte-ju12zg{color:var(--body-text-color)}.selectable.svelte-ju12zg.svelte-ju12zg{cursor:pointer}.label-input.svelte-1cag2po{transition:.15s;margin-top:1px;margin-right:calc(var(--size-1));border-radius:var(--radius-xs);padding:1px 5px;color:#000;font-weight:var(--weight-bold);font-size:var(--text-sm);text-transform:uppercase;line-height:1;color:#fff}.label-input.svelte-1cag2po::placeholder{color:#01010180}.label-clear-button.svelte-1ozsnjl.svelte-1ozsnjl{display:none;border-radius:var(--radius-xs);padding-top:2.5px;padding-right:var(--size-1);padding-bottom:3.5px;padding-left:var(--size-1);color:#000;background-color:var(--background-fill-secondary);user-select:none;position:relative;left:-3px;border-radius:0 var(--radius-xs) var(--radius-xs) 0;color:var(--block-label-text-color)}.text-class_or_confidence-container.svelte-1ozsnjl:hover .label-clear-button.svelte-1ozsnjl,.text-class_or_confidence-container.svelte-1ozsnjl:focus-within .label-clear-button.svelte-1ozsnjl,.score-text-container.svelte-1ozsnjl:hover .label-clear-button.svelte-1ozsnjl,.score-text-container.svelte-1ozsnjl:focus-within .label-clear-button.svelte-1ozsnjl{display:inline}.text-class_or_confidence-container.svelte-1ozsnjl:hover .textspan.hl.svelte-1ozsnjl,.text-class_or_confidence-container.svelte-1ozsnjl:focus-within .textspan.hl.svelte-1ozsnjl,.score-text.svelte-1ozsnjl.svelte-1ozsnjl:hover{border-radius:var(--radius-xs) 0 0 var(--radius-xs)}.container.svelte-1ozsnjl.svelte-1ozsnjl{display:flex;flex-direction:column;gap:var(--spacing-sm);padding:var(--block-padding)}.hl.svelte-1ozsnjl.svelte-1ozsnjl{margin-left:var(--size-1);transition:background-color .3s;user-select:none}.textspan.svelte-1ozsnjl:last-child>.label.svelte-1ozsnjl{margin-right:0}.class_or_confidence-legend.svelte-1ozsnjl.svelte-1ozsnjl{display:flex;flex-wrap:wrap;gap:var(--spacing-sm);color:#000}.class_or_confidence-label.svelte-1ozsnjl.svelte-1ozsnjl{cursor:pointer;border-radius:var(--radius-xs);padding-right:var(--size-2);padding-left:var(--size-2);font-weight:var(--weight-semibold)}.color-legend.svelte-1ozsnjl.svelte-1ozsnjl{display:flex;justify-content:space-between;border-radius:var(--radius-xs);background:linear-gradient(to right,var(--color-purple),rgba(255,255,255,0),var(--color-red));padding:var(--size-1) var(--size-2);font-weight:var(--weight-semibold)}.textfield.svelte-1ozsnjl.svelte-1ozsnjl{box-sizing:border-box;border-radius:var(--radius-xs);background:var(--background-fill-primary);background-color:transparent;max-width:var(--size-full);line-height:var(--scale-4);word-break:break-all}.textspan.svelte-1ozsnjl.svelte-1ozsnjl{transition:.15s;border-radius:var(--radius-xs);padding-top:2.5px;padding-right:var(--size-1);padding-bottom:3.5px;padding-left:var(--size-1);color:#000;cursor:text}.label.svelte-1ozsnjl.svelte-1ozsnjl{transition:.15s;margin-top:1px;border-radius:var(--radius-xs);padding:1px 5px;color:var(--body-text-color);color:#fff;font-weight:var(--weight-bold);font-size:var(--text-sm);text-transform:uppercase;user-select:none}.text.svelte-1ozsnjl.svelte-1ozsnjl{color:#000;white-space:pre-wrap}.textspan.hl.svelte-1ozsnjl.svelte-1ozsnjl{user-select:none}.score-text-container.svelte-1ozsnjl.svelte-1ozsnjl{margin-right:var(--size-1)}.score-text.svelte-1ozsnjl .text.svelte-1ozsnjl,.no-cat.svelte-1ozsnjl.svelte-1ozsnjl{color:var(--body-text-color)}.no-label.svelte-1ozsnjl.svelte-1ozsnjl{color:var(--body-text-color);user-select:text}.selectable.svelte-1ozsnjl.svelte-1ozsnjl{cursor:text;user-select:text} diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jsonschema/benchmarks/unused_registry.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jsonschema/benchmarks/unused_registry.py deleted file mode 100644 index 600351c02e02b964fa0f902941bfa278cf3cc71b..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jsonschema/benchmarks/unused_registry.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -An unused schema registry should not cause slower validation. - -"Unused" here means one where no reference resolution is occurring anyhow. - -See https://github.com/python-jsonschema/jsonschema/issues/1088. -""" -from pyperf import Runner -from referencing import Registry -from referencing.jsonschema import DRAFT201909 - -from jsonschema import Draft201909Validator - -registry = Registry().with_resource( - "urn:example:foo", - DRAFT201909.create_resource({}) -) - -schema = {"$ref": "https://json-schema.org/draft/2019-09/schema"} -instance = {"maxLength": 4} - -no_registry = Draft201909Validator(schema) -with_useless_registry = Draft201909Validator(schema, registry=registry) - -if __name__ == "__main__": - runner = Runner() - - runner.bench_func( - "no registry", - lambda: no_registry.is_valid(instance), - ) - runner.bench_func( - "useless registry", - lambda: with_useless_registry.is_valid(instance), - ) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/tri/_triangulation.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/tri/_triangulation.py deleted file mode 100644 index a07192dfc8cac08a102be6ef3b22047f264a5099..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/tri/_triangulation.py +++ /dev/null @@ -1,247 +0,0 @@ -import sys - -import numpy as np - -from matplotlib import _api - - -class Triangulation: - """ - An unstructured triangular grid consisting of npoints points and - ntri triangles. The triangles can either be specified by the user - or automatically generated using a Delaunay triangulation. - - Parameters - ---------- - x, y : (npoints,) array-like - Coordinates of grid points. - triangles : (ntri, 3) array-like of int, optional - For each triangle, the indices of the three points that make - up the triangle, ordered in an anticlockwise manner. If not - specified, the Delaunay triangulation is calculated. - mask : (ntri,) array-like of bool, optional - Which triangles are masked out. - - Attributes - ---------- - triangles : (ntri, 3) array of int - For each triangle, the indices of the three points that make - up the triangle, ordered in an anticlockwise manner. If you want to - take the *mask* into account, use `get_masked_triangles` instead. - mask : (ntri, 3) array of bool or None - Masked out triangles. - is_delaunay : bool - Whether the Triangulation is a calculated Delaunay - triangulation (where *triangles* was not specified) or not. - - Notes - ----- - For a Triangulation to be valid it must not have duplicate points, - triangles formed from colinear points, or overlapping triangles. - """ - def __init__(self, x, y, triangles=None, mask=None): - from matplotlib import _qhull - - self.x = np.asarray(x, dtype=np.float64) - self.y = np.asarray(y, dtype=np.float64) - if self.x.shape != self.y.shape or self.x.ndim != 1: - raise ValueError("x and y must be equal-length 1D arrays, but " - f"found shapes {self.x.shape!r} and " - f"{self.y.shape!r}") - - self.mask = None - self._edges = None - self._neighbors = None - self.is_delaunay = False - - if triangles is None: - # No triangulation specified, so use matplotlib._qhull to obtain - # Delaunay triangulation. - self.triangles, self._neighbors = _qhull.delaunay(x, y, sys.flags.verbose) - self.is_delaunay = True - else: - # Triangulation specified. Copy, since we may correct triangle - # orientation. - try: - self.triangles = np.array(triangles, dtype=np.int32, order='C') - except ValueError as e: - raise ValueError('triangles must be a (N, 3) int array, not ' - f'{triangles!r}') from e - if self.triangles.ndim != 2 or self.triangles.shape[1] != 3: - raise ValueError( - 'triangles must be a (N, 3) int array, but found shape ' - f'{self.triangles.shape!r}') - if self.triangles.max() >= len(self.x): - raise ValueError( - 'triangles are indices into the points and must be in the ' - f'range 0 <= i < {len(self.x)} but found value ' - f'{self.triangles.max()}') - if self.triangles.min() < 0: - raise ValueError( - 'triangles are indices into the points and must be in the ' - f'range 0 <= i < {len(self.x)} but found value ' - f'{self.triangles.min()}') - - # Underlying C++ object is not created until first needed. - self._cpp_triangulation = None - - # Default TriFinder not created until needed. - self._trifinder = None - - self.set_mask(mask) - - def calculate_plane_coefficients(self, z): - """ - Calculate plane equation coefficients for all unmasked triangles from - the point (x, y) coordinates and specified z-array of shape (npoints). - The returned array has shape (npoints, 3) and allows z-value at (x, y) - position in triangle tri to be calculated using - ``z = array[tri, 0] * x + array[tri, 1] * y + array[tri, 2]``. - """ - return self.get_cpp_triangulation().calculate_plane_coefficients(z) - - @property - def edges(self): - """ - Return integer array of shape (nedges, 2) containing all edges of - non-masked triangles. - - Each row defines an edge by its start point index and end point - index. Each edge appears only once, i.e. for an edge between points - *i* and *j*, there will only be either *(i, j)* or *(j, i)*. - """ - if self._edges is None: - self._edges = self.get_cpp_triangulation().get_edges() - return self._edges - - def get_cpp_triangulation(self): - """ - Return the underlying C++ Triangulation object, creating it - if necessary. - """ - from matplotlib import _tri - if self._cpp_triangulation is None: - self._cpp_triangulation = _tri.Triangulation( - # For unset arrays use empty tuple which has size of zero. - self.x, self.y, self.triangles, - self.mask if self.mask is not None else (), - self._edges if self._edges is not None else (), - self._neighbors if self._neighbors is not None else (), - not self.is_delaunay) - return self._cpp_triangulation - - def get_masked_triangles(self): - """ - Return an array of triangles taking the mask into account. - """ - if self.mask is not None: - return self.triangles[~self.mask] - else: - return self.triangles - - @staticmethod - def get_from_args_and_kwargs(*args, **kwargs): - """ - Return a Triangulation object from the args and kwargs, and - the remaining args and kwargs with the consumed values removed. - - There are two alternatives: either the first argument is a - Triangulation object, in which case it is returned, or the args - and kwargs are sufficient to create a new Triangulation to - return. In the latter case, see Triangulation.__init__ for - the possible args and kwargs. - """ - if isinstance(args[0], Triangulation): - triangulation, *args = args - if 'triangles' in kwargs: - _api.warn_external( - "Passing the keyword 'triangles' has no effect when also " - "passing a Triangulation") - if 'mask' in kwargs: - _api.warn_external( - "Passing the keyword 'mask' has no effect when also " - "passing a Triangulation") - else: - x, y, triangles, mask, args, kwargs = \ - Triangulation._extract_triangulation_params(args, kwargs) - triangulation = Triangulation(x, y, triangles, mask) - return triangulation, args, kwargs - - @staticmethod - def _extract_triangulation_params(args, kwargs): - x, y, *args = args - # Check triangles in kwargs then args. - triangles = kwargs.pop('triangles', None) - from_args = False - if triangles is None and args: - triangles = args[0] - from_args = True - if triangles is not None: - try: - triangles = np.asarray(triangles, dtype=np.int32) - except ValueError: - triangles = None - if triangles is not None and (triangles.ndim != 2 or - triangles.shape[1] != 3): - triangles = None - if triangles is not None and from_args: - args = args[1:] # Consumed first item in args. - # Check for mask in kwargs. - mask = kwargs.pop('mask', None) - return x, y, triangles, mask, args, kwargs - - def get_trifinder(self): - """ - Return the default `matplotlib.tri.TriFinder` of this - triangulation, creating it if necessary. This allows the same - TriFinder object to be easily shared. - """ - if self._trifinder is None: - # Default TriFinder class. - from matplotlib.tri._trifinder import TrapezoidMapTriFinder - self._trifinder = TrapezoidMapTriFinder(self) - return self._trifinder - - @property - def neighbors(self): - """ - Return integer array of shape (ntri, 3) containing neighbor triangles. - - For each triangle, the indices of the three triangles that - share the same edges, or -1 if there is no such neighboring - triangle. ``neighbors[i, j]`` is the triangle that is the neighbor - to the edge from point index ``triangles[i, j]`` to point index - ``triangles[i, (j+1)%3]``. - """ - if self._neighbors is None: - self._neighbors = self.get_cpp_triangulation().get_neighbors() - return self._neighbors - - def set_mask(self, mask): - """ - Set or clear the mask array. - - Parameters - ---------- - mask : None or bool array of length ntri - """ - if mask is None: - self.mask = None - else: - self.mask = np.asarray(mask, dtype=bool) - if self.mask.shape != (self.triangles.shape[0],): - raise ValueError('mask array must have same length as ' - 'triangles array') - - # Set mask in C++ Triangulation. - if self._cpp_triangulation is not None: - self._cpp_triangulation.set_mask( - self.mask if self.mask is not None else ()) - - # Clear derived fields so they are recalculated when needed. - self._edges = None - self._neighbors = None - - # Recalculate TriFinder if it exists. - if self._trifinder is not None: - self._trifinder._initialize() diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/array_api/tests/test_array_object.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/array_api/tests/test_array_object.py deleted file mode 100644 index 0feb72c4ea33a632545e6329854644ac9b817a4a..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/array_api/tests/test_array_object.py +++ /dev/null @@ -1,395 +0,0 @@ -import operator - -from numpy.testing import assert_raises, suppress_warnings -import numpy as np -import pytest - -from .. import ones, asarray, reshape, result_type, all, equal -from .._array_object import Array -from .._dtypes import ( - _all_dtypes, - _boolean_dtypes, - _real_floating_dtypes, - _floating_dtypes, - _complex_floating_dtypes, - _integer_dtypes, - _integer_or_boolean_dtypes, - _real_numeric_dtypes, - _numeric_dtypes, - int8, - int16, - int32, - int64, - uint64, - bool as bool_, -) - - -def test_validate_index(): - # The indexing tests in the official array API test suite test that the - # array object correctly handles the subset of indices that are required - # by the spec. But the NumPy array API implementation specifically - # disallows any index not required by the spec, via Array._validate_index. - # This test focuses on testing that non-valid indices are correctly - # rejected. See - # https://data-apis.org/array-api/latest/API_specification/indexing.html - # and the docstring of Array._validate_index for the exact indexing - # behavior that should be allowed. This does not test indices that are - # already invalid in NumPy itself because Array will generally just pass - # such indices directly to the underlying np.ndarray. - - a = ones((3, 4)) - - # Out of bounds slices are not allowed - assert_raises(IndexError, lambda: a[:4]) - assert_raises(IndexError, lambda: a[:-4]) - assert_raises(IndexError, lambda: a[:3:-1]) - assert_raises(IndexError, lambda: a[:-5:-1]) - assert_raises(IndexError, lambda: a[4:]) - assert_raises(IndexError, lambda: a[-4:]) - assert_raises(IndexError, lambda: a[4::-1]) - assert_raises(IndexError, lambda: a[-4::-1]) - - assert_raises(IndexError, lambda: a[...,:5]) - assert_raises(IndexError, lambda: a[...,:-5]) - assert_raises(IndexError, lambda: a[...,:5:-1]) - assert_raises(IndexError, lambda: a[...,:-6:-1]) - assert_raises(IndexError, lambda: a[...,5:]) - assert_raises(IndexError, lambda: a[...,-5:]) - assert_raises(IndexError, lambda: a[...,5::-1]) - assert_raises(IndexError, lambda: a[...,-5::-1]) - - # Boolean indices cannot be part of a larger tuple index - assert_raises(IndexError, lambda: a[a[:,0]==1,0]) - assert_raises(IndexError, lambda: a[a[:,0]==1,...]) - assert_raises(IndexError, lambda: a[..., a[0]==1]) - assert_raises(IndexError, lambda: a[[True, True, True]]) - assert_raises(IndexError, lambda: a[(True, True, True),]) - - # Integer array indices are not allowed (except for 0-D) - idx = asarray([[0, 1]]) - assert_raises(IndexError, lambda: a[idx]) - assert_raises(IndexError, lambda: a[idx,]) - assert_raises(IndexError, lambda: a[[0, 1]]) - assert_raises(IndexError, lambda: a[(0, 1), (0, 1)]) - assert_raises(IndexError, lambda: a[[0, 1]]) - assert_raises(IndexError, lambda: a[np.array([[0, 1]])]) - - # Multiaxis indices must contain exactly as many indices as dimensions - assert_raises(IndexError, lambda: a[()]) - assert_raises(IndexError, lambda: a[0,]) - assert_raises(IndexError, lambda: a[0]) - assert_raises(IndexError, lambda: a[:]) - -def test_operators(): - # For every operator, we test that it works for the required type - # combinations and raises TypeError otherwise - binary_op_dtypes = { - "__add__": "numeric", - "__and__": "integer_or_boolean", - "__eq__": "all", - "__floordiv__": "real numeric", - "__ge__": "real numeric", - "__gt__": "real numeric", - "__le__": "real numeric", - "__lshift__": "integer", - "__lt__": "real numeric", - "__mod__": "real numeric", - "__mul__": "numeric", - "__ne__": "all", - "__or__": "integer_or_boolean", - "__pow__": "numeric", - "__rshift__": "integer", - "__sub__": "numeric", - "__truediv__": "floating", - "__xor__": "integer_or_boolean", - } - # Recompute each time because of in-place ops - def _array_vals(): - for d in _integer_dtypes: - yield asarray(1, dtype=d) - for d in _boolean_dtypes: - yield asarray(False, dtype=d) - for d in _floating_dtypes: - yield asarray(1.0, dtype=d) - - - BIG_INT = int(1e30) - for op, dtypes in binary_op_dtypes.items(): - ops = [op] - if op not in ["__eq__", "__ne__", "__le__", "__ge__", "__lt__", "__gt__"]: - rop = "__r" + op[2:] - iop = "__i" + op[2:] - ops += [rop, iop] - for s in [1, 1.0, 1j, BIG_INT, False]: - for _op in ops: - for a in _array_vals(): - # Test array op scalar. From the spec, the following combinations - # are supported: - - # - Python bool for a bool array dtype, - # - a Python int within the bounds of the given dtype for integer array dtypes, - # - a Python int or float for real floating-point array dtypes - # - a Python int, float, or complex for complex floating-point array dtypes - - if ((dtypes == "all" - or dtypes == "numeric" and a.dtype in _numeric_dtypes - or dtypes == "real numeric" and a.dtype in _real_numeric_dtypes - or dtypes == "integer" and a.dtype in _integer_dtypes - or dtypes == "integer_or_boolean" and a.dtype in _integer_or_boolean_dtypes - or dtypes == "boolean" and a.dtype in _boolean_dtypes - or dtypes == "floating" and a.dtype in _floating_dtypes - ) - # bool is a subtype of int, which is why we avoid - # isinstance here. - and (a.dtype in _boolean_dtypes and type(s) == bool - or a.dtype in _integer_dtypes and type(s) == int - or a.dtype in _real_floating_dtypes and type(s) in [float, int] - or a.dtype in _complex_floating_dtypes and type(s) in [complex, float, int] - )): - if a.dtype in _integer_dtypes and s == BIG_INT: - assert_raises(OverflowError, lambda: getattr(a, _op)(s)) - else: - # Only test for no error - with suppress_warnings() as sup: - # ignore warnings from pow(BIG_INT) - sup.filter(RuntimeWarning, - "invalid value encountered in power") - getattr(a, _op)(s) - else: - assert_raises(TypeError, lambda: getattr(a, _op)(s)) - - # Test array op array. - for _op in ops: - for x in _array_vals(): - for y in _array_vals(): - # See the promotion table in NEP 47 or the array - # API spec page on type promotion. Mixed kind - # promotion is not defined. - if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64] - or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64] - or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes - or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes - or x.dtype in _boolean_dtypes and y.dtype not in _boolean_dtypes - or y.dtype in _boolean_dtypes and x.dtype not in _boolean_dtypes - or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes - or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes - ): - assert_raises(TypeError, lambda: getattr(x, _op)(y)) - # Ensure in-place operators only promote to the same dtype as the left operand. - elif ( - _op.startswith("__i") - and result_type(x.dtype, y.dtype) != x.dtype - ): - assert_raises(TypeError, lambda: getattr(x, _op)(y)) - # Ensure only those dtypes that are required for every operator are allowed. - elif (dtypes == "all" and (x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes - or x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes) - or (dtypes == "real numeric" and x.dtype in _real_numeric_dtypes and y.dtype in _real_numeric_dtypes) - or (dtypes == "numeric" and x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes) - or dtypes == "integer" and x.dtype in _integer_dtypes and y.dtype in _integer_dtypes - or dtypes == "integer_or_boolean" and (x.dtype in _integer_dtypes and y.dtype in _integer_dtypes - or x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes) - or dtypes == "boolean" and x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes - or dtypes == "floating" and x.dtype in _floating_dtypes and y.dtype in _floating_dtypes - ): - getattr(x, _op)(y) - else: - assert_raises(TypeError, lambda: getattr(x, _op)(y)) - - unary_op_dtypes = { - "__abs__": "numeric", - "__invert__": "integer_or_boolean", - "__neg__": "numeric", - "__pos__": "numeric", - } - for op, dtypes in unary_op_dtypes.items(): - for a in _array_vals(): - if ( - dtypes == "numeric" - and a.dtype in _numeric_dtypes - or dtypes == "integer_or_boolean" - and a.dtype in _integer_or_boolean_dtypes - ): - # Only test for no error - getattr(a, op)() - else: - assert_raises(TypeError, lambda: getattr(a, op)()) - - # Finally, matmul() must be tested separately, because it works a bit - # different from the other operations. - def _matmul_array_vals(): - for a in _array_vals(): - yield a - for d in _all_dtypes: - yield ones((3, 4), dtype=d) - yield ones((4, 2), dtype=d) - yield ones((4, 4), dtype=d) - - # Scalars always error - for _op in ["__matmul__", "__rmatmul__", "__imatmul__"]: - for s in [1, 1.0, False]: - for a in _matmul_array_vals(): - if (type(s) in [float, int] and a.dtype in _floating_dtypes - or type(s) == int and a.dtype in _integer_dtypes): - # Type promotion is valid, but @ is not allowed on 0-D - # inputs, so the error is a ValueError - assert_raises(ValueError, lambda: getattr(a, _op)(s)) - else: - assert_raises(TypeError, lambda: getattr(a, _op)(s)) - - for x in _matmul_array_vals(): - for y in _matmul_array_vals(): - if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64] - or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64] - or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes - or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes - or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes - or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes - or x.dtype in _boolean_dtypes - or y.dtype in _boolean_dtypes - ): - assert_raises(TypeError, lambda: x.__matmul__(y)) - assert_raises(TypeError, lambda: y.__rmatmul__(x)) - assert_raises(TypeError, lambda: x.__imatmul__(y)) - elif x.shape == () or y.shape == () or x.shape[1] != y.shape[0]: - assert_raises(ValueError, lambda: x.__matmul__(y)) - assert_raises(ValueError, lambda: y.__rmatmul__(x)) - if result_type(x.dtype, y.dtype) != x.dtype: - assert_raises(TypeError, lambda: x.__imatmul__(y)) - else: - assert_raises(ValueError, lambda: x.__imatmul__(y)) - else: - x.__matmul__(y) - y.__rmatmul__(x) - if result_type(x.dtype, y.dtype) != x.dtype: - assert_raises(TypeError, lambda: x.__imatmul__(y)) - elif y.shape[0] != y.shape[1]: - # This one fails because x @ y has a different shape from x - assert_raises(ValueError, lambda: x.__imatmul__(y)) - else: - x.__imatmul__(y) - - -def test_python_scalar_construtors(): - b = asarray(False) - i = asarray(0) - f = asarray(0.0) - c = asarray(0j) - - assert bool(b) == False - assert int(i) == 0 - assert float(f) == 0.0 - assert operator.index(i) == 0 - - # bool/int/float/complex should only be allowed on 0-D arrays. - assert_raises(TypeError, lambda: bool(asarray([False]))) - assert_raises(TypeError, lambda: int(asarray([0]))) - assert_raises(TypeError, lambda: float(asarray([0.0]))) - assert_raises(TypeError, lambda: complex(asarray([0j]))) - assert_raises(TypeError, lambda: operator.index(asarray([0]))) - - # bool should work on all types of arrays - assert bool(b) is bool(i) is bool(f) is bool(c) is False - - # int should fail on complex arrays - assert int(b) == int(i) == int(f) == 0 - assert_raises(TypeError, lambda: int(c)) - - # float should fail on complex arrays - assert float(b) == float(i) == float(f) == 0.0 - assert_raises(TypeError, lambda: float(c)) - - # complex should work on all types of arrays - assert complex(b) == complex(i) == complex(f) == complex(c) == 0j - - # index should only work on integer arrays - assert operator.index(i) == 0 - assert_raises(TypeError, lambda: operator.index(b)) - assert_raises(TypeError, lambda: operator.index(f)) - assert_raises(TypeError, lambda: operator.index(c)) - - -def test_device_property(): - a = ones((3, 4)) - assert a.device == 'cpu' - - assert all(equal(a.to_device('cpu'), a)) - assert_raises(ValueError, lambda: a.to_device('gpu')) - - assert all(equal(asarray(a, device='cpu'), a)) - assert_raises(ValueError, lambda: asarray(a, device='gpu')) - -def test_array_properties(): - a = ones((1, 2, 3)) - b = ones((2, 3)) - assert_raises(ValueError, lambda: a.T) - - assert isinstance(b.T, Array) - assert b.T.shape == (3, 2) - - assert isinstance(a.mT, Array) - assert a.mT.shape == (1, 3, 2) - assert isinstance(b.mT, Array) - assert b.mT.shape == (3, 2) - -def test___array__(): - a = ones((2, 3), dtype=int16) - assert np.asarray(a) is a._array - b = np.asarray(a, dtype=np.float64) - assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64))) - assert b.dtype == np.float64 - -def test_allow_newaxis(): - a = ones(5) - indexed_a = a[None, :] - assert indexed_a.shape == (1, 5) - -def test_disallow_flat_indexing_with_newaxis(): - a = ones((3, 3, 3)) - with pytest.raises(IndexError): - a[None, 0, 0] - -def test_disallow_mask_with_newaxis(): - a = ones((3, 3, 3)) - with pytest.raises(IndexError): - a[None, asarray(True)] - -@pytest.mark.parametrize("shape", [(), (5,), (3, 3, 3)]) -@pytest.mark.parametrize("index", ["string", False, True]) -def test_error_on_invalid_index(shape, index): - a = ones(shape) - with pytest.raises(IndexError): - a[index] - -def test_mask_0d_array_without_errors(): - a = ones(()) - a[asarray(True)] - -@pytest.mark.parametrize( - "i", [slice(5), slice(5, 0), asarray(True), asarray([0, 1])] -) -def test_error_on_invalid_index_with_ellipsis(i): - a = ones((3, 3, 3)) - with pytest.raises(IndexError): - a[..., i] - with pytest.raises(IndexError): - a[i, ...] - -def test_array_keys_use_private_array(): - """ - Indexing operations convert array keys before indexing the internal array - - Fails when array_api array keys are not converted into NumPy-proper arrays - in __getitem__(). This is achieved by passing array_api arrays with 0-sized - dimensions, which NumPy-proper treats erroneously - not sure why! - - TODO: Find and use appropriate __setitem__() case. - """ - a = ones((0, 0), dtype=bool_) - assert a[a].shape == (0,) - - a = ones((0,), dtype=bool_) - key = ones((0, 0), dtype=bool_) - with pytest.raises(IndexError): - a[key] diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/distutils/checks/cpu_avx512_spr.c b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/distutils/checks/cpu_avx512_spr.c deleted file mode 100644 index 9710d0b2fe2f2ac1fc9e19c1c9b4688807efd6d7..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/distutils/checks/cpu_avx512_spr.c +++ /dev/null @@ -1,26 +0,0 @@ -#if defined(DETECT_FEATURES) && defined(__INTEL_COMPILER) - /* - * Unlike GCC and CLANG, Intel Compiler exposes all supported intrinsics, - * whether or not the build options for those features are specified. - * Therefore, we must test #definitions of CPU features when option native/host - * is enabled via `--cpu-baseline` or through env var `CFLAGS` otherwise - * the test will be broken and leads to enable all possible features. - */ - #if !defined(__AVX512FP16__) - #error "HOST/ARCH doesn't support Sapphire Rapids AVX512FP16 features" - #endif -#endif - -#include - -int main(int argc, char **argv) -{ -/* clang has a bug regarding our spr coode, see gh-23730. */ -#if __clang__ -#error -#endif - __m512h a = _mm512_loadu_ph((void*)argv[argc-1]); - __m512h temp = _mm512_fmadd_ph(a, a, a); - _mm512_storeu_ph((void*)(argv[argc-1]), temp); - return 0; -} diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/core/arrays/sparse/array.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/core/arrays/sparse/array.py deleted file mode 100644 index e38fa0a3bdae5697e4511c5b8ae154db3d15a106..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/core/arrays/sparse/array.py +++ /dev/null @@ -1,1908 +0,0 @@ -""" -SparseArray data structure -""" -from __future__ import annotations - -from collections import abc -import numbers -import operator -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Literal, - cast, - overload, -) -import warnings - -import numpy as np - -from pandas._libs import lib -import pandas._libs.sparse as splib -from pandas._libs.sparse import ( - BlockIndex, - IntIndex, - SparseIndex, -) -from pandas._libs.tslibs import NaT -from pandas.compat.numpy import function as nv -from pandas.errors import PerformanceWarning -from pandas.util._exceptions import find_stack_level -from pandas.util._validators import ( - validate_bool_kwarg, - validate_insert_loc, -) - -from pandas.core.dtypes.astype import astype_array -from pandas.core.dtypes.cast import ( - construct_1d_arraylike_from_scalar, - find_common_type, - maybe_box_datetimelike, -) -from pandas.core.dtypes.common import ( - is_bool_dtype, - is_integer, - is_list_like, - is_object_dtype, - is_scalar, - is_string_dtype, - pandas_dtype, -) -from pandas.core.dtypes.dtypes import ( - DatetimeTZDtype, - SparseDtype, -) -from pandas.core.dtypes.generic import ( - ABCIndex, - ABCSeries, -) -from pandas.core.dtypes.missing import ( - isna, - na_value_for_dtype, - notna, -) - -from pandas.core import arraylike -import pandas.core.algorithms as algos -from pandas.core.arraylike import OpsMixin -from pandas.core.arrays import ExtensionArray -from pandas.core.base import PandasObject -import pandas.core.common as com -from pandas.core.construction import ( - ensure_wrapped_if_datetimelike, - extract_array, - sanitize_array, -) -from pandas.core.indexers import ( - check_array_indexer, - unpack_tuple_and_ellipses, -) -from pandas.core.nanops import check_below_min_count - -from pandas.io.formats import printing - -# See https://github.com/python/typing/issues/684 -if TYPE_CHECKING: - from collections.abc import Sequence - from enum import Enum - - class ellipsis(Enum): - Ellipsis = "..." - - Ellipsis = ellipsis.Ellipsis - - from scipy.sparse import spmatrix - - from pandas._typing import ( - FillnaOptions, - NumpySorter, - ) - - SparseIndexKind = Literal["integer", "block"] - - from pandas._typing import ( - ArrayLike, - AstypeArg, - Axis, - AxisInt, - Dtype, - NpDtype, - PositionalIndexer, - Scalar, - ScalarIndexer, - Self, - SequenceIndexer, - npt, - ) - - from pandas import Series - -else: - ellipsis = type(Ellipsis) - - -# ---------------------------------------------------------------------------- -# Array - -_sparray_doc_kwargs = {"klass": "SparseArray"} - - -def _get_fill(arr: SparseArray) -> np.ndarray: - """ - Create a 0-dim ndarray containing the fill value - - Parameters - ---------- - arr : SparseArray - - Returns - ------- - fill_value : ndarray - 0-dim ndarray with just the fill value. - - Notes - ----- - coerce fill_value to arr dtype if possible - int64 SparseArray can have NaN as fill_value if there is no missing - """ - try: - return np.asarray(arr.fill_value, dtype=arr.dtype.subtype) - except ValueError: - return np.asarray(arr.fill_value) - - -def _sparse_array_op( - left: SparseArray, right: SparseArray, op: Callable, name: str -) -> SparseArray: - """ - Perform a binary operation between two arrays. - - Parameters - ---------- - left : Union[SparseArray, ndarray] - right : Union[SparseArray, ndarray] - op : Callable - The binary operation to perform - name str - Name of the callable. - - Returns - ------- - SparseArray - """ - if name.startswith("__"): - # For lookups in _libs.sparse we need non-dunder op name - name = name[2:-2] - - # dtype used to find corresponding sparse method - ltype = left.dtype.subtype - rtype = right.dtype.subtype - - if ltype != rtype: - subtype = find_common_type([ltype, rtype]) - ltype = SparseDtype(subtype, left.fill_value) - rtype = SparseDtype(subtype, right.fill_value) - - left = left.astype(ltype, copy=False) - right = right.astype(rtype, copy=False) - dtype = ltype.subtype - else: - dtype = ltype - - # dtype the result must have - result_dtype = None - - if left.sp_index.ngaps == 0 or right.sp_index.ngaps == 0: - with np.errstate(all="ignore"): - result = op(left.to_dense(), right.to_dense()) - fill = op(_get_fill(left), _get_fill(right)) - - if left.sp_index.ngaps == 0: - index = left.sp_index - else: - index = right.sp_index - elif left.sp_index.equals(right.sp_index): - with np.errstate(all="ignore"): - result = op(left.sp_values, right.sp_values) - fill = op(_get_fill(left), _get_fill(right)) - index = left.sp_index - else: - if name[0] == "r": - left, right = right, left - name = name[1:] - - if name in ("and", "or", "xor") and dtype == "bool": - opname = f"sparse_{name}_uint8" - # to make template simple, cast here - left_sp_values = left.sp_values.view(np.uint8) - right_sp_values = right.sp_values.view(np.uint8) - result_dtype = bool - else: - opname = f"sparse_{name}_{dtype}" - left_sp_values = left.sp_values - right_sp_values = right.sp_values - - if ( - name in ["floordiv", "mod"] - and (right == 0).any() - and left.dtype.kind in "iu" - ): - # Match the non-Sparse Series behavior - opname = f"sparse_{name}_float64" - left_sp_values = left_sp_values.astype("float64") - right_sp_values = right_sp_values.astype("float64") - - sparse_op = getattr(splib, opname) - - with np.errstate(all="ignore"): - result, index, fill = sparse_op( - left_sp_values, - left.sp_index, - left.fill_value, - right_sp_values, - right.sp_index, - right.fill_value, - ) - - if name == "divmod": - # result is a 2-tuple - # error: Incompatible return value type (got "Tuple[SparseArray, - # SparseArray]", expected "SparseArray") - return ( # type: ignore[return-value] - _wrap_result(name, result[0], index, fill[0], dtype=result_dtype), - _wrap_result(name, result[1], index, fill[1], dtype=result_dtype), - ) - - if result_dtype is None: - result_dtype = result.dtype - - return _wrap_result(name, result, index, fill, dtype=result_dtype) - - -def _wrap_result( - name: str, data, sparse_index, fill_value, dtype: Dtype | None = None -) -> SparseArray: - """ - wrap op result to have correct dtype - """ - if name.startswith("__"): - # e.g. __eq__ --> eq - name = name[2:-2] - - if name in ("eq", "ne", "lt", "gt", "le", "ge"): - dtype = bool - - fill_value = lib.item_from_zerodim(fill_value) - - if is_bool_dtype(dtype): - # fill_value may be np.bool_ - fill_value = bool(fill_value) - return SparseArray( - data, sparse_index=sparse_index, fill_value=fill_value, dtype=dtype - ) - - -class SparseArray(OpsMixin, PandasObject, ExtensionArray): - """ - An ExtensionArray for storing sparse data. - - Parameters - ---------- - data : array-like or scalar - A dense array of values to store in the SparseArray. This may contain - `fill_value`. - sparse_index : SparseIndex, optional - fill_value : scalar, optional - Elements in data that are ``fill_value`` are not stored in the - SparseArray. For memory savings, this should be the most common value - in `data`. By default, `fill_value` depends on the dtype of `data`: - - =========== ========== - data.dtype na_value - =========== ========== - float ``np.nan`` - int ``0`` - bool False - datetime64 ``pd.NaT`` - timedelta64 ``pd.NaT`` - =========== ========== - - The fill value is potentially specified in three ways. In order of - precedence, these are - - 1. The `fill_value` argument - 2. ``dtype.fill_value`` if `fill_value` is None and `dtype` is - a ``SparseDtype`` - 3. ``data.dtype.fill_value`` if `fill_value` is None and `dtype` - is not a ``SparseDtype`` and `data` is a ``SparseArray``. - - kind : str - Can be 'integer' or 'block', default is 'integer'. - The type of storage for sparse locations. - - * 'block': Stores a `block` and `block_length` for each - contiguous *span* of sparse values. This is best when - sparse data tends to be clumped together, with large - regions of ``fill-value`` values between sparse values. - * 'integer': uses an integer to store the location of - each sparse value. - - dtype : np.dtype or SparseDtype, optional - The dtype to use for the SparseArray. For numpy dtypes, this - determines the dtype of ``self.sp_values``. For SparseDtype, - this determines ``self.sp_values`` and ``self.fill_value``. - copy : bool, default False - Whether to explicitly copy the incoming `data` array. - - Attributes - ---------- - None - - Methods - ------- - None - - Examples - -------- - >>> from pandas.arrays import SparseArray - >>> arr = SparseArray([0, 0, 1, 2]) - >>> arr - [0, 0, 1, 2] - Fill: 0 - IntIndex - Indices: array([2, 3], dtype=int32) - """ - - _subtyp = "sparse_array" # register ABCSparseArray - _hidden_attrs = PandasObject._hidden_attrs | frozenset([]) - _sparse_index: SparseIndex - _sparse_values: np.ndarray - _dtype: SparseDtype - - def __init__( - self, - data, - sparse_index=None, - fill_value=None, - kind: SparseIndexKind = "integer", - dtype: Dtype | None = None, - copy: bool = False, - ) -> None: - if fill_value is None and isinstance(dtype, SparseDtype): - fill_value = dtype.fill_value - - if isinstance(data, type(self)): - # disable normal inference on dtype, sparse_index, & fill_value - if sparse_index is None: - sparse_index = data.sp_index - if fill_value is None: - fill_value = data.fill_value - if dtype is None: - dtype = data.dtype - # TODO: make kind=None, and use data.kind? - data = data.sp_values - - # Handle use-provided dtype - if isinstance(dtype, str): - # Two options: dtype='int', regular numpy dtype - # or dtype='Sparse[int]', a sparse dtype - try: - dtype = SparseDtype.construct_from_string(dtype) - except TypeError: - dtype = pandas_dtype(dtype) - - if isinstance(dtype, SparseDtype): - if fill_value is None: - fill_value = dtype.fill_value - dtype = dtype.subtype - - if is_scalar(data): - warnings.warn( - f"Constructing {type(self).__name__} with scalar data is deprecated " - "and will raise in a future version. Pass a sequence instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - if sparse_index is None: - npoints = 1 - else: - npoints = sparse_index.length - - data = construct_1d_arraylike_from_scalar(data, npoints, dtype=None) - dtype = data.dtype - - if dtype is not None: - dtype = pandas_dtype(dtype) - - # TODO: disentangle the fill_value dtype inference from - # dtype inference - if data is None: - # TODO: What should the empty dtype be? Object or float? - - # error: Argument "dtype" to "array" has incompatible type - # "Union[ExtensionDtype, dtype[Any], None]"; expected "Union[dtype[Any], - # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, - # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" - data = np.array([], dtype=dtype) # type: ignore[arg-type] - - try: - data = sanitize_array(data, index=None) - except ValueError: - # NumPy may raise a ValueError on data like [1, []] - # we retry with object dtype here. - if dtype is None: - dtype = np.dtype(object) - data = np.atleast_1d(np.asarray(data, dtype=dtype)) - else: - raise - - if copy: - # TODO: avoid double copy when dtype forces cast. - data = data.copy() - - if fill_value is None: - fill_value_dtype = data.dtype if dtype is None else dtype - if fill_value_dtype is None: - fill_value = np.nan - else: - fill_value = na_value_for_dtype(fill_value_dtype) - - if isinstance(data, type(self)) and sparse_index is None: - sparse_index = data._sparse_index - # error: Argument "dtype" to "asarray" has incompatible type - # "Union[ExtensionDtype, dtype[Any], None]"; expected "None" - sparse_values = np.asarray( - data.sp_values, dtype=dtype # type: ignore[arg-type] - ) - elif sparse_index is None: - data = extract_array(data, extract_numpy=True) - if not isinstance(data, np.ndarray): - # EA - if isinstance(data.dtype, DatetimeTZDtype): - warnings.warn( - f"Creating SparseArray from {data.dtype} data " - "loses timezone information. Cast to object before " - "sparse to retain timezone information.", - UserWarning, - stacklevel=find_stack_level(), - ) - data = np.asarray(data, dtype="datetime64[ns]") - if fill_value is NaT: - fill_value = np.datetime64("NaT", "ns") - data = np.asarray(data) - sparse_values, sparse_index, fill_value = _make_sparse( - # error: Argument "dtype" to "_make_sparse" has incompatible type - # "Union[ExtensionDtype, dtype[Any], None]"; expected - # "Optional[dtype[Any]]" - data, - kind=kind, - fill_value=fill_value, - dtype=dtype, # type: ignore[arg-type] - ) - else: - # error: Argument "dtype" to "asarray" has incompatible type - # "Union[ExtensionDtype, dtype[Any], None]"; expected "None" - sparse_values = np.asarray(data, dtype=dtype) # type: ignore[arg-type] - if len(sparse_values) != sparse_index.npoints: - raise AssertionError( - f"Non array-like type {type(sparse_values)} must " - "have the same length as the index" - ) - self._sparse_index = sparse_index - self._sparse_values = sparse_values - self._dtype = SparseDtype(sparse_values.dtype, fill_value) - - @classmethod - def _simple_new( - cls, - sparse_array: np.ndarray, - sparse_index: SparseIndex, - dtype: SparseDtype, - ) -> Self: - new = object.__new__(cls) - new._sparse_index = sparse_index - new._sparse_values = sparse_array - new._dtype = dtype - return new - - @classmethod - def from_spmatrix(cls, data: spmatrix) -> Self: - """ - Create a SparseArray from a scipy.sparse matrix. - - Parameters - ---------- - data : scipy.sparse.sp_matrix - This should be a SciPy sparse matrix where the size - of the second dimension is 1. In other words, a - sparse matrix with a single column. - - Returns - ------- - SparseArray - - Examples - -------- - >>> import scipy.sparse - >>> mat = scipy.sparse.coo_matrix((4, 1)) - >>> pd.arrays.SparseArray.from_spmatrix(mat) - [0.0, 0.0, 0.0, 0.0] - Fill: 0.0 - IntIndex - Indices: array([], dtype=int32) - """ - length, ncol = data.shape - - if ncol != 1: - raise ValueError(f"'data' must have a single column, not '{ncol}'") - - # our sparse index classes require that the positions be strictly - # increasing. So we need to sort loc, and arr accordingly. - data = data.tocsc() - data.sort_indices() - arr = data.data - idx = data.indices - - zero = np.array(0, dtype=arr.dtype).item() - dtype = SparseDtype(arr.dtype, zero) - index = IntIndex(length, idx) - - return cls._simple_new(arr, index, dtype) - - def __array__(self, dtype: NpDtype | None = None) -> np.ndarray: - fill_value = self.fill_value - - if self.sp_index.ngaps == 0: - # Compat for na dtype and int values. - return self.sp_values - if dtype is None: - # Can NumPy represent this type? - # If not, `np.result_type` will raise. We catch that - # and return object. - if self.sp_values.dtype.kind == "M": - # However, we *do* special-case the common case of - # a datetime64 with pandas NaT. - if fill_value is NaT: - # Can't put pd.NaT in a datetime64[ns] - fill_value = np.datetime64("NaT") - try: - dtype = np.result_type(self.sp_values.dtype, type(fill_value)) - except TypeError: - dtype = object - - out = np.full(self.shape, fill_value, dtype=dtype) - out[self.sp_index.indices] = self.sp_values - return out - - def __setitem__(self, key, value) -> None: - # I suppose we could allow setting of non-fill_value elements. - # TODO(SparseArray.__setitem__): remove special cases in - # ExtensionBlock.where - msg = "SparseArray does not support item assignment via setitem" - raise TypeError(msg) - - @classmethod - def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False): - return cls(scalars, dtype=dtype) - - @classmethod - def _from_factorized(cls, values, original): - return cls(values, dtype=original.dtype) - - # ------------------------------------------------------------------------ - # Data - # ------------------------------------------------------------------------ - @property - def sp_index(self) -> SparseIndex: - """ - The SparseIndex containing the location of non- ``fill_value`` points. - """ - return self._sparse_index - - @property - def sp_values(self) -> np.ndarray: - """ - An ndarray containing the non- ``fill_value`` values. - - Examples - -------- - >>> from pandas.arrays import SparseArray - >>> s = SparseArray([0, 0, 1, 0, 2], fill_value=0) - >>> s.sp_values - array([1, 2]) - """ - return self._sparse_values - - @property - def dtype(self) -> SparseDtype: - return self._dtype - - @property - def fill_value(self): - """ - Elements in `data` that are `fill_value` are not stored. - - For memory savings, this should be the most common value in the array. - - Examples - -------- - >>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]") - >>> ser.sparse.fill_value - 0 - >>> spa_dtype = pd.SparseDtype(dtype=np.int32, fill_value=2) - >>> ser = pd.Series([0, 0, 2, 2, 2], dtype=spa_dtype) - >>> ser.sparse.fill_value - 2 - """ - return self.dtype.fill_value - - @fill_value.setter - def fill_value(self, value) -> None: - self._dtype = SparseDtype(self.dtype.subtype, value) - - @property - def kind(self) -> SparseIndexKind: - """ - The kind of sparse index for this array. One of {'integer', 'block'}. - """ - if isinstance(self.sp_index, IntIndex): - return "integer" - else: - return "block" - - @property - def _valid_sp_values(self) -> np.ndarray: - sp_vals = self.sp_values - mask = notna(sp_vals) - return sp_vals[mask] - - def __len__(self) -> int: - return self.sp_index.length - - @property - def _null_fill_value(self) -> bool: - return self._dtype._is_na_fill_value - - def _fill_value_matches(self, fill_value) -> bool: - if self._null_fill_value: - return isna(fill_value) - else: - return self.fill_value == fill_value - - @property - def nbytes(self) -> int: - return self.sp_values.nbytes + self.sp_index.nbytes - - @property - def density(self) -> float: - """ - The percent of non- ``fill_value`` points, as decimal. - - Examples - -------- - >>> from pandas.arrays import SparseArray - >>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0) - >>> s.density - 0.6 - """ - return self.sp_index.npoints / self.sp_index.length - - @property - def npoints(self) -> int: - """ - The number of non- ``fill_value`` points. - - Examples - -------- - >>> from pandas.arrays import SparseArray - >>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0) - >>> s.npoints - 3 - """ - return self.sp_index.npoints - - def isna(self): - # If null fill value, we want SparseDtype[bool, true] - # to preserve the same memory usage. - dtype = SparseDtype(bool, self._null_fill_value) - if self._null_fill_value: - return type(self)._simple_new(isna(self.sp_values), self.sp_index, dtype) - mask = np.full(len(self), False, dtype=np.bool_) - mask[self.sp_index.indices] = isna(self.sp_values) - return type(self)(mask, fill_value=False, dtype=dtype) - - def _pad_or_backfill( # pylint: disable=useless-parent-delegation - self, *, method: FillnaOptions, limit: int | None = None, copy: bool = True - ) -> Self: - # TODO(3.0): We can remove this method once deprecation for fillna method - # keyword is enforced. - return super()._pad_or_backfill(method=method, limit=limit, copy=copy) - - def fillna( - self, - value=None, - method: FillnaOptions | None = None, - limit: int | None = None, - copy: bool = True, - ) -> Self: - """ - Fill missing values with `value`. - - Parameters - ---------- - value : scalar, optional - method : str, optional - - .. warning:: - - Using 'method' will result in high memory use, - as all `fill_value` methods will be converted to - an in-memory ndarray - - limit : int, optional - - copy: bool, default True - Ignored for SparseArray. - - Returns - ------- - SparseArray - - Notes - ----- - When `value` is specified, the result's ``fill_value`` depends on - ``self.fill_value``. The goal is to maintain low-memory use. - - If ``self.fill_value`` is NA, the result dtype will be - ``SparseDtype(self.dtype, fill_value=value)``. This will preserve - amount of memory used before and after filling. - - When ``self.fill_value`` is not NA, the result dtype will be - ``self.dtype``. Again, this preserves the amount of memory used. - """ - if (method is None and value is None) or ( - method is not None and value is not None - ): - raise ValueError("Must specify one of 'method' or 'value'.") - - if method is not None: - return super().fillna(method=method, limit=limit) - - else: - new_values = np.where(isna(self.sp_values), value, self.sp_values) - - if self._null_fill_value: - # This is essentially just updating the dtype. - new_dtype = SparseDtype(self.dtype.subtype, fill_value=value) - else: - new_dtype = self.dtype - - return self._simple_new(new_values, self._sparse_index, new_dtype) - - def shift(self, periods: int = 1, fill_value=None) -> Self: - if not len(self) or periods == 0: - return self.copy() - - if isna(fill_value): - fill_value = self.dtype.na_value - - subtype = np.result_type(fill_value, self.dtype.subtype) - - if subtype != self.dtype.subtype: - # just coerce up front - arr = self.astype(SparseDtype(subtype, self.fill_value)) - else: - arr = self - - empty = self._from_sequence( - [fill_value] * min(abs(periods), len(self)), dtype=arr.dtype - ) - - if periods > 0: - a = empty - b = arr[:-periods] - else: - a = arr[abs(periods) :] - b = empty - return arr._concat_same_type([a, b]) - - def _first_fill_value_loc(self): - """ - Get the location of the first fill value. - - Returns - ------- - int - """ - if len(self) == 0 or self.sp_index.npoints == len(self): - return -1 - - indices = self.sp_index.indices - if not len(indices) or indices[0] > 0: - return 0 - - # a number larger than 1 should be appended to - # the last in case of fill value only appears - # in the tail of array - diff = np.r_[np.diff(indices), 2] - return indices[(diff > 1).argmax()] + 1 - - def unique(self) -> Self: - uniques = algos.unique(self.sp_values) - if len(self.sp_values) != len(self): - fill_loc = self._first_fill_value_loc() - # Inorder to align the behavior of pd.unique or - # pd.Series.unique, we should keep the original - # order, here we use unique again to find the - # insertion place. Since the length of sp_values - # is not large, maybe minor performance hurt - # is worthwhile to the correctness. - insert_loc = len(algos.unique(self.sp_values[:fill_loc])) - uniques = np.insert(uniques, insert_loc, self.fill_value) - return type(self)._from_sequence(uniques, dtype=self.dtype) - - def _values_for_factorize(self): - # Still override this for hash_pandas_object - return np.asarray(self), self.fill_value - - def factorize( - self, - use_na_sentinel: bool = True, - ) -> tuple[np.ndarray, SparseArray]: - # Currently, ExtensionArray.factorize -> Tuple[ndarray, EA] - # The sparsity on this is backwards from what Sparse would want. Want - # ExtensionArray.factorize -> Tuple[EA, EA] - # Given that we have to return a dense array of codes, why bother - # implementing an efficient factorize? - codes, uniques = algos.factorize( - np.asarray(self), use_na_sentinel=use_na_sentinel - ) - uniques_sp = SparseArray(uniques, dtype=self.dtype) - return codes, uniques_sp - - def value_counts(self, dropna: bool = True) -> Series: - """ - Returns a Series containing counts of unique values. - - Parameters - ---------- - dropna : bool, default True - Don't include counts of NaN, even if NaN is in sp_values. - - Returns - ------- - counts : Series - """ - from pandas import ( - Index, - Series, - ) - - keys, counts = algos.value_counts_arraylike(self.sp_values, dropna=dropna) - fcounts = self.sp_index.ngaps - if fcounts > 0 and (not self._null_fill_value or not dropna): - mask = isna(keys) if self._null_fill_value else keys == self.fill_value - if mask.any(): - counts[mask] += fcounts - else: - # error: Argument 1 to "insert" has incompatible type "Union[ - # ExtensionArray,ndarray[Any, Any]]"; expected "Union[ - # _SupportsArray[dtype[Any]], Sequence[_SupportsArray[dtype - # [Any]]], Sequence[Sequence[_SupportsArray[dtype[Any]]]], - # Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]], Sequence - # [Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]]]]" - keys = np.insert(keys, 0, self.fill_value) # type: ignore[arg-type] - counts = np.insert(counts, 0, fcounts) - - if not isinstance(keys, ABCIndex): - index = Index(keys) - else: - index = keys - return Series(counts, index=index, copy=False) - - # -------- - # Indexing - # -------- - @overload - def __getitem__(self, key: ScalarIndexer) -> Any: - ... - - @overload - def __getitem__( - self, - key: SequenceIndexer | tuple[int | ellipsis, ...], - ) -> Self: - ... - - def __getitem__( - self, - key: PositionalIndexer | tuple[int | ellipsis, ...], - ) -> Self | Any: - if isinstance(key, tuple): - key = unpack_tuple_and_ellipses(key) - if key is Ellipsis: - raise ValueError("Cannot slice with Ellipsis") - - if is_integer(key): - return self._get_val_at(key) - elif isinstance(key, tuple): - # error: Invalid index type "Tuple[Union[int, ellipsis], ...]" - # for "ndarray[Any, Any]"; expected type - # "Union[SupportsIndex, _SupportsArray[dtype[Union[bool_, - # integer[Any]]]], _NestedSequence[_SupportsArray[dtype[ - # Union[bool_, integer[Any]]]]], _NestedSequence[Union[ - # bool, int]], Tuple[Union[SupportsIndex, _SupportsArray[ - # dtype[Union[bool_, integer[Any]]]], _NestedSequence[ - # _SupportsArray[dtype[Union[bool_, integer[Any]]]]], - # _NestedSequence[Union[bool, int]]], ...]]" - data_slice = self.to_dense()[key] # type: ignore[index] - elif isinstance(key, slice): - # Avoid densifying when handling contiguous slices - if key.step is None or key.step == 1: - start = 0 if key.start is None else key.start - if start < 0: - start += len(self) - - end = len(self) if key.stop is None else key.stop - if end < 0: - end += len(self) - - indices = self.sp_index.indices - keep_inds = np.flatnonzero((indices >= start) & (indices < end)) - sp_vals = self.sp_values[keep_inds] - - sp_index = indices[keep_inds].copy() - - # If we've sliced to not include the start of the array, all our indices - # should be shifted. NB: here we are careful to also not shift by a - # negative value for a case like [0, 1][-100:] where the start index - # should be treated like 0 - if start > 0: - sp_index -= start - - # Length of our result should match applying this slice to a range - # of the length of our original array - new_len = len(range(len(self))[key]) - new_sp_index = make_sparse_index(new_len, sp_index, self.kind) - return type(self)._simple_new(sp_vals, new_sp_index, self.dtype) - else: - indices = np.arange(len(self), dtype=np.int32)[key] - return self.take(indices) - - elif not is_list_like(key): - # e.g. "foo" or 2.5 - # exception message copied from numpy - raise IndexError( - r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis " - r"(`None`) and integer or boolean arrays are valid indices" - ) - - else: - if isinstance(key, SparseArray): - # NOTE: If we guarantee that SparseDType(bool) - # has only fill_value - true, false or nan - # (see GH PR 44955) - # we can apply mask very fast: - if is_bool_dtype(key): - if isna(key.fill_value): - return self.take(key.sp_index.indices[key.sp_values]) - if not key.fill_value: - return self.take(key.sp_index.indices) - n = len(self) - mask = np.full(n, True, dtype=np.bool_) - mask[key.sp_index.indices] = False - return self.take(np.arange(n)[mask]) - else: - key = np.asarray(key) - - key = check_array_indexer(self, key) - - if com.is_bool_indexer(key): - # mypy doesn't know we have an array here - key = cast(np.ndarray, key) - return self.take(np.arange(len(key), dtype=np.int32)[key]) - elif hasattr(key, "__len__"): - return self.take(key) - else: - raise ValueError(f"Cannot slice with '{key}'") - - return type(self)(data_slice, kind=self.kind) - - def _get_val_at(self, loc): - loc = validate_insert_loc(loc, len(self)) - - sp_loc = self.sp_index.lookup(loc) - if sp_loc == -1: - return self.fill_value - else: - val = self.sp_values[sp_loc] - val = maybe_box_datetimelike(val, self.sp_values.dtype) - return val - - def take(self, indices, *, allow_fill: bool = False, fill_value=None) -> Self: - if is_scalar(indices): - raise ValueError(f"'indices' must be an array, not a scalar '{indices}'.") - indices = np.asarray(indices, dtype=np.int32) - - dtype = None - if indices.size == 0: - result = np.array([], dtype="object") - dtype = self.dtype - elif allow_fill: - result = self._take_with_fill(indices, fill_value=fill_value) - else: - return self._take_without_fill(indices) - - return type(self)( - result, fill_value=self.fill_value, kind=self.kind, dtype=dtype - ) - - def _take_with_fill(self, indices, fill_value=None) -> np.ndarray: - if fill_value is None: - fill_value = self.dtype.na_value - - if indices.min() < -1: - raise ValueError( - "Invalid value in 'indices'. Must be between -1 " - "and the length of the array." - ) - - if indices.max() >= len(self): - raise IndexError("out of bounds value in 'indices'.") - - if len(self) == 0: - # Empty... Allow taking only if all empty - if (indices == -1).all(): - dtype = np.result_type(self.sp_values, type(fill_value)) - taken = np.empty_like(indices, dtype=dtype) - taken.fill(fill_value) - return taken - else: - raise IndexError("cannot do a non-empty take from an empty axes.") - - # sp_indexer may be -1 for two reasons - # 1.) we took for an index of -1 (new) - # 2.) we took a value that was self.fill_value (old) - sp_indexer = self.sp_index.lookup_array(indices) - new_fill_indices = indices == -1 - old_fill_indices = (sp_indexer == -1) & ~new_fill_indices - - if self.sp_index.npoints == 0 and old_fill_indices.all(): - # We've looked up all valid points on an all-sparse array. - taken = np.full( - sp_indexer.shape, fill_value=self.fill_value, dtype=self.dtype.subtype - ) - - elif self.sp_index.npoints == 0: - # Avoid taking from the empty self.sp_values - _dtype = np.result_type(self.dtype.subtype, type(fill_value)) - taken = np.full(sp_indexer.shape, fill_value=fill_value, dtype=_dtype) - else: - taken = self.sp_values.take(sp_indexer) - - # Fill in two steps. - # Old fill values - # New fill values - # potentially coercing to a new dtype at each stage. - - m0 = sp_indexer[old_fill_indices] < 0 - m1 = sp_indexer[new_fill_indices] < 0 - - result_type = taken.dtype - - if m0.any(): - result_type = np.result_type(result_type, type(self.fill_value)) - taken = taken.astype(result_type) - taken[old_fill_indices] = self.fill_value - - if m1.any(): - result_type = np.result_type(result_type, type(fill_value)) - taken = taken.astype(result_type) - taken[new_fill_indices] = fill_value - - return taken - - def _take_without_fill(self, indices) -> Self: - to_shift = indices < 0 - - n = len(self) - - if (indices.max() >= n) or (indices.min() < -n): - if n == 0: - raise IndexError("cannot do a non-empty take from an empty axes.") - raise IndexError("out of bounds value in 'indices'.") - - if to_shift.any(): - indices = indices.copy() - indices[to_shift] += n - - sp_indexer = self.sp_index.lookup_array(indices) - value_mask = sp_indexer != -1 - new_sp_values = self.sp_values[sp_indexer[value_mask]] - - value_indices = np.flatnonzero(value_mask).astype(np.int32, copy=False) - - new_sp_index = make_sparse_index(len(indices), value_indices, kind=self.kind) - return type(self)._simple_new(new_sp_values, new_sp_index, dtype=self.dtype) - - def searchsorted( - self, - v: ArrayLike | object, - side: Literal["left", "right"] = "left", - sorter: NumpySorter | None = None, - ) -> npt.NDArray[np.intp] | np.intp: - msg = "searchsorted requires high memory usage." - warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level()) - v = np.asarray(v) - return np.asarray(self, dtype=self.dtype.subtype).searchsorted(v, side, sorter) - - def copy(self) -> Self: - values = self.sp_values.copy() - return self._simple_new(values, self.sp_index, self.dtype) - - @classmethod - def _concat_same_type(cls, to_concat: Sequence[Self]) -> Self: - fill_value = to_concat[0].fill_value - - values = [] - length = 0 - - if to_concat: - sp_kind = to_concat[0].kind - else: - sp_kind = "integer" - - sp_index: SparseIndex - if sp_kind == "integer": - indices = [] - - for arr in to_concat: - int_idx = arr.sp_index.indices.copy() - int_idx += length # TODO: wraparound - length += arr.sp_index.length - - values.append(arr.sp_values) - indices.append(int_idx) - - data = np.concatenate(values) - indices_arr = np.concatenate(indices) - # error: Argument 2 to "IntIndex" has incompatible type - # "ndarray[Any, dtype[signedinteger[_32Bit]]]"; - # expected "Sequence[int]" - sp_index = IntIndex(length, indices_arr) # type: ignore[arg-type] - - else: - # when concatenating block indices, we don't claim that you'll - # get an identical index as concatenating the values and then - # creating a new index. We don't want to spend the time trying - # to merge blocks across arrays in `to_concat`, so the resulting - # BlockIndex may have more blocks. - blengths = [] - blocs = [] - - for arr in to_concat: - block_idx = arr.sp_index.to_block_index() - - values.append(arr.sp_values) - blocs.append(block_idx.blocs.copy() + length) - blengths.append(block_idx.blengths) - length += arr.sp_index.length - - data = np.concatenate(values) - blocs_arr = np.concatenate(blocs) - blengths_arr = np.concatenate(blengths) - - sp_index = BlockIndex(length, blocs_arr, blengths_arr) - - return cls(data, sparse_index=sp_index, fill_value=fill_value) - - def astype(self, dtype: AstypeArg | None = None, copy: bool = True): - """ - Change the dtype of a SparseArray. - - The output will always be a SparseArray. To convert to a dense - ndarray with a certain dtype, use :meth:`numpy.asarray`. - - Parameters - ---------- - dtype : np.dtype or ExtensionDtype - For SparseDtype, this changes the dtype of - ``self.sp_values`` and the ``self.fill_value``. - - For other dtypes, this only changes the dtype of - ``self.sp_values``. - - copy : bool, default True - Whether to ensure a copy is made, even if not necessary. - - Returns - ------- - SparseArray - - Examples - -------- - >>> arr = pd.arrays.SparseArray([0, 0, 1, 2]) - >>> arr - [0, 0, 1, 2] - Fill: 0 - IntIndex - Indices: array([2, 3], dtype=int32) - - >>> arr.astype(SparseDtype(np.dtype('int32'))) - [0, 0, 1, 2] - Fill: 0 - IntIndex - Indices: array([2, 3], dtype=int32) - - Using a NumPy dtype with a different kind (e.g. float) will coerce - just ``self.sp_values``. - - >>> arr.astype(SparseDtype(np.dtype('float64'))) - ... # doctest: +NORMALIZE_WHITESPACE - [nan, nan, 1.0, 2.0] - Fill: nan - IntIndex - Indices: array([2, 3], dtype=int32) - - Using a SparseDtype, you can also change the fill value as well. - - >>> arr.astype(SparseDtype("float64", fill_value=0.0)) - ... # doctest: +NORMALIZE_WHITESPACE - [0.0, 0.0, 1.0, 2.0] - Fill: 0.0 - IntIndex - Indices: array([2, 3], dtype=int32) - """ - if dtype == self._dtype: - if not copy: - return self - else: - return self.copy() - - future_dtype = pandas_dtype(dtype) - if not isinstance(future_dtype, SparseDtype): - # GH#34457 - values = np.asarray(self) - values = ensure_wrapped_if_datetimelike(values) - return astype_array(values, dtype=future_dtype, copy=False) - - dtype = self.dtype.update_dtype(dtype) - subtype = pandas_dtype(dtype._subtype_with_str) - subtype = cast(np.dtype, subtype) # ensured by update_dtype - values = ensure_wrapped_if_datetimelike(self.sp_values) - sp_values = astype_array(values, subtype, copy=copy) - sp_values = np.asarray(sp_values) - - return self._simple_new(sp_values, self.sp_index, dtype) - - def map(self, mapper, na_action=None) -> Self: - """ - Map categories using an input mapping or function. - - Parameters - ---------- - mapper : dict, Series, callable - The correspondence from old values to new. - na_action : {None, 'ignore'}, default None - If 'ignore', propagate NA values, without passing them to the - mapping correspondence. - - Returns - ------- - SparseArray - The output array will have the same density as the input. - The output fill value will be the result of applying the - mapping to ``self.fill_value`` - - Examples - -------- - >>> arr = pd.arrays.SparseArray([0, 1, 2]) - >>> arr.map(lambda x: x + 10) - [10, 11, 12] - Fill: 10 - IntIndex - Indices: array([1, 2], dtype=int32) - - >>> arr.map({0: 10, 1: 11, 2: 12}) - [10, 11, 12] - Fill: 10 - IntIndex - Indices: array([1, 2], dtype=int32) - - >>> arr.map(pd.Series([10, 11, 12], index=[0, 1, 2])) - [10, 11, 12] - Fill: 10 - IntIndex - Indices: array([1, 2], dtype=int32) - """ - is_map = isinstance(mapper, (abc.Mapping, ABCSeries)) - - fill_val = self.fill_value - - if na_action is None or notna(fill_val): - fill_val = mapper.get(fill_val, fill_val) if is_map else mapper(fill_val) - - def func(sp_val): - new_sp_val = mapper.get(sp_val, None) if is_map else mapper(sp_val) - # check identity and equality because nans are not equal to each other - if new_sp_val is fill_val or new_sp_val == fill_val: - msg = "fill value in the sparse values not supported" - raise ValueError(msg) - return new_sp_val - - sp_values = [func(x) for x in self.sp_values] - - return type(self)(sp_values, sparse_index=self.sp_index, fill_value=fill_val) - - def to_dense(self) -> np.ndarray: - """ - Convert SparseArray to a NumPy array. - - Returns - ------- - arr : NumPy array - """ - return np.asarray(self, dtype=self.sp_values.dtype) - - def _where(self, mask, value): - # NB: may not preserve dtype, e.g. result may be Sparse[float64] - # while self is Sparse[int64] - naive_implementation = np.where(mask, self, value) - dtype = SparseDtype(naive_implementation.dtype, fill_value=self.fill_value) - result = type(self)._from_sequence(naive_implementation, dtype=dtype) - return result - - # ------------------------------------------------------------------------ - # IO - # ------------------------------------------------------------------------ - def __setstate__(self, state) -> None: - """Necessary for making this object picklable""" - if isinstance(state, tuple): - # Compat for pandas < 0.24.0 - nd_state, (fill_value, sp_index) = state - sparse_values = np.array([]) - sparse_values.__setstate__(nd_state) - - self._sparse_values = sparse_values - self._sparse_index = sp_index - self._dtype = SparseDtype(sparse_values.dtype, fill_value) - else: - self.__dict__.update(state) - - def nonzero(self) -> tuple[npt.NDArray[np.int32]]: - if self.fill_value == 0: - return (self.sp_index.indices,) - else: - return (self.sp_index.indices[self.sp_values != 0],) - - # ------------------------------------------------------------------------ - # Reductions - # ------------------------------------------------------------------------ - - def _reduce( - self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs - ): - method = getattr(self, name, None) - - if method is None: - raise TypeError(f"cannot perform {name} with type {self.dtype}") - - if skipna: - arr = self - else: - arr = self.dropna() - - result = getattr(arr, name)(**kwargs) - - if keepdims: - return type(self)([result], dtype=self.dtype) - else: - return result - - def all(self, axis=None, *args, **kwargs): - """ - Tests whether all elements evaluate True - - Returns - ------- - all : bool - - See Also - -------- - numpy.all - """ - nv.validate_all(args, kwargs) - - values = self.sp_values - - if len(values) != len(self) and not np.all(self.fill_value): - return False - - return values.all() - - def any(self, axis: AxisInt = 0, *args, **kwargs): - """ - Tests whether at least one of elements evaluate True - - Returns - ------- - any : bool - - See Also - -------- - numpy.any - """ - nv.validate_any(args, kwargs) - - values = self.sp_values - - if len(values) != len(self) and np.any(self.fill_value): - return True - - return values.any().item() - - def sum( - self, - axis: AxisInt = 0, - min_count: int = 0, - skipna: bool = True, - *args, - **kwargs, - ) -> Scalar: - """ - Sum of non-NA/null values - - Parameters - ---------- - axis : int, default 0 - Not Used. NumPy compatibility. - min_count : int, default 0 - The required number of valid values to perform the summation. If fewer - than ``min_count`` valid values are present, the result will be the missing - value indicator for subarray type. - *args, **kwargs - Not Used. NumPy compatibility. - - Returns - ------- - scalar - """ - nv.validate_sum(args, kwargs) - valid_vals = self._valid_sp_values - sp_sum = valid_vals.sum() - has_na = self.sp_index.ngaps > 0 and not self._null_fill_value - - if has_na and not skipna: - return na_value_for_dtype(self.dtype.subtype, compat=False) - - if self._null_fill_value: - if check_below_min_count(valid_vals.shape, None, min_count): - return na_value_for_dtype(self.dtype.subtype, compat=False) - return sp_sum - else: - nsparse = self.sp_index.ngaps - if check_below_min_count(valid_vals.shape, None, min_count - nsparse): - return na_value_for_dtype(self.dtype.subtype, compat=False) - return sp_sum + self.fill_value * nsparse - - def cumsum(self, axis: AxisInt = 0, *args, **kwargs) -> SparseArray: - """ - Cumulative sum of non-NA/null values. - - When performing the cumulative summation, any non-NA/null values will - be skipped. The resulting SparseArray will preserve the locations of - NaN values, but the fill value will be `np.nan` regardless. - - Parameters - ---------- - axis : int or None - Axis over which to perform the cumulative summation. If None, - perform cumulative summation over flattened array. - - Returns - ------- - cumsum : SparseArray - """ - nv.validate_cumsum(args, kwargs) - - if axis is not None and axis >= self.ndim: # Mimic ndarray behaviour. - raise ValueError(f"axis(={axis}) out of bounds") - - if not self._null_fill_value: - return SparseArray(self.to_dense()).cumsum() - - return SparseArray( - self.sp_values.cumsum(), - sparse_index=self.sp_index, - fill_value=self.fill_value, - ) - - def mean(self, axis: Axis = 0, *args, **kwargs): - """ - Mean of non-NA/null values - - Returns - ------- - mean : float - """ - nv.validate_mean(args, kwargs) - valid_vals = self._valid_sp_values - sp_sum = valid_vals.sum() - ct = len(valid_vals) - - if self._null_fill_value: - return sp_sum / ct - else: - nsparse = self.sp_index.ngaps - return (sp_sum + self.fill_value * nsparse) / (ct + nsparse) - - def max(self, *, axis: AxisInt | None = None, skipna: bool = True): - """ - Max of array values, ignoring NA values if specified. - - Parameters - ---------- - axis : int, default 0 - Not Used. NumPy compatibility. - skipna : bool, default True - Whether to ignore NA values. - - Returns - ------- - scalar - """ - nv.validate_minmax_axis(axis, self.ndim) - return self._min_max("max", skipna=skipna) - - def min(self, *, axis: AxisInt | None = None, skipna: bool = True): - """ - Min of array values, ignoring NA values if specified. - - Parameters - ---------- - axis : int, default 0 - Not Used. NumPy compatibility. - skipna : bool, default True - Whether to ignore NA values. - - Returns - ------- - scalar - """ - nv.validate_minmax_axis(axis, self.ndim) - return self._min_max("min", skipna=skipna) - - def _min_max(self, kind: Literal["min", "max"], skipna: bool) -> Scalar: - """ - Min/max of non-NA/null values - - Parameters - ---------- - kind : {"min", "max"} - skipna : bool - - Returns - ------- - scalar - """ - valid_vals = self._valid_sp_values - has_nonnull_fill_vals = not self._null_fill_value and self.sp_index.ngaps > 0 - - if len(valid_vals) > 0: - sp_min_max = getattr(valid_vals, kind)() - - # If a non-null fill value is currently present, it might be the min/max - if has_nonnull_fill_vals: - func = max if kind == "max" else min - return func(sp_min_max, self.fill_value) - elif skipna: - return sp_min_max - elif self.sp_index.ngaps == 0: - # No NAs present - return sp_min_max - else: - return na_value_for_dtype(self.dtype.subtype, compat=False) - elif has_nonnull_fill_vals: - return self.fill_value - else: - return na_value_for_dtype(self.dtype.subtype, compat=False) - - def _argmin_argmax(self, kind: Literal["argmin", "argmax"]) -> int: - values = self._sparse_values - index = self._sparse_index.indices - mask = np.asarray(isna(values)) - func = np.argmax if kind == "argmax" else np.argmin - - idx = np.arange(values.shape[0]) - non_nans = values[~mask] - non_nan_idx = idx[~mask] - - _candidate = non_nan_idx[func(non_nans)] - candidate = index[_candidate] - - if isna(self.fill_value): - return candidate - if kind == "argmin" and self[candidate] < self.fill_value: - return candidate - if kind == "argmax" and self[candidate] > self.fill_value: - return candidate - _loc = self._first_fill_value_loc() - if _loc == -1: - # fill_value doesn't exist - return candidate - else: - return _loc - - def argmax(self, skipna: bool = True) -> int: - validate_bool_kwarg(skipna, "skipna") - if not skipna and self._hasna: - raise NotImplementedError - return self._argmin_argmax("argmax") - - def argmin(self, skipna: bool = True) -> int: - validate_bool_kwarg(skipna, "skipna") - if not skipna and self._hasna: - raise NotImplementedError - return self._argmin_argmax("argmin") - - # ------------------------------------------------------------------------ - # Ufuncs - # ------------------------------------------------------------------------ - - _HANDLED_TYPES = (np.ndarray, numbers.Number) - - def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs): - out = kwargs.get("out", ()) - - for x in inputs + out: - if not isinstance(x, self._HANDLED_TYPES + (SparseArray,)): - return NotImplemented - - # for binary ops, use our custom dunder methods - result = arraylike.maybe_dispatch_ufunc_to_dunder_op( - self, ufunc, method, *inputs, **kwargs - ) - if result is not NotImplemented: - return result - - if "out" in kwargs: - # e.g. tests.arrays.sparse.test_arithmetics.test_ndarray_inplace - res = arraylike.dispatch_ufunc_with_out( - self, ufunc, method, *inputs, **kwargs - ) - return res - - if method == "reduce": - result = arraylike.dispatch_reduction_ufunc( - self, ufunc, method, *inputs, **kwargs - ) - if result is not NotImplemented: - # e.g. tests.series.test_ufunc.TestNumpyReductions - return result - - if len(inputs) == 1: - # No alignment necessary. - sp_values = getattr(ufunc, method)(self.sp_values, **kwargs) - fill_value = getattr(ufunc, method)(self.fill_value, **kwargs) - - if ufunc.nout > 1: - # multiple outputs. e.g. modf - arrays = tuple( - self._simple_new( - sp_value, self.sp_index, SparseDtype(sp_value.dtype, fv) - ) - for sp_value, fv in zip(sp_values, fill_value) - ) - return arrays - elif method == "reduce": - # e.g. reductions - return sp_values - - return self._simple_new( - sp_values, self.sp_index, SparseDtype(sp_values.dtype, fill_value) - ) - - new_inputs = tuple(np.asarray(x) for x in inputs) - result = getattr(ufunc, method)(*new_inputs, **kwargs) - if out: - if len(out) == 1: - out = out[0] - return out - - if ufunc.nout > 1: - return tuple(type(self)(x) for x in result) - elif method == "at": - # no return value - return None - else: - return type(self)(result) - - # ------------------------------------------------------------------------ - # Ops - # ------------------------------------------------------------------------ - - def _arith_method(self, other, op): - op_name = op.__name__ - - if isinstance(other, SparseArray): - return _sparse_array_op(self, other, op, op_name) - - elif is_scalar(other): - with np.errstate(all="ignore"): - fill = op(_get_fill(self), np.asarray(other)) - result = op(self.sp_values, other) - - if op_name == "divmod": - left, right = result - lfill, rfill = fill - return ( - _wrap_result(op_name, left, self.sp_index, lfill), - _wrap_result(op_name, right, self.sp_index, rfill), - ) - - return _wrap_result(op_name, result, self.sp_index, fill) - - else: - other = np.asarray(other) - with np.errstate(all="ignore"): - if len(self) != len(other): - raise AssertionError( - f"length mismatch: {len(self)} vs. {len(other)}" - ) - if not isinstance(other, SparseArray): - dtype = getattr(other, "dtype", None) - other = SparseArray(other, fill_value=self.fill_value, dtype=dtype) - return _sparse_array_op(self, other, op, op_name) - - def _cmp_method(self, other, op) -> SparseArray: - if not is_scalar(other) and not isinstance(other, type(self)): - # convert list-like to ndarray - other = np.asarray(other) - - if isinstance(other, np.ndarray): - # TODO: make this more flexible than just ndarray... - other = SparseArray(other, fill_value=self.fill_value) - - if isinstance(other, SparseArray): - if len(self) != len(other): - raise ValueError( - f"operands have mismatched length {len(self)} and {len(other)}" - ) - - op_name = op.__name__.strip("_") - return _sparse_array_op(self, other, op, op_name) - else: - # scalar - fill_value = op(self.fill_value, other) - result = np.full(len(self), fill_value, dtype=np.bool_) - result[self.sp_index.indices] = op(self.sp_values, other) - - return type(self)( - result, - fill_value=fill_value, - dtype=np.bool_, - ) - - _logical_method = _cmp_method - - def _unary_method(self, op) -> SparseArray: - fill_value = op(np.array(self.fill_value)).item() - dtype = SparseDtype(self.dtype.subtype, fill_value) - # NOTE: if fill_value doesn't change - # we just have to apply op to sp_values - if isna(self.fill_value) or fill_value == self.fill_value: - values = op(self.sp_values) - return type(self)._simple_new(values, self.sp_index, self.dtype) - # In the other case we have to recalc indexes - return type(self)(op(self.to_dense()), dtype=dtype) - - def __pos__(self) -> SparseArray: - return self._unary_method(operator.pos) - - def __neg__(self) -> SparseArray: - return self._unary_method(operator.neg) - - def __invert__(self) -> SparseArray: - return self._unary_method(operator.invert) - - def __abs__(self) -> SparseArray: - return self._unary_method(operator.abs) - - # ---------- - # Formatting - # ----------- - def __repr__(self) -> str: - pp_str = printing.pprint_thing(self) - pp_fill = printing.pprint_thing(self.fill_value) - pp_index = printing.pprint_thing(self.sp_index) - return f"{pp_str}\nFill: {pp_fill}\n{pp_index}" - - def _formatter(self, boxed: bool = False): - # Defer to the formatter from the GenericArrayFormatter calling us. - # This will infer the correct formatter from the dtype of the values. - return None - - -def _make_sparse( - arr: np.ndarray, - kind: SparseIndexKind = "block", - fill_value=None, - dtype: np.dtype | None = None, -): - """ - Convert ndarray to sparse format - - Parameters - ---------- - arr : ndarray - kind : {'block', 'integer'} - fill_value : NaN or another value - dtype : np.dtype, optional - copy : bool, default False - - Returns - ------- - (sparse_values, index, fill_value) : (ndarray, SparseIndex, Scalar) - """ - assert isinstance(arr, np.ndarray) - - if arr.ndim > 1: - raise TypeError("expected dimension <= 1 data") - - if fill_value is None: - fill_value = na_value_for_dtype(arr.dtype) - - if isna(fill_value): - mask = notna(arr) - else: - # cast to object comparison to be safe - if is_string_dtype(arr.dtype): - arr = arr.astype(object) - - if is_object_dtype(arr.dtype): - # element-wise equality check method in numpy doesn't treat - # each element type, eg. 0, 0.0, and False are treated as - # same. So we have to check the both of its type and value. - mask = splib.make_mask_object_ndarray(arr, fill_value) - else: - mask = arr != fill_value - - length = len(arr) - if length != len(mask): - # the arr is a SparseArray - indices = mask.sp_index.indices - else: - indices = mask.nonzero()[0].astype(np.int32) - - index = make_sparse_index(length, indices, kind) - sparsified_values = arr[mask] - if dtype is not None: - sparsified_values = ensure_wrapped_if_datetimelike(sparsified_values) - sparsified_values = astype_array(sparsified_values, dtype=dtype) - sparsified_values = np.asarray(sparsified_values) - - # TODO: copy - return sparsified_values, index, fill_value - - -@overload -def make_sparse_index(length: int, indices, kind: Literal["block"]) -> BlockIndex: - ... - - -@overload -def make_sparse_index(length: int, indices, kind: Literal["integer"]) -> IntIndex: - ... - - -def make_sparse_index(length: int, indices, kind: SparseIndexKind) -> SparseIndex: - index: SparseIndex - if kind == "block": - locs, lens = splib.get_blocks(indices) - index = BlockIndex(length, locs, lens) - elif kind == "integer": - index = IntIndex(length, indices) - else: # pragma: no cover - raise ValueError("must be block or integer type") - return index diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_count.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_count.py deleted file mode 100644 index 1553a8a86305dd931c5378245daf272472d41b20..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_count.py +++ /dev/null @@ -1,39 +0,0 @@ -from pandas import ( - DataFrame, - Series, -) -import pandas._testing as tm - - -class TestDataFrameCount: - def test_count(self): - # corner case - frame = DataFrame() - ct1 = frame.count(1) - assert isinstance(ct1, Series) - - ct2 = frame.count(0) - assert isinstance(ct2, Series) - - # GH#423 - df = DataFrame(index=range(10)) - result = df.count(1) - expected = Series(0, index=df.index) - tm.assert_series_equal(result, expected) - - df = DataFrame(columns=range(10)) - result = df.count(0) - expected = Series(0, index=df.columns) - tm.assert_series_equal(result, expected) - - df = DataFrame() - result = df.count() - expected = Series(dtype="int64") - tm.assert_series_equal(result, expected) - - def test_count_objects(self, float_string_frame): - dm = DataFrame(float_string_frame._series) - df = DataFrame(float_string_frame._series) - - tm.assert_series_equal(dm.count(), df.count()) - tm.assert_series_equal(dm.count(1), df.count(1)) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/test_nanops.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/test_nanops.py deleted file mode 100644 index a0062d2b6dd4447a59445af8424782351ee73cbd..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/test_nanops.py +++ /dev/null @@ -1,1275 +0,0 @@ -from functools import partial - -import numpy as np -import pytest - -import pandas.util._test_decorators as td - -from pandas.core.dtypes.common import is_integer_dtype - -import pandas as pd -from pandas import ( - Series, - isna, -) -import pandas._testing as tm -from pandas.core import nanops -from pandas.core.arrays import DatetimeArray - -use_bn = nanops._USE_BOTTLENECK - - -@pytest.fixture -def disable_bottleneck(monkeypatch): - with monkeypatch.context() as m: - m.setattr(nanops, "_USE_BOTTLENECK", False) - yield - - -@pytest.fixture -def arr_shape(): - return 11, 7 - - -@pytest.fixture -def arr_float(arr_shape): - return np.random.default_rng(2).standard_normal(arr_shape) - - -@pytest.fixture -def arr_complex(arr_float): - return arr_float + arr_float * 1j - - -@pytest.fixture -def arr_int(arr_shape): - return np.random.default_rng(2).integers(-10, 10, arr_shape) - - -@pytest.fixture -def arr_bool(arr_shape): - return np.random.default_rng(2).integers(0, 2, arr_shape) == 0 - - -@pytest.fixture -def arr_str(arr_float): - return np.abs(arr_float).astype("S") - - -@pytest.fixture -def arr_utf(arr_float): - return np.abs(arr_float).astype("U") - - -@pytest.fixture -def arr_date(arr_shape): - return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]") - - -@pytest.fixture -def arr_tdelta(arr_shape): - return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]") - - -@pytest.fixture -def arr_nan(arr_shape): - return np.tile(np.nan, arr_shape) - - -@pytest.fixture -def arr_float_nan(arr_float, arr_nan): - return np.vstack([arr_float, arr_nan]) - - -@pytest.fixture -def arr_nan_float1(arr_nan, arr_float): - return np.vstack([arr_nan, arr_float]) - - -@pytest.fixture -def arr_nan_nan(arr_nan): - return np.vstack([arr_nan, arr_nan]) - - -@pytest.fixture -def arr_inf(arr_float): - return arr_float * np.inf - - -@pytest.fixture -def arr_float_inf(arr_float, arr_inf): - return np.vstack([arr_float, arr_inf]) - - -@pytest.fixture -def arr_nan_inf(arr_nan, arr_inf): - return np.vstack([arr_nan, arr_inf]) - - -@pytest.fixture -def arr_float_nan_inf(arr_float, arr_nan, arr_inf): - return np.vstack([arr_float, arr_nan, arr_inf]) - - -@pytest.fixture -def arr_nan_nan_inf(arr_nan, arr_inf): - return np.vstack([arr_nan, arr_nan, arr_inf]) - - -@pytest.fixture -def arr_obj( - arr_float, arr_int, arr_bool, arr_complex, arr_str, arr_utf, arr_date, arr_tdelta -): - return np.vstack( - [ - arr_float.astype("O"), - arr_int.astype("O"), - arr_bool.astype("O"), - arr_complex.astype("O"), - arr_str.astype("O"), - arr_utf.astype("O"), - arr_date.astype("O"), - arr_tdelta.astype("O"), - ] - ) - - -@pytest.fixture -def arr_nan_nanj(arr_nan): - with np.errstate(invalid="ignore"): - return arr_nan + arr_nan * 1j - - -@pytest.fixture -def arr_complex_nan(arr_complex, arr_nan_nanj): - with np.errstate(invalid="ignore"): - return np.vstack([arr_complex, arr_nan_nanj]) - - -@pytest.fixture -def arr_nan_infj(arr_inf): - with np.errstate(invalid="ignore"): - return arr_inf * 1j - - -@pytest.fixture -def arr_complex_nan_infj(arr_complex, arr_nan_infj): - with np.errstate(invalid="ignore"): - return np.vstack([arr_complex, arr_nan_infj]) - - -@pytest.fixture -def arr_float_1d(arr_float): - return arr_float[:, 0] - - -@pytest.fixture -def arr_nan_1d(arr_nan): - return arr_nan[:, 0] - - -@pytest.fixture -def arr_float_nan_1d(arr_float_nan): - return arr_float_nan[:, 0] - - -@pytest.fixture -def arr_float1_nan_1d(arr_float1_nan): - return arr_float1_nan[:, 0] - - -@pytest.fixture -def arr_nan_float1_1d(arr_nan_float1): - return arr_nan_float1[:, 0] - - -class TestnanopsDataFrame: - def setup_method(self): - nanops._USE_BOTTLENECK = False - - arr_shape = (11, 7) - - self.arr_float = np.random.default_rng(2).standard_normal(arr_shape) - self.arr_float1 = np.random.default_rng(2).standard_normal(arr_shape) - self.arr_complex = self.arr_float + self.arr_float1 * 1j - self.arr_int = np.random.default_rng(2).integers(-10, 10, arr_shape) - self.arr_bool = np.random.default_rng(2).integers(0, 2, arr_shape) == 0 - self.arr_str = np.abs(self.arr_float).astype("S") - self.arr_utf = np.abs(self.arr_float).astype("U") - self.arr_date = ( - np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]") - ) - self.arr_tdelta = ( - np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]") - ) - - self.arr_nan = np.tile(np.nan, arr_shape) - self.arr_float_nan = np.vstack([self.arr_float, self.arr_nan]) - self.arr_float1_nan = np.vstack([self.arr_float1, self.arr_nan]) - self.arr_nan_float1 = np.vstack([self.arr_nan, self.arr_float1]) - self.arr_nan_nan = np.vstack([self.arr_nan, self.arr_nan]) - - self.arr_inf = self.arr_float * np.inf - self.arr_float_inf = np.vstack([self.arr_float, self.arr_inf]) - - self.arr_nan_inf = np.vstack([self.arr_nan, self.arr_inf]) - self.arr_float_nan_inf = np.vstack([self.arr_float, self.arr_nan, self.arr_inf]) - self.arr_nan_nan_inf = np.vstack([self.arr_nan, self.arr_nan, self.arr_inf]) - self.arr_obj = np.vstack( - [ - self.arr_float.astype("O"), - self.arr_int.astype("O"), - self.arr_bool.astype("O"), - self.arr_complex.astype("O"), - self.arr_str.astype("O"), - self.arr_utf.astype("O"), - self.arr_date.astype("O"), - self.arr_tdelta.astype("O"), - ] - ) - - with np.errstate(invalid="ignore"): - self.arr_nan_nanj = self.arr_nan + self.arr_nan * 1j - self.arr_complex_nan = np.vstack([self.arr_complex, self.arr_nan_nanj]) - - self.arr_nan_infj = self.arr_inf * 1j - self.arr_complex_nan_infj = np.vstack([self.arr_complex, self.arr_nan_infj]) - - self.arr_float_2d = self.arr_float - self.arr_float1_2d = self.arr_float1 - - self.arr_nan_2d = self.arr_nan - self.arr_float_nan_2d = self.arr_float_nan - self.arr_float1_nan_2d = self.arr_float1_nan - self.arr_nan_float1_2d = self.arr_nan_float1 - - self.arr_float_1d = self.arr_float[:, 0] - self.arr_float1_1d = self.arr_float1[:, 0] - - self.arr_nan_1d = self.arr_nan[:, 0] - self.arr_float_nan_1d = self.arr_float_nan[:, 0] - self.arr_float1_nan_1d = self.arr_float1_nan[:, 0] - self.arr_nan_float1_1d = self.arr_nan_float1[:, 0] - - def teardown_method(self): - nanops._USE_BOTTLENECK = use_bn - - def check_results(self, targ, res, axis, check_dtype=True): - res = getattr(res, "asm8", res) - - if ( - axis != 0 - and hasattr(targ, "shape") - and targ.ndim - and targ.shape != res.shape - ): - res = np.split(res, [targ.shape[0]], axis=0)[0] - - try: - tm.assert_almost_equal(targ, res, check_dtype=check_dtype) - except AssertionError: - # handle timedelta dtypes - if hasattr(targ, "dtype") and targ.dtype == "m8[ns]": - raise - - # There are sometimes rounding errors with - # complex and object dtypes. - # If it isn't one of those, re-raise the error. - if not hasattr(res, "dtype") or res.dtype.kind not in ["c", "O"]: - raise - # convert object dtypes to something that can be split into - # real and imaginary parts - if res.dtype.kind == "O": - if targ.dtype.kind != "O": - res = res.astype(targ.dtype) - else: - cast_dtype = "c16" if hasattr(np, "complex128") else "f8" - res = res.astype(cast_dtype) - targ = targ.astype(cast_dtype) - # there should never be a case where numpy returns an object - # but nanops doesn't, so make that an exception - elif targ.dtype.kind == "O": - raise - tm.assert_almost_equal(np.real(targ), np.real(res), check_dtype=check_dtype) - tm.assert_almost_equal(np.imag(targ), np.imag(res), check_dtype=check_dtype) - - def check_fun_data( - self, - testfunc, - targfunc, - testarval, - targarval, - skipna, - check_dtype=True, - empty_targfunc=None, - **kwargs, - ): - for axis in list(range(targarval.ndim)) + [None]: - targartempval = targarval if skipna else testarval - if skipna and empty_targfunc and isna(targartempval).all(): - targ = empty_targfunc(targartempval, axis=axis, **kwargs) - else: - targ = targfunc(targartempval, axis=axis, **kwargs) - - if targartempval.dtype == object and ( - targfunc is np.any or targfunc is np.all - ): - # GH#12863 the numpy functions will retain e.g. floatiness - if isinstance(targ, np.ndarray): - targ = targ.astype(bool) - else: - targ = bool(targ) - - res = testfunc(testarval, axis=axis, skipna=skipna, **kwargs) - - if ( - isinstance(targ, np.complex128) - and isinstance(res, float) - and np.isnan(targ) - and np.isnan(res) - ): - # GH#18463 - targ = res - - self.check_results(targ, res, axis, check_dtype=check_dtype) - if skipna: - res = testfunc(testarval, axis=axis, **kwargs) - self.check_results(targ, res, axis, check_dtype=check_dtype) - if axis is None: - res = testfunc(testarval, skipna=skipna, **kwargs) - self.check_results(targ, res, axis, check_dtype=check_dtype) - if skipna and axis is None: - res = testfunc(testarval, **kwargs) - self.check_results(targ, res, axis, check_dtype=check_dtype) - - if testarval.ndim <= 1: - return - - # Recurse on lower-dimension - testarval2 = np.take(testarval, 0, axis=-1) - targarval2 = np.take(targarval, 0, axis=-1) - self.check_fun_data( - testfunc, - targfunc, - testarval2, - targarval2, - skipna=skipna, - check_dtype=check_dtype, - empty_targfunc=empty_targfunc, - **kwargs, - ) - - def check_fun( - self, testfunc, targfunc, testar, skipna, empty_targfunc=None, **kwargs - ): - targar = testar - if testar.endswith("_nan") and hasattr(self, testar[:-4]): - targar = testar[:-4] - - testarval = getattr(self, testar) - targarval = getattr(self, targar) - self.check_fun_data( - testfunc, - targfunc, - testarval, - targarval, - skipna=skipna, - empty_targfunc=empty_targfunc, - **kwargs, - ) - - def check_funs( - self, - testfunc, - targfunc, - skipna, - allow_complex=True, - allow_all_nan=True, - allow_date=True, - allow_tdelta=True, - allow_obj=True, - **kwargs, - ): - self.check_fun(testfunc, targfunc, "arr_float", skipna, **kwargs) - self.check_fun(testfunc, targfunc, "arr_float_nan", skipna, **kwargs) - self.check_fun(testfunc, targfunc, "arr_int", skipna, **kwargs) - self.check_fun(testfunc, targfunc, "arr_bool", skipna, **kwargs) - objs = [ - self.arr_float.astype("O"), - self.arr_int.astype("O"), - self.arr_bool.astype("O"), - ] - - if allow_all_nan: - self.check_fun(testfunc, targfunc, "arr_nan", skipna, **kwargs) - - if allow_complex: - self.check_fun(testfunc, targfunc, "arr_complex", skipna, **kwargs) - self.check_fun(testfunc, targfunc, "arr_complex_nan", skipna, **kwargs) - if allow_all_nan: - self.check_fun(testfunc, targfunc, "arr_nan_nanj", skipna, **kwargs) - objs += [self.arr_complex.astype("O")] - - if allow_date: - targfunc(self.arr_date) - self.check_fun(testfunc, targfunc, "arr_date", skipna, **kwargs) - objs += [self.arr_date.astype("O")] - - if allow_tdelta: - try: - targfunc(self.arr_tdelta) - except TypeError: - pass - else: - self.check_fun(testfunc, targfunc, "arr_tdelta", skipna, **kwargs) - objs += [self.arr_tdelta.astype("O")] - - if allow_obj: - self.arr_obj = np.vstack(objs) - # some nanops handle object dtypes better than their numpy - # counterparts, so the numpy functions need to be given something - # else - if allow_obj == "convert": - targfunc = partial( - self._badobj_wrap, func=targfunc, allow_complex=allow_complex - ) - self.check_fun(testfunc, targfunc, "arr_obj", skipna, **kwargs) - - def _badobj_wrap(self, value, func, allow_complex=True, **kwargs): - if value.dtype.kind == "O": - if allow_complex: - value = value.astype("c16") - else: - value = value.astype("f8") - return func(value, **kwargs) - - @pytest.mark.parametrize( - "nan_op,np_op", [(nanops.nanany, np.any), (nanops.nanall, np.all)] - ) - def test_nan_funcs(self, nan_op, np_op, skipna): - self.check_funs(nan_op, np_op, skipna, allow_all_nan=False, allow_date=False) - - def test_nansum(self, skipna): - self.check_funs( - nanops.nansum, - np.sum, - skipna, - allow_date=False, - check_dtype=False, - empty_targfunc=np.nansum, - ) - - def test_nanmean(self, skipna): - self.check_funs( - nanops.nanmean, np.mean, skipna, allow_obj=False, allow_date=False - ) - - @pytest.mark.filterwarnings("ignore::RuntimeWarning") - def test_nanmedian(self, skipna): - self.check_funs( - nanops.nanmedian, - np.median, - skipna, - allow_complex=False, - allow_date=False, - allow_obj="convert", - ) - - @pytest.mark.parametrize("ddof", range(3)) - def test_nanvar(self, ddof, skipna): - self.check_funs( - nanops.nanvar, - np.var, - skipna, - allow_complex=False, - allow_date=False, - allow_obj="convert", - ddof=ddof, - ) - - @pytest.mark.parametrize("ddof", range(3)) - def test_nanstd(self, ddof, skipna): - self.check_funs( - nanops.nanstd, - np.std, - skipna, - allow_complex=False, - allow_date=False, - allow_obj="convert", - ddof=ddof, - ) - - @pytest.mark.parametrize("ddof", range(3)) - def test_nansem(self, ddof, skipna): - sp_stats = pytest.importorskip("scipy.stats") - - with np.errstate(invalid="ignore"): - self.check_funs( - nanops.nansem, - sp_stats.sem, - skipna, - allow_complex=False, - allow_date=False, - allow_tdelta=False, - allow_obj="convert", - ddof=ddof, - ) - - @pytest.mark.filterwarnings("ignore::RuntimeWarning") - @pytest.mark.parametrize( - "nan_op,np_op", [(nanops.nanmin, np.min), (nanops.nanmax, np.max)] - ) - def test_nanops_with_warnings(self, nan_op, np_op, skipna): - self.check_funs(nan_op, np_op, skipna, allow_obj=False) - - def _argminmax_wrap(self, value, axis=None, func=None): - res = func(value, axis) - nans = np.min(value, axis) - nullnan = isna(nans) - if res.ndim: - res[nullnan] = -1 - elif ( - hasattr(nullnan, "all") - and nullnan.all() - or not hasattr(nullnan, "all") - and nullnan - ): - res = -1 - return res - - @pytest.mark.filterwarnings("ignore::RuntimeWarning") - def test_nanargmax(self, skipna): - func = partial(self._argminmax_wrap, func=np.argmax) - self.check_funs(nanops.nanargmax, func, skipna, allow_obj=False) - - @pytest.mark.filterwarnings("ignore::RuntimeWarning") - def test_nanargmin(self, skipna): - func = partial(self._argminmax_wrap, func=np.argmin) - self.check_funs(nanops.nanargmin, func, skipna, allow_obj=False) - - def _skew_kurt_wrap(self, values, axis=None, func=None): - if not isinstance(values.dtype.type, np.floating): - values = values.astype("f8") - result = func(values, axis=axis, bias=False) - # fix for handling cases where all elements in an axis are the same - if isinstance(result, np.ndarray): - result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0 - return result - elif np.max(values) == np.min(values): - return 0.0 - return result - - def test_nanskew(self, skipna): - sp_stats = pytest.importorskip("scipy.stats") - - func = partial(self._skew_kurt_wrap, func=sp_stats.skew) - with np.errstate(invalid="ignore"): - self.check_funs( - nanops.nanskew, - func, - skipna, - allow_complex=False, - allow_date=False, - allow_tdelta=False, - ) - - def test_nankurt(self, skipna): - sp_stats = pytest.importorskip("scipy.stats") - - func1 = partial(sp_stats.kurtosis, fisher=True) - func = partial(self._skew_kurt_wrap, func=func1) - with np.errstate(invalid="ignore"): - self.check_funs( - nanops.nankurt, - func, - skipna, - allow_complex=False, - allow_date=False, - allow_tdelta=False, - ) - - def test_nanprod(self, skipna): - self.check_funs( - nanops.nanprod, - np.prod, - skipna, - allow_date=False, - allow_tdelta=False, - empty_targfunc=np.nanprod, - ) - - def check_nancorr_nancov_2d(self, checkfun, targ0, targ1, **kwargs): - res00 = checkfun(self.arr_float_2d, self.arr_float1_2d, **kwargs) - res01 = checkfun( - self.arr_float_2d, - self.arr_float1_2d, - min_periods=len(self.arr_float_2d) - 1, - **kwargs, - ) - tm.assert_almost_equal(targ0, res00) - tm.assert_almost_equal(targ0, res01) - - res10 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d, **kwargs) - res11 = checkfun( - self.arr_float_nan_2d, - self.arr_float1_nan_2d, - min_periods=len(self.arr_float_2d) - 1, - **kwargs, - ) - tm.assert_almost_equal(targ1, res10) - tm.assert_almost_equal(targ1, res11) - - targ2 = np.nan - res20 = checkfun(self.arr_nan_2d, self.arr_float1_2d, **kwargs) - res21 = checkfun(self.arr_float_2d, self.arr_nan_2d, **kwargs) - res22 = checkfun(self.arr_nan_2d, self.arr_nan_2d, **kwargs) - res23 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d, **kwargs) - res24 = checkfun( - self.arr_float_nan_2d, - self.arr_nan_float1_2d, - min_periods=len(self.arr_float_2d) - 1, - **kwargs, - ) - res25 = checkfun( - self.arr_float_2d, - self.arr_float1_2d, - min_periods=len(self.arr_float_2d) + 1, - **kwargs, - ) - tm.assert_almost_equal(targ2, res20) - tm.assert_almost_equal(targ2, res21) - tm.assert_almost_equal(targ2, res22) - tm.assert_almost_equal(targ2, res23) - tm.assert_almost_equal(targ2, res24) - tm.assert_almost_equal(targ2, res25) - - def check_nancorr_nancov_1d(self, checkfun, targ0, targ1, **kwargs): - res00 = checkfun(self.arr_float_1d, self.arr_float1_1d, **kwargs) - res01 = checkfun( - self.arr_float_1d, - self.arr_float1_1d, - min_periods=len(self.arr_float_1d) - 1, - **kwargs, - ) - tm.assert_almost_equal(targ0, res00) - tm.assert_almost_equal(targ0, res01) - - res10 = checkfun(self.arr_float_nan_1d, self.arr_float1_nan_1d, **kwargs) - res11 = checkfun( - self.arr_float_nan_1d, - self.arr_float1_nan_1d, - min_periods=len(self.arr_float_1d) - 1, - **kwargs, - ) - tm.assert_almost_equal(targ1, res10) - tm.assert_almost_equal(targ1, res11) - - targ2 = np.nan - res20 = checkfun(self.arr_nan_1d, self.arr_float1_1d, **kwargs) - res21 = checkfun(self.arr_float_1d, self.arr_nan_1d, **kwargs) - res22 = checkfun(self.arr_nan_1d, self.arr_nan_1d, **kwargs) - res23 = checkfun(self.arr_float_nan_1d, self.arr_nan_float1_1d, **kwargs) - res24 = checkfun( - self.arr_float_nan_1d, - self.arr_nan_float1_1d, - min_periods=len(self.arr_float_1d) - 1, - **kwargs, - ) - res25 = checkfun( - self.arr_float_1d, - self.arr_float1_1d, - min_periods=len(self.arr_float_1d) + 1, - **kwargs, - ) - tm.assert_almost_equal(targ2, res20) - tm.assert_almost_equal(targ2, res21) - tm.assert_almost_equal(targ2, res22) - tm.assert_almost_equal(targ2, res23) - tm.assert_almost_equal(targ2, res24) - tm.assert_almost_equal(targ2, res25) - - def test_nancorr(self): - targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] - targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] - self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1) - targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1] - targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] - self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson") - - def test_nancorr_pearson(self): - targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] - targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] - self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="pearson") - targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1] - targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] - self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson") - - def test_nancorr_kendall(self): - sp_stats = pytest.importorskip("scipy.stats") - - targ0 = sp_stats.kendalltau(self.arr_float_2d, self.arr_float1_2d)[0] - targ1 = sp_stats.kendalltau(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0] - self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="kendall") - targ0 = sp_stats.kendalltau(self.arr_float_1d, self.arr_float1_1d)[0] - targ1 = sp_stats.kendalltau(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0] - self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="kendall") - - def test_nancorr_spearman(self): - sp_stats = pytest.importorskip("scipy.stats") - - targ0 = sp_stats.spearmanr(self.arr_float_2d, self.arr_float1_2d)[0] - targ1 = sp_stats.spearmanr(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0] - self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="spearman") - targ0 = sp_stats.spearmanr(self.arr_float_1d, self.arr_float1_1d)[0] - targ1 = sp_stats.spearmanr(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0] - self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="spearman") - - def test_invalid_method(self): - pytest.importorskip("scipy") - targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] - targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] - msg = "Unknown method 'foo', expected one of 'kendall', 'spearman'" - with pytest.raises(ValueError, match=msg): - self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="foo") - - def test_nancov(self): - targ0 = np.cov(self.arr_float_2d, self.arr_float1_2d)[0, 1] - targ1 = np.cov(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] - self.check_nancorr_nancov_2d(nanops.nancov, targ0, targ1) - targ0 = np.cov(self.arr_float_1d, self.arr_float1_1d)[0, 1] - targ1 = np.cov(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] - self.check_nancorr_nancov_1d(nanops.nancov, targ0, targ1) - - -@pytest.mark.parametrize( - "arr, correct", - [ - ("arr_complex", False), - ("arr_int", False), - ("arr_bool", False), - ("arr_str", False), - ("arr_utf", False), - ("arr_complex", False), - ("arr_complex_nan", False), - ("arr_nan_nanj", False), - ("arr_nan_infj", True), - ("arr_complex_nan_infj", True), - ], -) -def test_has_infs_non_float(request, arr, correct, disable_bottleneck): - val = request.getfixturevalue(arr) - while getattr(val, "ndim", True): - res0 = nanops._has_infs(val) - if correct: - assert res0 - else: - assert not res0 - - if not hasattr(val, "ndim"): - break - - # Reduce dimension for next step in the loop - val = np.take(val, 0, axis=-1) - - -@pytest.mark.parametrize( - "arr, correct", - [ - ("arr_float", False), - ("arr_nan", False), - ("arr_float_nan", False), - ("arr_nan_nan", False), - ("arr_float_inf", True), - ("arr_inf", True), - ("arr_nan_inf", True), - ("arr_float_nan_inf", True), - ("arr_nan_nan_inf", True), - ], -) -@pytest.mark.parametrize("astype", [None, "f4", "f2"]) -def test_has_infs_floats(request, arr, correct, astype, disable_bottleneck): - val = request.getfixturevalue(arr) - if astype is not None: - val = val.astype(astype) - while getattr(val, "ndim", True): - res0 = nanops._has_infs(val) - if correct: - assert res0 - else: - assert not res0 - - if not hasattr(val, "ndim"): - break - - # Reduce dimension for next step in the loop - val = np.take(val, 0, axis=-1) - - -@pytest.mark.parametrize( - "fixture", ["arr_float", "arr_complex", "arr_int", "arr_bool", "arr_str", "arr_utf"] -) -def test_bn_ok_dtype(fixture, request, disable_bottleneck): - obj = request.getfixturevalue(fixture) - assert nanops._bn_ok_dtype(obj.dtype, "test") - - -@pytest.mark.parametrize( - "fixture", - [ - "arr_date", - "arr_tdelta", - "arr_obj", - ], -) -def test_bn_not_ok_dtype(fixture, request, disable_bottleneck): - obj = request.getfixturevalue(fixture) - assert not nanops._bn_ok_dtype(obj.dtype, "test") - - -class TestEnsureNumeric: - def test_numeric_values(self): - # Test integer - assert nanops._ensure_numeric(1) == 1 - - # Test float - assert nanops._ensure_numeric(1.1) == 1.1 - - # Test complex - assert nanops._ensure_numeric(1 + 2j) == 1 + 2j - - def test_ndarray(self): - # Test numeric ndarray - values = np.array([1, 2, 3]) - assert np.allclose(nanops._ensure_numeric(values), values) - - # Test object ndarray - o_values = values.astype(object) - assert np.allclose(nanops._ensure_numeric(o_values), values) - - # Test convertible string ndarray - s_values = np.array(["1", "2", "3"], dtype=object) - msg = r"Could not convert \['1' '2' '3'\] to numeric" - with pytest.raises(TypeError, match=msg): - nanops._ensure_numeric(s_values) - - # Test non-convertible string ndarray - s_values = np.array(["foo", "bar", "baz"], dtype=object) - msg = r"Could not convert .* to numeric" - with pytest.raises(TypeError, match=msg): - nanops._ensure_numeric(s_values) - - def test_convertable_values(self): - with pytest.raises(TypeError, match="Could not convert string '1' to numeric"): - nanops._ensure_numeric("1") - with pytest.raises( - TypeError, match="Could not convert string '1.1' to numeric" - ): - nanops._ensure_numeric("1.1") - with pytest.raises( - TypeError, match=r"Could not convert string '1\+1j' to numeric" - ): - nanops._ensure_numeric("1+1j") - - def test_non_convertable_values(self): - msg = "Could not convert string 'foo' to numeric" - with pytest.raises(TypeError, match=msg): - nanops._ensure_numeric("foo") - - # with the wrong type, python raises TypeError for us - msg = "argument must be a string or a number" - with pytest.raises(TypeError, match=msg): - nanops._ensure_numeric({}) - with pytest.raises(TypeError, match=msg): - nanops._ensure_numeric([]) - - -class TestNanvarFixedValues: - # xref GH10242 - # Samples from a normal distribution. - @pytest.fixture - def variance(self): - return 3.0 - - @pytest.fixture - def samples(self, variance): - return self.prng.normal(scale=variance**0.5, size=100000) - - def test_nanvar_all_finite(self, samples, variance): - actual_variance = nanops.nanvar(samples) - tm.assert_almost_equal(actual_variance, variance, rtol=1e-2) - - def test_nanvar_nans(self, samples, variance): - samples_test = np.nan * np.ones(2 * samples.shape[0]) - samples_test[::2] = samples - - actual_variance = nanops.nanvar(samples_test, skipna=True) - tm.assert_almost_equal(actual_variance, variance, rtol=1e-2) - - actual_variance = nanops.nanvar(samples_test, skipna=False) - tm.assert_almost_equal(actual_variance, np.nan, rtol=1e-2) - - def test_nanstd_nans(self, samples, variance): - samples_test = np.nan * np.ones(2 * samples.shape[0]) - samples_test[::2] = samples - - actual_std = nanops.nanstd(samples_test, skipna=True) - tm.assert_almost_equal(actual_std, variance**0.5, rtol=1e-2) - - actual_std = nanops.nanvar(samples_test, skipna=False) - tm.assert_almost_equal(actual_std, np.nan, rtol=1e-2) - - def test_nanvar_axis(self, samples, variance): - # Generate some sample data. - samples_unif = self.prng.uniform(size=samples.shape[0]) - samples = np.vstack([samples, samples_unif]) - - actual_variance = nanops.nanvar(samples, axis=1) - tm.assert_almost_equal( - actual_variance, np.array([variance, 1.0 / 12]), rtol=1e-2 - ) - - def test_nanvar_ddof(self): - n = 5 - samples = self.prng.uniform(size=(10000, n + 1)) - samples[:, -1] = np.nan # Force use of our own algorithm. - - variance_0 = nanops.nanvar(samples, axis=1, skipna=True, ddof=0).mean() - variance_1 = nanops.nanvar(samples, axis=1, skipna=True, ddof=1).mean() - variance_2 = nanops.nanvar(samples, axis=1, skipna=True, ddof=2).mean() - - # The unbiased estimate. - var = 1.0 / 12 - tm.assert_almost_equal(variance_1, var, rtol=1e-2) - - # The underestimated variance. - tm.assert_almost_equal(variance_0, (n - 1.0) / n * var, rtol=1e-2) - - # The overestimated variance. - tm.assert_almost_equal(variance_2, (n - 1.0) / (n - 2.0) * var, rtol=1e-2) - - @pytest.mark.parametrize("axis", range(2)) - @pytest.mark.parametrize("ddof", range(3)) - def test_ground_truth(self, axis, ddof): - # Test against values that were precomputed with Numpy. - samples = np.empty((4, 4)) - samples[:3, :3] = np.array( - [ - [0.97303362, 0.21869576, 0.55560287], - [0.72980153, 0.03109364, 0.99155171], - [0.09317602, 0.60078248, 0.15871292], - ] - ) - samples[3] = samples[:, 3] = np.nan - - # Actual variances along axis=0, 1 for ddof=0, 1, 2 - variance = np.array( - [ - [ - [0.13762259, 0.05619224, 0.11568816], - [0.20643388, 0.08428837, 0.17353224], - [0.41286776, 0.16857673, 0.34706449], - ], - [ - [0.09519783, 0.16435395, 0.05082054], - [0.14279674, 0.24653093, 0.07623082], - [0.28559348, 0.49306186, 0.15246163], - ], - ] - ) - - # Test nanvar. - var = nanops.nanvar(samples, skipna=True, axis=axis, ddof=ddof) - tm.assert_almost_equal(var[:3], variance[axis, ddof]) - assert np.isnan(var[3]) - - # Test nanstd. - std = nanops.nanstd(samples, skipna=True, axis=axis, ddof=ddof) - tm.assert_almost_equal(std[:3], variance[axis, ddof] ** 0.5) - assert np.isnan(std[3]) - - @pytest.mark.parametrize("ddof", range(3)) - def test_nanstd_roundoff(self, ddof): - # Regression test for GH 10242 (test data taken from GH 10489). Ensure - # that variance is stable. - data = Series(766897346 * np.ones(10)) - result = data.std(ddof=ddof) - assert result == 0.0 - - @property - def prng(self): - return np.random.default_rng(2) - - -class TestNanskewFixedValues: - # xref GH 11974 - # Test data + skewness value (computed with scipy.stats.skew) - @pytest.fixture - def samples(self): - return np.sin(np.linspace(0, 1, 200)) - - @pytest.fixture - def actual_skew(self): - return -0.1875895205961754 - - @pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5]) - def test_constant_series(self, val): - # xref GH 11974 - data = val * np.ones(300) - skew = nanops.nanskew(data) - assert skew == 0.0 - - def test_all_finite(self): - alpha, beta = 0.3, 0.1 - left_tailed = self.prng.beta(alpha, beta, size=100) - assert nanops.nanskew(left_tailed) < 0 - - alpha, beta = 0.1, 0.3 - right_tailed = self.prng.beta(alpha, beta, size=100) - assert nanops.nanskew(right_tailed) > 0 - - def test_ground_truth(self, samples, actual_skew): - skew = nanops.nanskew(samples) - tm.assert_almost_equal(skew, actual_skew) - - def test_axis(self, samples, actual_skew): - samples = np.vstack([samples, np.nan * np.ones(len(samples))]) - skew = nanops.nanskew(samples, axis=1) - tm.assert_almost_equal(skew, np.array([actual_skew, np.nan])) - - def test_nans(self, samples): - samples = np.hstack([samples, np.nan]) - skew = nanops.nanskew(samples, skipna=False) - assert np.isnan(skew) - - def test_nans_skipna(self, samples, actual_skew): - samples = np.hstack([samples, np.nan]) - skew = nanops.nanskew(samples, skipna=True) - tm.assert_almost_equal(skew, actual_skew) - - @property - def prng(self): - return np.random.default_rng(2) - - -class TestNankurtFixedValues: - # xref GH 11974 - # Test data + kurtosis value (computed with scipy.stats.kurtosis) - @pytest.fixture - def samples(self): - return np.sin(np.linspace(0, 1, 200)) - - @pytest.fixture - def actual_kurt(self): - return -1.2058303433799713 - - @pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5]) - def test_constant_series(self, val): - # xref GH 11974 - data = val * np.ones(300) - kurt = nanops.nankurt(data) - assert kurt == 0.0 - - def test_all_finite(self): - alpha, beta = 0.3, 0.1 - left_tailed = self.prng.beta(alpha, beta, size=100) - assert nanops.nankurt(left_tailed) < 2 - - alpha, beta = 0.1, 0.3 - right_tailed = self.prng.beta(alpha, beta, size=100) - assert nanops.nankurt(right_tailed) < 0 - - def test_ground_truth(self, samples, actual_kurt): - kurt = nanops.nankurt(samples) - tm.assert_almost_equal(kurt, actual_kurt) - - def test_axis(self, samples, actual_kurt): - samples = np.vstack([samples, np.nan * np.ones(len(samples))]) - kurt = nanops.nankurt(samples, axis=1) - tm.assert_almost_equal(kurt, np.array([actual_kurt, np.nan])) - - def test_nans(self, samples): - samples = np.hstack([samples, np.nan]) - kurt = nanops.nankurt(samples, skipna=False) - assert np.isnan(kurt) - - def test_nans_skipna(self, samples, actual_kurt): - samples = np.hstack([samples, np.nan]) - kurt = nanops.nankurt(samples, skipna=True) - tm.assert_almost_equal(kurt, actual_kurt) - - @property - def prng(self): - return np.random.default_rng(2) - - -class TestDatetime64NaNOps: - @pytest.fixture(params=["s", "ms", "us", "ns"]) - def unit(self, request): - return request.param - - # Enabling mean changes the behavior of DataFrame.mean - # See https://github.com/pandas-dev/pandas/issues/24752 - def test_nanmean(self, unit): - dti = pd.date_range("2016-01-01", periods=3).as_unit(unit) - expected = dti[1] - - for obj in [dti, DatetimeArray(dti), Series(dti)]: - result = nanops.nanmean(obj) - assert result == expected - - dti2 = dti.insert(1, pd.NaT) - - for obj in [dti2, DatetimeArray(dti2), Series(dti2)]: - result = nanops.nanmean(obj) - assert result == expected - - @pytest.mark.parametrize("constructor", ["M8", "m8"]) - def test_nanmean_skipna_false(self, constructor, unit): - dtype = f"{constructor}[{unit}]" - arr = np.arange(12).astype(np.int64).view(dtype).reshape(4, 3) - - arr[-1, -1] = "NaT" - - result = nanops.nanmean(arr, skipna=False) - assert np.isnat(result) - assert result.dtype == dtype - - result = nanops.nanmean(arr, axis=0, skipna=False) - expected = np.array([4, 5, "NaT"], dtype=arr.dtype) - tm.assert_numpy_array_equal(result, expected) - - result = nanops.nanmean(arr, axis=1, skipna=False) - expected = np.array([arr[0, 1], arr[1, 1], arr[2, 1], arr[-1, -1]]) - tm.assert_numpy_array_equal(result, expected) - - -def test_use_bottleneck(): - if nanops._BOTTLENECK_INSTALLED: - with pd.option_context("use_bottleneck", True): - assert pd.get_option("use_bottleneck") - - with pd.option_context("use_bottleneck", False): - assert not pd.get_option("use_bottleneck") - - -@pytest.mark.parametrize( - "numpy_op, expected", - [ - (np.sum, 10), - (np.nansum, 10), - (np.mean, 2.5), - (np.nanmean, 2.5), - (np.median, 2.5), - (np.nanmedian, 2.5), - (np.min, 1), - (np.max, 4), - (np.nanmin, 1), - (np.nanmax, 4), - ], -) -def test_numpy_ops(numpy_op, expected): - # GH8383 - result = numpy_op(Series([1, 2, 3, 4])) - assert result == expected - - -@pytest.mark.parametrize( - "operation", - [ - nanops.nanany, - nanops.nanall, - nanops.nansum, - nanops.nanmean, - nanops.nanmedian, - nanops.nanstd, - nanops.nanvar, - nanops.nansem, - nanops.nanargmax, - nanops.nanargmin, - nanops.nanmax, - nanops.nanmin, - nanops.nanskew, - nanops.nankurt, - nanops.nanprod, - ], -) -def test_nanops_independent_of_mask_param(operation): - # GH22764 - ser = Series([1, 2, np.nan, 3, np.nan, 4]) - mask = ser.isna() - median_expected = operation(ser._values) - median_result = operation(ser._values, mask=mask) - assert median_expected == median_result - - -@pytest.mark.parametrize("min_count", [-1, 0]) -def test_check_below_min_count_negative_or_zero_min_count(min_count): - # GH35227 - result = nanops.check_below_min_count((21, 37), None, min_count) - expected_result = False - assert result == expected_result - - -@pytest.mark.parametrize( - "mask", [None, np.array([False, False, True]), np.array([True] + 9 * [False])] -) -@pytest.mark.parametrize("min_count, expected_result", [(1, False), (101, True)]) -def test_check_below_min_count_positive_min_count(mask, min_count, expected_result): - # GH35227 - shape = (10, 10) - result = nanops.check_below_min_count(shape, mask, min_count) - assert result == expected_result - - -@td.skip_if_windows -@td.skip_if_32bit -@pytest.mark.parametrize("min_count, expected_result", [(1, False), (2812191852, True)]) -def test_check_below_min_count_large_shape(min_count, expected_result): - # GH35227 large shape used to show that the issue is fixed - shape = (2244367, 1253) - result = nanops.check_below_min_count(shape, mask=None, min_count=min_count) - assert result == expected_result - - -@pytest.mark.parametrize("func", ["nanmean", "nansum"]) -def test_check_bottleneck_disallow(any_real_numpy_dtype, func): - # GH 42878 bottleneck sometimes produces unreliable results for mean and sum - assert not nanops._bn_ok_dtype(np.dtype(any_real_numpy_dtype).type, func) - - -@pytest.mark.parametrize("val", [2**55, -(2**55), 20150515061816532]) -def test_nanmean_overflow(disable_bottleneck, val): - # GH 10155 - # In the previous implementation mean can overflow for int dtypes, it - # is now consistent with numpy - - ser = Series(val, index=range(500), dtype=np.int64) - result = ser.mean() - np_result = ser.values.mean() - assert result == val - assert result == np_result - assert result.dtype == np.float64 - - -@pytest.mark.parametrize( - "dtype", - [ - np.int16, - np.int32, - np.int64, - np.float32, - np.float64, - getattr(np, "float128", None), - ], -) -@pytest.mark.parametrize("method", ["mean", "std", "var", "skew", "kurt", "min", "max"]) -def test_returned_dtype(disable_bottleneck, dtype, method): - if dtype is None: - pytest.skip("np.float128 not available") - - ser = Series(range(10), dtype=dtype) - result = getattr(ser, method)() - if is_integer_dtype(dtype) and method not in ["min", "max"]: - assert result.dtype == np.float64 - else: - assert result.dtype == dtype diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/req/constructors.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/req/constructors.py deleted file mode 100644 index 25bfb391d88259d72cc90cb2e4229ab9698ebb04..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/req/constructors.py +++ /dev/null @@ -1,490 +0,0 @@ -"""Backing implementation for InstallRequirement's various constructors - -The idea here is that these formed a major chunk of InstallRequirement's size -so, moving them and support code dedicated to them outside of that class -helps creates for better understandability for the rest of the code. - -These are meant to be used elsewhere within pip to create instances of -InstallRequirement. -""" - -import logging -import os -import re -from typing import Any, Dict, Optional, Set, Tuple, Union - -from pip._vendor.packaging.markers import Marker -from pip._vendor.packaging.requirements import InvalidRequirement, Requirement -from pip._vendor.packaging.specifiers import Specifier - -from pip._internal.exceptions import InstallationError -from pip._internal.models.index import PyPI, TestPyPI -from pip._internal.models.link import Link -from pip._internal.models.wheel import Wheel -from pip._internal.req.req_file import ParsedRequirement -from pip._internal.req.req_install import InstallRequirement -from pip._internal.utils.filetypes import is_archive_file -from pip._internal.utils.misc import is_installable_dir -from pip._internal.utils.packaging import get_requirement -from pip._internal.utils.urls import path_to_url -from pip._internal.vcs import is_url, vcs - -__all__ = [ - "install_req_from_editable", - "install_req_from_line", - "parse_editable", -] - -logger = logging.getLogger(__name__) -operators = Specifier._operators.keys() - - -def _strip_extras(path: str) -> Tuple[str, Optional[str]]: - m = re.match(r"^(.+)(\[[^\]]+\])$", path) - extras = None - if m: - path_no_extras = m.group(1) - extras = m.group(2) - else: - path_no_extras = path - - return path_no_extras, extras - - -def convert_extras(extras: Optional[str]) -> Set[str]: - if not extras: - return set() - return get_requirement("placeholder" + extras.lower()).extras - - -def parse_editable(editable_req: str) -> Tuple[Optional[str], str, Set[str]]: - """Parses an editable requirement into: - - a requirement name - - an URL - - extras - - editable options - Accepted requirements: - svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir - .[some_extra] - """ - - url = editable_req - - # If a file path is specified with extras, strip off the extras. - url_no_extras, extras = _strip_extras(url) - - if os.path.isdir(url_no_extras): - # Treating it as code that has already been checked out - url_no_extras = path_to_url(url_no_extras) - - if url_no_extras.lower().startswith("file:"): - package_name = Link(url_no_extras).egg_fragment - if extras: - return ( - package_name, - url_no_extras, - get_requirement("placeholder" + extras.lower()).extras, - ) - else: - return package_name, url_no_extras, set() - - for version_control in vcs: - if url.lower().startswith(f"{version_control}:"): - url = f"{version_control}+{url}" - break - - link = Link(url) - - if not link.is_vcs: - backends = ", ".join(vcs.all_schemes) - raise InstallationError( - f"{editable_req} is not a valid editable requirement. " - f"It should either be a path to a local project or a VCS URL " - f"(beginning with {backends})." - ) - - package_name = link.egg_fragment - if not package_name: - raise InstallationError( - "Could not detect requirement name for '{}', please specify one " - "with #egg=your_package_name".format(editable_req) - ) - return package_name, url, set() - - -def check_first_requirement_in_file(filename: str) -> None: - """Check if file is parsable as a requirements file. - - This is heavily based on ``pkg_resources.parse_requirements``, but - simplified to just check the first meaningful line. - - :raises InvalidRequirement: If the first meaningful line cannot be parsed - as an requirement. - """ - with open(filename, encoding="utf-8", errors="ignore") as f: - # Create a steppable iterator, so we can handle \-continuations. - lines = ( - line - for line in (line.strip() for line in f) - if line and not line.startswith("#") # Skip blank lines/comments. - ) - - for line in lines: - # Drop comments -- a hash without a space may be in a URL. - if " #" in line: - line = line[: line.find(" #")] - # If there is a line continuation, drop it, and append the next line. - if line.endswith("\\"): - line = line[:-2].strip() + next(lines, "") - Requirement(line) - return - - -def deduce_helpful_msg(req: str) -> str: - """Returns helpful msg in case requirements file does not exist, - or cannot be parsed. - - :params req: Requirements file path - """ - if not os.path.exists(req): - return f" File '{req}' does not exist." - msg = " The path does exist. " - # Try to parse and check if it is a requirements file. - try: - check_first_requirement_in_file(req) - except InvalidRequirement: - logger.debug("Cannot parse '%s' as requirements file", req) - else: - msg += ( - f"The argument you provided " - f"({req}) appears to be a" - f" requirements file. If that is the" - f" case, use the '-r' flag to install" - f" the packages specified within it." - ) - return msg - - -class RequirementParts: - def __init__( - self, - requirement: Optional[Requirement], - link: Optional[Link], - markers: Optional[Marker], - extras: Set[str], - ): - self.requirement = requirement - self.link = link - self.markers = markers - self.extras = extras - - -def parse_req_from_editable(editable_req: str) -> RequirementParts: - name, url, extras_override = parse_editable(editable_req) - - if name is not None: - try: - req: Optional[Requirement] = Requirement(name) - except InvalidRequirement: - raise InstallationError(f"Invalid requirement: '{name}'") - else: - req = None - - link = Link(url) - - return RequirementParts(req, link, None, extras_override) - - -# ---- The actual constructors follow ---- - - -def install_req_from_editable( - editable_req: str, - comes_from: Optional[Union[InstallRequirement, str]] = None, - use_pep517: Optional[bool] = None, - isolated: bool = False, - options: Optional[Dict[str, Any]] = None, - constraint: bool = False, - user_supplied: bool = False, - permit_editable_wheels: bool = False, -) -> InstallRequirement: - - parts = parse_req_from_editable(editable_req) - - return InstallRequirement( - parts.requirement, - comes_from=comes_from, - user_supplied=user_supplied, - editable=True, - permit_editable_wheels=permit_editable_wheels, - link=parts.link, - constraint=constraint, - use_pep517=use_pep517, - isolated=isolated, - install_options=options.get("install_options", []) if options else [], - global_options=options.get("global_options", []) if options else [], - hash_options=options.get("hashes", {}) if options else {}, - extras=parts.extras, - ) - - -def _looks_like_path(name: str) -> bool: - """Checks whether the string "looks like" a path on the filesystem. - - This does not check whether the target actually exists, only judge from the - appearance. - - Returns true if any of the following conditions is true: - * a path separator is found (either os.path.sep or os.path.altsep); - * a dot is found (which represents the current directory). - """ - if os.path.sep in name: - return True - if os.path.altsep is not None and os.path.altsep in name: - return True - if name.startswith("."): - return True - return False - - -def _get_url_from_path(path: str, name: str) -> Optional[str]: - """ - First, it checks whether a provided path is an installable directory. If it - is, returns the path. - - If false, check if the path is an archive file (such as a .whl). - The function checks if the path is a file. If false, if the path has - an @, it will treat it as a PEP 440 URL requirement and return the path. - """ - if _looks_like_path(name) and os.path.isdir(path): - if is_installable_dir(path): - return path_to_url(path) - # TODO: The is_installable_dir test here might not be necessary - # now that it is done in load_pyproject_toml too. - raise InstallationError( - f"Directory {name!r} is not installable. Neither 'setup.py' " - "nor 'pyproject.toml' found." - ) - if not is_archive_file(path): - return None - if os.path.isfile(path): - return path_to_url(path) - urlreq_parts = name.split("@", 1) - if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]): - # If the path contains '@' and the part before it does not look - # like a path, try to treat it as a PEP 440 URL req instead. - return None - logger.warning( - "Requirement %r looks like a filename, but the file does not exist", - name, - ) - return path_to_url(path) - - -def parse_req_from_line(name: str, line_source: Optional[str]) -> RequirementParts: - if is_url(name): - marker_sep = "; " - else: - marker_sep = ";" - if marker_sep in name: - name, markers_as_string = name.split(marker_sep, 1) - markers_as_string = markers_as_string.strip() - if not markers_as_string: - markers = None - else: - markers = Marker(markers_as_string) - else: - markers = None - name = name.strip() - req_as_string = None - path = os.path.normpath(os.path.abspath(name)) - link = None - extras_as_string = None - - if is_url(name): - link = Link(name) - else: - p, extras_as_string = _strip_extras(path) - url = _get_url_from_path(p, name) - if url is not None: - link = Link(url) - - # it's a local file, dir, or url - if link: - # Handle relative file URLs - if link.scheme == "file" and re.search(r"\.\./", link.url): - link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path)))) - # wheel file - if link.is_wheel: - wheel = Wheel(link.filename) # can raise InvalidWheelFilename - req_as_string = f"{wheel.name}=={wheel.version}" - else: - # set the req to the egg fragment. when it's not there, this - # will become an 'unnamed' requirement - req_as_string = link.egg_fragment - - # a requirement specifier - else: - req_as_string = name - - extras = convert_extras(extras_as_string) - - def with_source(text: str) -> str: - if not line_source: - return text - return f"{text} (from {line_source})" - - def _parse_req_string(req_as_string: str) -> Requirement: - try: - req = get_requirement(req_as_string) - except InvalidRequirement: - if os.path.sep in req_as_string: - add_msg = "It looks like a path." - add_msg += deduce_helpful_msg(req_as_string) - elif "=" in req_as_string and not any( - op in req_as_string for op in operators - ): - add_msg = "= is not a valid operator. Did you mean == ?" - else: - add_msg = "" - msg = with_source(f"Invalid requirement: {req_as_string!r}") - if add_msg: - msg += f"\nHint: {add_msg}" - raise InstallationError(msg) - else: - # Deprecate extras after specifiers: "name>=1.0[extras]" - # This currently works by accident because _strip_extras() parses - # any extras in the end of the string and those are saved in - # RequirementParts - for spec in req.specifier: - spec_str = str(spec) - if spec_str.endswith("]"): - msg = f"Extras after version '{spec_str}'." - raise InstallationError(msg) - return req - - if req_as_string is not None: - req: Optional[Requirement] = _parse_req_string(req_as_string) - else: - req = None - - return RequirementParts(req, link, markers, extras) - - -def install_req_from_line( - name: str, - comes_from: Optional[Union[str, InstallRequirement]] = None, - use_pep517: Optional[bool] = None, - isolated: bool = False, - options: Optional[Dict[str, Any]] = None, - constraint: bool = False, - line_source: Optional[str] = None, - user_supplied: bool = False, -) -> InstallRequirement: - """Creates an InstallRequirement from a name, which might be a - requirement, directory containing 'setup.py', filename, or URL. - - :param line_source: An optional string describing where the line is from, - for logging purposes in case of an error. - """ - parts = parse_req_from_line(name, line_source) - - return InstallRequirement( - parts.requirement, - comes_from, - link=parts.link, - markers=parts.markers, - use_pep517=use_pep517, - isolated=isolated, - install_options=options.get("install_options", []) if options else [], - global_options=options.get("global_options", []) if options else [], - hash_options=options.get("hashes", {}) if options else {}, - constraint=constraint, - extras=parts.extras, - user_supplied=user_supplied, - ) - - -def install_req_from_req_string( - req_string: str, - comes_from: Optional[InstallRequirement] = None, - isolated: bool = False, - use_pep517: Optional[bool] = None, - user_supplied: bool = False, -) -> InstallRequirement: - try: - req = get_requirement(req_string) - except InvalidRequirement: - raise InstallationError(f"Invalid requirement: '{req_string}'") - - domains_not_allowed = [ - PyPI.file_storage_domain, - TestPyPI.file_storage_domain, - ] - if ( - req.url - and comes_from - and comes_from.link - and comes_from.link.netloc in domains_not_allowed - ): - # Explicitly disallow pypi packages that depend on external urls - raise InstallationError( - "Packages installed from PyPI cannot depend on packages " - "which are not also hosted on PyPI.\n" - "{} depends on {} ".format(comes_from.name, req) - ) - - return InstallRequirement( - req, - comes_from, - isolated=isolated, - use_pep517=use_pep517, - user_supplied=user_supplied, - ) - - -def install_req_from_parsed_requirement( - parsed_req: ParsedRequirement, - isolated: bool = False, - use_pep517: Optional[bool] = None, - user_supplied: bool = False, -) -> InstallRequirement: - if parsed_req.is_editable: - req = install_req_from_editable( - parsed_req.requirement, - comes_from=parsed_req.comes_from, - use_pep517=use_pep517, - constraint=parsed_req.constraint, - isolated=isolated, - user_supplied=user_supplied, - ) - - else: - req = install_req_from_line( - parsed_req.requirement, - comes_from=parsed_req.comes_from, - use_pep517=use_pep517, - isolated=isolated, - options=parsed_req.options, - constraint=parsed_req.constraint, - line_source=parsed_req.line_source, - user_supplied=user_supplied, - ) - return req - - -def install_req_from_link_and_ireq( - link: Link, ireq: InstallRequirement -) -> InstallRequirement: - return InstallRequirement( - req=ireq.req, - comes_from=ireq.comes_from, - editable=ireq.editable, - link=link, - markers=ireq.markers, - use_pep517=ireq.use_pep517, - isolated=ireq.isolated, - install_options=ireq.install_options, - global_options=ireq.global_options, - hash_options=ireq.hash_options, - ) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/resolution/legacy/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/resolution/legacy/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/rich/status.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/rich/status.py deleted file mode 100644 index 09eff405ec194ee2884f203cb48c5df54ff0b9c7..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/rich/status.py +++ /dev/null @@ -1,132 +0,0 @@ -from types import TracebackType -from typing import Optional, Type - -from .console import Console, RenderableType -from .jupyter import JupyterMixin -from .live import Live -from .spinner import Spinner -from .style import StyleType - - -class Status(JupyterMixin): - """Displays a status indicator with a 'spinner' animation. - - Args: - status (RenderableType): A status renderable (str or Text typically). - console (Console, optional): Console instance to use, or None for global console. Defaults to None. - spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots". - spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner". - speed (float, optional): Speed factor for spinner animation. Defaults to 1.0. - refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5. - """ - - def __init__( - self, - status: RenderableType, - *, - console: Optional[Console] = None, - spinner: str = "dots", - spinner_style: StyleType = "status.spinner", - speed: float = 1.0, - refresh_per_second: float = 12.5, - ): - self.status = status - self.spinner_style = spinner_style - self.speed = speed - self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed) - self._live = Live( - self.renderable, - console=console, - refresh_per_second=refresh_per_second, - transient=True, - ) - - @property - def renderable(self) -> Spinner: - return self._spinner - - @property - def console(self) -> "Console": - """Get the Console used by the Status objects.""" - return self._live.console - - def update( - self, - status: Optional[RenderableType] = None, - *, - spinner: Optional[str] = None, - spinner_style: Optional[StyleType] = None, - speed: Optional[float] = None, - ) -> None: - """Update status. - - Args: - status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None. - spinner (Optional[str], optional): New spinner or None for no change. Defaults to None. - spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None. - speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None. - """ - if status is not None: - self.status = status - if spinner_style is not None: - self.spinner_style = spinner_style - if speed is not None: - self.speed = speed - if spinner is not None: - self._spinner = Spinner( - spinner, text=self.status, style=self.spinner_style, speed=self.speed - ) - self._live.update(self.renderable, refresh=True) - else: - self._spinner.update( - text=self.status, style=self.spinner_style, speed=self.speed - ) - - def start(self) -> None: - """Start the status animation.""" - self._live.start() - - def stop(self) -> None: - """Stop the spinner animation.""" - self._live.stop() - - def __rich__(self) -> RenderableType: - return self.renderable - - def __enter__(self) -> "Status": - self.start() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - self.stop() - - -if __name__ == "__main__": # pragma: no cover - - from time import sleep - - from .console import Console - - console = Console() - with console.status("[magenta]Covid detector booting up") as status: - sleep(3) - console.log("Importing advanced AI") - sleep(3) - console.log("Advanced Covid AI Ready") - sleep(3) - status.update(status="[bold blue] Scanning for Covid", spinner="earth") - sleep(3) - console.log("Found 10,000,000,000 copies of Covid32.exe") - sleep(3) - status.update( - status="[bold red]Moving Covid32.exe to Trash", - spinner="bouncingBall", - spinner_style="yellow", - ) - sleep(5) - console.print("[bold green]Covid deleted successfully") diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/tomli/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/tomli/__init__.py deleted file mode 100644 index 1cd8e07279ae7b5e11954d5aaf7d3be03d107cb6..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/tomli/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""A lil' TOML parser.""" - -__all__ = ("loads", "load", "TOMLDecodeError") -__version__ = "1.0.3" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT - -from pip._vendor.tomli._parser import TOMLDecodeError, load, loads diff --git a/spaces/pustozerov/poc-handwriting-ocr/pages/handwriting_ocr_en_page.py b/spaces/pustozerov/poc-handwriting-ocr/pages/handwriting_ocr_en_page.py deleted file mode 100644 index e3cf58a035af9c1e33e80803c7e90a61432f9ec1..0000000000000000000000000000000000000000 --- a/spaces/pustozerov/poc-handwriting-ocr/pages/handwriting_ocr_en_page.py +++ /dev/null @@ -1,61 +0,0 @@ -import glob -import os -import random -import shutil -from pathlib import Path - -import streamlit as st - -from modules.ocr_model_en.ocr import preprocess_image, recognize_char - -st.title('Latin handwriting full page OCR demo') -st.write('This simple demo shows the possibilities of deep learning architecture in the task of automatic text ' - 'recognition for Latin texts. It works with text pages of various sizes. You can pick an image from the ' - 'built-in database or try uploading your photo or scanned documents.') -st.write('Note: this demo shows up a reduced-performance model. To get a full-performance neural network or develop a ' - 'system adapted to your task – contact kirill.lozovoi@exposit.com.') - -if st.button('Try random samples from the database'): - folder = "data/sample/" - os.makedirs(folder, exist_ok=True) - list_all_texts = glob.glob("data/pages/*.jpg") - chosen_file = sorted(random.sample(list_all_texts, 1)) - for f in glob.glob(folder + '*'): - os.remove(f) - for f in chosen_file: - path = shutil.copy2(f, folder) - for f in glob.glob(folder + '*'): - col1, col2 = st.columns(2) - with col1: - st.image(f) - with col2: - lines, crop, image_with_boxes = preprocess_image(chosen_file[0]) - st.image(image_with_boxes) - for line in lines: - st.text(" ".join([recognize_char(crop[y1:y2, x1:x2]) for (x1, y1, x2, y2) in line])) - -uploaded_file = st.file_uploader("Choose your page with latin text", - accept_multiple_files=False, type=["png", "jpeg", "jpg"]) -if uploaded_file is not None: - folder = "data/user_data/" - os.makedirs(folder, exist_ok=True) - for f in glob.glob(folder + '*'): - os.remove(f) - bytes_data = uploaded_file.read() - # st.image(bytes_data) - save_path = Path(folder, uploaded_file.name) - for f in glob.glob(folder + '*'): - os.remove(f) - chosen_file = Path(folder, uploaded_file.name) - with open(save_path, mode='wb') as w: - w.write(uploaded_file.getvalue()) - st.write(chosen_file) - for f in glob.glob(folder + '*'): - col1, col2 = st.columns(2) - with col1: - st.image(f) - with col2: - lines, crop, image_with_boxes = preprocess_image(f) - st.image(image_with_boxes) - for line in lines: - st.text(" ".join([recognize_char(crop[y1:y2, x1:x2]) for (x1, y1, x2, y2) in line])) diff --git a/spaces/pustozerov/poc-handwriting-ocr/pages/handwriting_ocr_ru.py b/spaces/pustozerov/poc-handwriting-ocr/pages/handwriting_ocr_ru.py deleted file mode 100644 index 97327d01caac8c40d91e6cb10681f015cd74b4cc..0000000000000000000000000000000000000000 --- a/spaces/pustozerov/poc-handwriting-ocr/pages/handwriting_ocr_ru.py +++ /dev/null @@ -1,51 +0,0 @@ -import glob -import os -import random -import shutil -from pathlib import Path - -import streamlit as st - -from modules.ocr_model_ru.model import prediction - -st.title('Cyrillic handwriting OCR demo') -st.write('This simple demo shows the possibilities of the Transformer deep learning architecture in automatic text ' - 'recognition tasks for Cyrillic texts. It now works with single-line samples. You can randomly pick a set of ' - 'images from the built-in database or try uploading your files.') -st.write('Note: this demo shows up a reduced-performance model. To get a full-performance neural network or develop a ' - 'system adapted to your task – contact kirill.lozovoi@exposit.com.') - -if st.button('Try random samples from the database'): - folder = "data/sample/" - os.makedirs(folder, exist_ok=True) - list_all_texts = glob.glob("data/cyrillic_handwriting_dataset/data_decimated/*.png") - chosen_files = sorted(random.sample(list_all_texts, 3)) - for f in glob.glob(folder + '*'): - os.remove(f) - for f in chosen_files: - path = shutil.copy2(f, folder) - for f in glob.glob(folder + '*'): - col1, col2 = st.columns(2) - with col1: - st.image(f) - with col2: - st.text(f) - - preds = prediction(folder) - print(preds) - st.write(preds) -uploaded_file = st.file_uploader("Choose your image with a single line of text in cyrillic", - accept_multiple_files=False, type=["png", "jpeg", "jpg"]) -if uploaded_file is not None: - folder = "data/user_data/" - os.makedirs(folder, exist_ok=True) - for f in glob.glob(folder + '*'): - os.remove(f) - bytes_data = uploaded_file.read() - st.image(bytes_data) - save_path = Path(folder, uploaded_file.name) - with open(save_path, mode='wb') as w: - w.write(uploaded_file.getvalue()) - preds = prediction(folder) - print(preds) - st.write(preds) diff --git a/spaces/qdd319/ChuanhuChatGPT/ChuanhuChatbot.py b/spaces/qdd319/ChuanhuChatGPT/ChuanhuChatbot.py deleted file mode 100644 index 5d18393a7cc42c6545d90e9a8ebf949745ebe5bf..0000000000000000000000000000000000000000 --- a/spaces/qdd319/ChuanhuChatGPT/ChuanhuChatbot.py +++ /dev/null @@ -1,423 +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.chat_func import * -from modules.openai_func import get_usage - -gr.Chatbot.postprocess = postprocess -PromptHelper.compact_text_chunks = compact_text_chunks - -with open("assets/custom.css", "r", encoding="utf-8") as f: - customCSS = f.read() - -with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo: - user_name = gr.State("") - history = gr.State([]) - token_count = gr.State([]) - promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2)) - user_api_key = gr.State(my_api_key) - user_question = gr.State("") - outputing = gr.State(False) - topic = gr.State("未命名对话历史记录") - - with gr.Row(): - with gr.Column(): - gr.HTML(title) - user_info = gr.Markdown(value="", elem_id="user_info") - gr.HTML('
    Duplicate Space
    ') - status_display = gr.Markdown(get_geoip(), elem_id="status_display") - - # 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}") - return gr.Markdown.update(value=f"User: {request.username}"), request.username - else: - return gr.Markdown.update(value=f"User: default", visible=False), "" - demo.load(create_greeting, inputs=None, outputs=[user_info, user_name]) - - with gr.Row().style(equal_height=True): - with gr.Column(scale=5): - with gr.Row(): - chatbot = gr.Chatbot(elem_id="chuanhu_chatbot").style(height="100%") - with gr.Row(): - with gr.Column(scale=12): - user_input = gr.Textbox( - elem_id="user_input_tb", - show_label=False, placeholder="在这里输入" - ).style(container=False) - with gr.Column(min_width=70, scale=1): - submitBtn = gr.Button("发送", variant="primary") - cancelBtn = gr.Button("取消", variant="secondary", visible=False) - with gr.Row(): - emptyBtn = gr.Button( - "🧹 新的对话", - ) - retryBtn = gr.Button("🔄 重新生成") - delFirstBtn = gr.Button("🗑️ 删除最旧对话") - delLastBtn = gr.Button("🗑️ 删除最新对话") - reduceTokenBtn = gr.Button("♻️ 总结对话") - - with gr.Column(): - with gr.Column(min_width=50, scale=1): - with gr.Tab(label="ChatGPT"): - keyTxt = gr.Textbox( - show_label=True, - placeholder=f"OpenAI API-key...", - value=hide_middle_chars(my_api_key), - type="password", - visible=not HIDE_MY_KEY, - label="API-Key", - ) - if multi_api_key: - usageTxt = gr.Markdown("多账号模式已开启,无需输入key,可直接开始对话", elem_id="usage_display") - else: - usageTxt = gr.Markdown("**发送消息** 或 **提交key** 以显示额度", elem_id="usage_display") - model_select_dropdown = gr.Dropdown( - label="选择模型", choices=MODELS, multiselect=False, value=MODELS[0] - ) - use_streaming_checkbox = gr.Checkbox( - label="实时传输回答", value=True, visible=enable_streaming_option - ) - use_websearch_checkbox = gr.Checkbox(label="使用在线搜索", value=False) - language_select_dropdown = gr.Dropdown( - label="选择回复语言(针对搜索&索引功能)", - choices=REPLY_LANGUAGES, - multiselect=False, - value=REPLY_LANGUAGES[0], - ) - index_files = gr.Files(label="上传索引文件", type="file", multiple=True) - two_column = gr.Checkbox(label="双栏pdf", value=advance_docs["pdf"].get("two_column", False)) - # TODO: 公式ocr - # formula_ocr = gr.Checkbox(label="识别公式", value=advance_docs["pdf"].get("formula_ocr", False)) - - with gr.Tab(label="Prompt"): - systemPromptTxt = gr.Textbox( - show_label=True, - placeholder=f"在这里输入System Prompt...", - label="System prompt", - value=initial_prompt, - lines=10, - ).style(container=False) - with gr.Accordion(label="加载Prompt模板", open=True): - with gr.Column(): - with gr.Row(): - with gr.Column(scale=6): - templateFileSelectDropdown = gr.Dropdown( - label="选择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("🔄 刷新") - with gr.Row(): - with gr.Column(): - templateSelectDropdown = gr.Dropdown( - label="从Prompt模板中加载", - choices=load_template( - get_template_names(plain=True)[0], mode=1 - ), - multiselect=False, - ).style(container=False) - - with gr.Tab(label="保存/加载"): - with gr.Accordion(label="保存/加载对话历史记录", open=True): - with gr.Column(): - with gr.Row(): - with gr.Column(scale=6): - historyFileSelectDropdown = gr.Dropdown( - label="从列表中加载对话", - choices=get_history_names(plain=True), - multiselect=False, - value=get_history_names(plain=True)[0], - ) - with gr.Column(scale=1): - historyRefreshBtn = gr.Button("🔄 刷新") - with gr.Row(): - with gr.Column(scale=6): - saveFileName = gr.Textbox( - show_label=True, - placeholder=f"设置文件名: 默认为.json,可选为.md", - label="设置保存文件名", - value="对话历史记录", - ).style(container=True) - with gr.Column(scale=1): - saveHistoryBtn = gr.Button("💾 保存对话") - exportMarkdownBtn = gr.Button("📝 导出为Markdown") - gr.Markdown("默认保存于history文件夹") - with gr.Row(): - with gr.Column(): - downloadFile = gr.File(interactive=True) - - with gr.Tab(label="高级"): - gr.Markdown("# ⚠️ 务必谨慎更改 ⚠️\n\n如果无法使用请恢复默认设置") - default_btn = gr.Button("🔙 恢复默认设置") - - with gr.Accordion("参数", open=False): - top_p = gr.Slider( - minimum=-0, - maximum=1.0, - value=1.0, - step=0.05, - interactive=True, - label="Top-p", - ) - temperature = gr.Slider( - minimum=-0, - maximum=2.0, - value=1.0, - step=0.1, - interactive=True, - label="Temperature", - ) - - with gr.Accordion("网络设置", open=False, visible=False): - # 优先展示自定义的api_host - apihostTxt = gr.Textbox( - show_label=True, - placeholder=f"在这里输入API-Host...", - label="API-Host", - value=config.api_host or shared.API_HOST, - lines=1, - ) - changeAPIURLBtn = gr.Button("🔄 切换API地址") - proxyTxt = gr.Textbox( - show_label=True, - placeholder=f"在这里输入代理地址...", - label="代理地址(示例:http://127.0.0.1:10809)", - value="", - lines=2, - ) - changeProxyBtn = gr.Button("🔄 设置代理地址") - - gr.Markdown(description) - gr.HTML(footer.format(versions=versions_html()), elem_id="footer") - chatgpt_predict_args = dict( - fn=predict, - inputs=[ - user_api_key, - systemPromptTxt, - history, - user_question, - chatbot, - token_count, - top_p, - temperature, - use_streaming_checkbox, - model_select_dropdown, - use_websearch_checkbox, - index_files, - language_select_dropdown, - ], - outputs=[chatbot, history, status_display, token_count], - 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=get_usage, inputs=[user_api_key], outputs=[usageTxt], show_progress=False - ) - - - # Chatbot - cancelBtn.click(cancel_outputing, [], []) - - 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).then(**end_outputing_args) - submitBtn.click(**get_usage_args) - - emptyBtn.click( - reset_state, - outputs=[chatbot, history, token_count, status_display], - show_progress=True, - ) - emptyBtn.click(**reset_textbox_args) - - retryBtn.click(**start_outputing_args).then( - retry, - [ - user_api_key, - systemPromptTxt, - history, - chatbot, - token_count, - top_p, - temperature, - use_streaming_checkbox, - model_select_dropdown, - language_select_dropdown, - ], - [chatbot, history, status_display, token_count], - show_progress=True, - ).then(**end_outputing_args) - retryBtn.click(**get_usage_args) - - delFirstBtn.click( - delete_first_conversation, - [history, token_count], - [history, token_count, status_display], - ) - - delLastBtn.click( - delete_last_conversation, - [chatbot, history, token_count], - [chatbot, history, token_count, status_display], - show_progress=True, - ) - - reduceTokenBtn.click( - reduce_token_size, - [ - user_api_key, - systemPromptTxt, - history, - chatbot, - token_count, - top_p, - temperature, - gr.State(sum(token_count.value[-4:])), - model_select_dropdown, - language_select_dropdown, - ], - [chatbot, history, status_display, token_count], - show_progress=True, - ) - reduceTokenBtn.click(**get_usage_args) - - two_column.change(update_doc_config, [two_column], None) - - # ChatGPT - keyTxt.change(submit_key, keyTxt, [user_api_key, status_display]).then(**get_usage_args) - keyTxt.submit(**get_usage_args) - - # Template - 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, - [saveFileName, systemPromptTxt, history, chatbot, user_name], - downloadFile, - show_progress=True, - ) - saveHistoryBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown]) - exportMarkdownBtn.click( - export_markdown, - [saveFileName, systemPromptTxt, history, chatbot, user_name], - downloadFile, - show_progress=True, - ) - historyRefreshBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown]) - historyFileSelectDropdown.change( - load_chat_history, - [historyFileSelectDropdown, systemPromptTxt, history, chatbot, user_name], - [saveFileName, systemPromptTxt, history, chatbot], - show_progress=True, - ) - downloadFile.change( - load_chat_history, - [downloadFile, systemPromptTxt, history, chatbot, user_name], - [saveFileName, systemPromptTxt, history, chatbot], - ) - - # Advanced - 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 = "川虎ChatGPT 🚀" - -if __name__ == "__main__": - reload_javascript() - # if running in Docker - if dockerflag: - if authflag: - demo.queue(concurrency_count=CONCURRENT_COUNT).launch( - server_name="0.0.0.0", - server_port=7860, - auth=auth_list, - favicon_path="./assets/favicon.ico", - ) - else: - demo.queue(concurrency_count=CONCURRENT_COUNT).launch( - server_name="0.0.0.0", - server_port=7860, - share=False, - favicon_path="./assets/favicon.ico", - ) - # if not running in Docker - else: - if authflag: - demo.queue(concurrency_count=CONCURRENT_COUNT).launch( - share=False, - auth=auth_list, - favicon_path="./assets/favicon.ico", - inbrowser=True, - ) - else: - demo.queue(concurrency_count=CONCURRENT_COUNT).launch( - share=False, favicon_path="./assets/favicon.ico", inbrowser=True - ) # 改为 share=True 可以创建公开分享链接 - # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口 - # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码 - # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(auth=("在这里填写用户名", "在这里填写密码")) # 适合Nginx反向代理 diff --git a/spaces/qinzhu/diy-girlfriend-online/monotonic_align/core.py b/spaces/qinzhu/diy-girlfriend-online/monotonic_align/core.py deleted file mode 100644 index 1f940605fe4fd0738fa0006149fcba14ef88223a..0000000000000000000000000000000000000000 --- a/spaces/qinzhu/diy-girlfriend-online/monotonic_align/core.py +++ /dev/null @@ -1,36 +0,0 @@ -import numba - - -@numba.jit(numba.void(numba.int32[:, :, ::1], numba.float32[:, :, ::1], numba.int32[::1], numba.int32[::1]), - nopython=True, nogil=True) -def maximum_path_jit(paths, values, t_ys, t_xs): - b = paths.shape[0] - max_neg_val = -1e9 - for i in range(int(b)): - path = paths[i] - value = values[i] - t_y = t_ys[i] - t_x = t_xs[i] - - v_prev = v_cur = 0.0 - 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: - v_cur = max_neg_val - else: - v_cur = value[y - 1, x] - if x == 0: - if y == 0: - v_prev = 0. - else: - v_prev = max_neg_val - 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): - path[y, index] = 1 - if index != 0 and (index == y or value[y - 1, index] < value[y - 1, index - 1]): - index = index - 1 diff --git a/spaces/quidiaMuxgu/Expedit-SAM/All Roblox Dll Scripts.md b/spaces/quidiaMuxgu/Expedit-SAM/All Roblox Dll Scripts.md deleted file mode 100644 index 774dbcce6a381fbc706c028657499d1d0a0ced00..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/All Roblox Dll Scripts.md +++ /dev/null @@ -1,116 +0,0 @@ -
    -

    All Roblox Dll Scripts: Everything You Need to Know

    -

    If you are interested in exploiting, hacking or cheating in Roblox games, you might have heard of Roblox Dll Scripts. But what are they exactly, and how can you use them? In this article, we will explain everything you need to know about Roblox Dll Scripts, including what they are, how they work, where to get them, and how to create your own.

    -

    What are Roblox Dll Scripts?

    -

    Roblox Dll Scripts are files that contain code that can be injected into Roblox games using a Roblox exploit or executor. Dll stands for Dynamic Link Library, which is a type of file that can be loaded and executed by other programs. Roblox Dll Scripts can contain various functions and commands that can manipulate the game environment, such as changing variables, spawning objects, teleporting players, executing scripts, and more.

    -

    All Roblox Dll Scripts


    DOWNLOAD ❤❤❤ https://geags.com/2uCsRW



    -

    How do Roblox Dll Scripts work?

    -

    Roblox Dll Scripts work by using a Roblox exploit or executor to inject the code into the game process. A Roblox exploit is a program that can bypass the security measures of Roblox and execute code that is not authorized by the game developers. A Roblox executor is a program that can run Roblox Dll Scripts or other types of scripts, such as Lua or C++. Some examples of popular Roblox exploits and executors are Synapse X, KRNL, Hydroxide, TaaprWare, and Zeus X.

    -

    To use a Roblox Dll Script, you need to have a compatible Roblox exploit or executor installed on your computer. Then, you need to find and download a Roblox Dll Script that suits your needs. You can find many Roblox Dll Scripts on GitHub or other websites that host them. However, you should be careful when downloading Roblox Dll Scripts from unknown sources, as they might contain malware or viruses that can harm your computer or account.

    -

    Once you have downloaded a Roblox Dll Script, you need to open your Roblox exploit or executor and select the file. Then, you need to join a Roblox game and press a key or button to inject the code into the game. Depending on the script, you might see a user interface or a console that allows you to control the script's functions and commands. You can then use the script to exploit, hack or cheat in the game as you wish.

    -

    Where to get Roblox Dll Scripts?

    -

    There are many sources where you can get Roblox Dll Scripts for free or for a fee. Some of the most popular sources are:

    -
      -
    • GitHub: GitHub is a platform where developers can host and share their code projects. You can find many repositories that contain Roblox Dll Scripts on GitHub by searching for topics such as roblox-executor, roblox-exploiting, roblox-exploit, roblox-cheat, roblox-scripts, roblox-script, or roblox-dll. Some examples of GitHub repositories that contain Roblox Dll Scripts are rasyidrafi/Roblox-Exploit-DLL, Upbolt/Hydroxide, plusgiant5/TaaprWareV3, and OgeidCC/ROBLOX-ZEUS-X-EXPLOIT-2023.
    • -
    • Websites: There are many websites that host and share Roblox Dll Scripts for free or for a fee. Some of these websites might require you to complete surveys, watch ads, or enter keys to access the scripts. Some examples of websites that host and share Roblox Dll Scripts are v3rmillion.net, robloxsong.com/dll-scripts/, robloxdll.com/scripts/, and robloxdllscripts.com/.
    • -
    • Discord: Discord is a platform where users can communicate and interact with each other through text, voice, and video chat. You can find many Discord servers that are dedicated to Roblox exploiting, hacking or cheating. These servers might have channels where users can share their own or request others' Roblox Dll Scripts. Some examples of Discord servers that are related to Roblox exploiting are Finity UI Library (https://discord.gg/CenXcThBFv), Krnl Key Bypass (https://discord.gg/krnl), Hydrogen Executer (https://discord.gg/hydrogen), and Zeus X (https://discord.gg/zeusx).
    • -
    -

    How to create your own Roblox Dll Scripts?

    -

    If you want to create your own Roblox Dll Scripts, you need to have some knowledge of programming languages such as Lua or C++. You also need to have some tools such as a text editor (e.g., Notepad++), a compiler (e.g., Visual Studio), and a debugger (e.g., Cheat Engine). The process of creating your own Roblox Dll Scripts involves writing the code in your text editor, compiling it into a dll file using your compiler, and testing it using your debugger.

    -

    The code of your Roblox Dll Script should contain functions and commands that can interact with the game environment using the Roblox API. The Roblox API is a set of functions and variables that are available for developers to use in their scripts. You can find the documentation of the Roblox API on https://developer.roblox.com/en-us/api-reference.

    -

    Here is an example of a simple Roblox Dll Script that prints "Hello World" in the game chat:

    - -```c++ -#include - -// Define the function prototype for ExecuteScript -typedef int(__cdecl* ExecuteScript)(const char* script); - -// Declare a global variable for ExecuteScript -ExecuteScript executeScript; - -// Define the entry point function for the dll -BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason, - LPVOID lpvReserved) - - // Check if the dll is attached - if (fdwReason == DLL_PROCESS_ATTACH) - - // Get the base address of DataModel.dll - uintptr_t dataModelBase = (uintptr_t)GetModuleHandleA("DataModel.dll"); - - // Get the offset of ExecuteScript from DataModel.dll - uintptr_t executeScriptOffset = 0x1F9E0; - - // Calculate the address of ExecuteScript - uintptr_t executeScriptAddress = dataModelBase + executeScriptOffset; - - // Cast the address of ExecuteScript to a function pointer - executeScript = (ExecuteScript)executeScriptAddress; - - // Call ExecuteScript with "Hello World" as an argument - executeScript("print(\"Hello World\")"); - - - return TRUE; - -``` - -

    To compile this code into a dll file using Visual Studio:

    -

    -
      -
    1. Create a new project with Empty Project template.
    2. -
    3. Add a new source file with .cpp extension.
    4. -
    5. Paste the code into the source file.
    6. -
    7. Go to Project -> Properties -> Configuration Properties -> General.
    8. -
    9. Change Configuration Type to Dynamic Library (.dll).
    10. -
    11. Change Character Set to Use Multi-Byte Character Set.
    12. -
    13. Go to Build -> Build Solution.
    14. -
    15. Find the dll file in your project folder under Debug or Release subfolder.
    16. -
    - -

    To test this code using Cheat Engine:

    -
      -
    1. Open Cheat Engine and select robloxplayerbeta.exe as the process.
    2. -
    3. Go to Memory View -> Tools -> Inject DLL.
    4. -
    5. Select the dll file that you compiled.
    6. -
    7. Join any Roblox game and check the game chat for "Hello World".
    8. -
    - -

    This is just a basic example of how to create your own Roblox Dll Script. You can learn more about how to create more advanced and complex scripts by reading tutorials online or watching videos on YouTube.

    - -

    Conclusion

    - -

    In this article, we have covered everything you need to know about All Roblox Dll Scripts. We have explained what they are, how they work, where to get them, and how to create your own. We hope this article has been helpful and informative for you. If you have any questions or feedback, feel free to leave them in the comments below. Happy exploiting!

    -

    What are the benefits and risks of using Roblox Dll Scripts?

    -

    Using Roblox Dll Scripts can have some benefits and risks, depending on how you use them and what your intentions are. Some of the benefits are:

    -
      -
    • Fun and entertainment: Using Roblox Dll Scripts can make your gaming experience more fun and entertaining, as you can do things that are normally impossible or difficult to do in the game. You can also prank or troll other players, create your own mini-games, or explore hidden features of the game.
    • -
    • Learning and creativity: Using Roblox Dll Scripts can help you learn more about programming, game development, and hacking. You can also express your creativity by creating your own Roblox Dll Scripts or modifying existing ones.
    • -
    • Advantage and competition: Using Roblox Dll Scripts can give you an advantage over other players, especially in competitive games. You can gain access to cheats such as god mode, infinite money, speed hack, aimbot, wallhack, and more. You can also bypass some game restrictions or limitations, such as level requirements, cooldowns, or anti-cheat systems.
    • -
    -

    Some of the risks are:

    -
      -
    • Ban and punishment: Using Roblox Dll Scripts is against the Roblox Terms of Service and can result in your account being banned or terminated. You can also face other punishments such as losing your items, progress, or reputation. Roblox has various methods to detect and prevent exploiting, such as data analysis, moderation reports, anti-exploit scripts, and security updates.
    • -
    • Malware and virus: Using Roblox Dll Scripts from unknown or untrusted sources can expose your computer or account to malware or viruses that can harm your system or steal your information. You should always scan any files that you download with an antivirus program and avoid clicking on suspicious links or ads.
    • -
    • Backlash and hate: Using Roblox Dll Scripts can cause backlash and hate from other players, especially those who are affected by your actions. You might receive negative feedback, insults, threats, or reports from other players who dislike exploiting or cheating. You might also lose friends or respect from other players who value fair play and honesty.
    • -
    - -

    How to avoid getting banned for using Roblox Dll Scripts?

    -

    If you decide to use Roblox Dll Scripts despite the risks, you should take some precautions to avoid getting banned or detected by Roblox. Some of the precautions are:

    -
      -
    • Use a VPN: A VPN (Virtual Private Network) is a service that can hide your IP address and encrypt your internet traffic. This can help you avoid getting tracked or traced by Roblox or other authorities. You can find many free or paid VPN services online that you can use.
    • -
    • Use an alt account: An alt account is a secondary or alternative account that you can use for exploiting or cheating. This can help you protect your main account from getting banned or punished. You can create a new account with a different email address and username that is not linked to your main account.
    • -
    • Use a trusted exploit or executor: A trusted exploit or executor is a program that has been tested and verified by other users to be safe and effective. This can help you avoid using a program that contains malware or viruses or that does not work properly. You should always check the reviews, ratings, comments, and feedback of any exploit or executor that you use.
    • -
    • Use a stealthy script: A stealthy script is a script that has been designed to avoid detection or suspicion by Roblox or other players. This can help you avoid using a script that is obvious or blatant or that triggers anti-exploit systems. You should always check the features, functions, commands, and options of any script that you use.
    • -
    • Use common sense: Common sense is the ability to use good judgment and logic in different situations. This can help you avoid using Roblox Dll Scripts in a way that is harmful, disrespectful, abusive, or illegal. You should always follow the rules and guidelines of Roblox and any game that you play. You should also respect other players' rights and feelings.
    • -
    - -

    Conclusion

    - -

    In this article, we have covered everything you need to know about All Roblox Dll Scripts. We have explained what they are, how they work, where to get them, how to create your own, what are the benefits and risks of using them, and how to avoid getting banned for using them. We hope this article has been helpful and informative for you. If you have any questions or feedback, feel free to leave them in the comments below. Happy exploiting!

    -

    Conclusion

    - -

    In this article, we have covered everything you need to know about All Roblox Dll Scripts. We have explained what they are, how they work, where to get them, how to create your own, what are the benefits and risks of using them, and how to avoid getting banned for using them. We hope this article has been helpful and informative for you. If you have any questions or feedback, feel free to leave them in the comments below. Happy exploiting!

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Maple 18 Purchase Code Crack [CRACKED].md b/spaces/quidiaMuxgu/Expedit-SAM/Maple 18 Purchase Code Crack [CRACKED].md deleted file mode 100644 index 40abc2ab71fc6c651fcf4f3eba3018b8f6454187..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Maple 18 Purchase Code Crack [CRACKED].md +++ /dev/null @@ -1,22 +0,0 @@ -

    maple 18 purchase code crack


    Downloadhttps://geags.com/2uCr0C



    -
    -exe installation failed for some reason, please try to reinstall Maple 18. - -**Step 4.** In the input box, enter the absolute value of (1-α) in (2.1.1) and the exact value of α in (2.1.2) and then press the **Enter** key. You will be prompted to make the logical choice between the two alternatives. - -**Step 5.** Select the **true** alternative. If you selected **false**, you will need to reset this choice to **true** or **false** using the **Reset** button. - -**Step 6.** In the input box, enter the absolute value of (1-α) in (2.1.1) and the exact value of α in (2.1.2) and then press the **Enter** key. You will be prompted to make the logical choice between the two alternatives. - -**Step 7.** Select the **false** alternative. If you selected **true**, you will need to reset this choice to **true** or **false** using the **Reset** button. - -**Step 8.** If you selected the **true** alternative, press the **Reset** button. - -**Step 9.** Confirm the specified values by entering the values in the appropriate input boxes. The function **Optimal** will appear in the results box. You are now ready to perform the function's analysis. - -**Output 2.1:** Optimal Control Option for the CTGFCM Function - - results: 4fefd39f24
    -
    -
    -

    diff --git a/spaces/radames/UserControllableLT-Latent-Transformer/interface/pixel2style2pixel/models/stylegan2/op/fused_act.py b/spaces/radames/UserControllableLT-Latent-Transformer/interface/pixel2style2pixel/models/stylegan2/op/fused_act.py deleted file mode 100644 index 973a84fffde53668d31397da5fb993bbc95f7be0..0000000000000000000000000000000000000000 --- a/spaces/radames/UserControllableLT-Latent-Transformer/interface/pixel2style2pixel/models/stylegan2/op/fused_act.py +++ /dev/null @@ -1,85 +0,0 @@ -import os - -import torch -from torch import nn -from torch.autograd import Function -from torch.utils.cpp_extension import load - -module_path = os.path.dirname(__file__) -fused = load( - 'fused', - sources=[ - os.path.join(module_path, 'fused_bias_act.cpp'), - os.path.join(module_path, 'fused_bias_act_kernel.cu'), - ], -) - - -class FusedLeakyReLUFunctionBackward(Function): - @staticmethod - def forward(ctx, grad_output, out, negative_slope, scale): - ctx.save_for_backward(out) - ctx.negative_slope = negative_slope - ctx.scale = scale - - empty = grad_output.new_empty(0) - - grad_input = fused.fused_bias_act( - grad_output, empty, out, 3, 1, negative_slope, scale - ) - - dim = [0] - - if grad_input.ndim > 2: - dim += list(range(2, grad_input.ndim)) - - grad_bias = grad_input.sum(dim).detach() - - return grad_input, grad_bias - - @staticmethod - def backward(ctx, gradgrad_input, gradgrad_bias): - out, = ctx.saved_tensors - gradgrad_out = fused.fused_bias_act( - gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale - ) - - return gradgrad_out, None, None, None - - -class FusedLeakyReLUFunction(Function): - @staticmethod - def forward(ctx, input, bias, negative_slope, scale): - empty = input.new_empty(0) - out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) - ctx.save_for_backward(out) - ctx.negative_slope = negative_slope - ctx.scale = scale - - return out - - @staticmethod - def backward(ctx, grad_output): - out, = ctx.saved_tensors - - grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( - grad_output, out, ctx.negative_slope, ctx.scale - ) - - return grad_input, grad_bias, None, None - - -class FusedLeakyReLU(nn.Module): - def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5): - super().__init__() - - self.bias = nn.Parameter(torch.zeros(channel)) - self.negative_slope = negative_slope - self.scale = scale - - def forward(self, input): - return fused_leaky_relu(input, self.bias, self.negative_slope, self.scale) - - -def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): - return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Asus X16 96072 Iso Rapidshare Tips and Tricks for Installing Windows 7 on Your Computer.md b/spaces/raedeXanto/academic-chatgpt-beta/Asus X16 96072 Iso Rapidshare Tips and Tricks for Installing Windows 7 on Your Computer.md deleted file mode 100644 index d307ff6b44ebeb233a8ee8fdf748f88f58a5d012..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Asus X16 96072 Iso Rapidshare Tips and Tricks for Installing Windows 7 on Your Computer.md +++ /dev/null @@ -1,135 +0,0 @@ -
    -
    - The possible solutions and alternatives for obtaining a Windows 7 installation media.
    - The steps and precautions for downloading Asus X16 96072 Iso Rapidshare from a reliable source. | | H2: How to install Asus X16 96072 Iso Rapidshare? | - The requirements and preparations for installing Windows 7 Home Premium OA X16-96072 (64bit) on your Asus laptop.
    - The instructions and tips for installing Asus X16 96072 Iso Rapidshare using a DVD or a USB flash drive.
    - The activation and verification of your Windows 7 product key. | | H2: How to use Asus X16 96072 Iso Rapidshare? | - The features and benefits of Windows 7 Home Premium OA X16-96072 (64bit) on your Asus laptop.
    - The common issues and troubleshooting methods for Windows 7 Home Premium OA X16-96072 (64bit).
    - The best practices and recommendations for optimizing and maintaining your Windows 7 system. | | H1: Conclusion | - A summary of the main points and the key takeaways from the article.
    - A call to action and an invitation for feedback from the readers. | **Table 2: Article with HTML formatting**

    What is Asus X16 96072 Iso Rapidshare?

    -

    If you are a Windows 7 user who owns an Asus laptop, you might have heard of Asus X16 96072 Iso Rapidshare. But what is it exactly and why do you need it? In this article, we will explain everything you need to know about this topic and how you can download, install, and use it on your Asus laptop.

    -

    Asus X16 96072 Iso Rapidshare is a file name that refers to a specific version of Windows 7 Home Premium OA (Original Equipment Manufacturer Activation) that is designed for Asus laptops. This version of Windows 7 comes pre-installed on some Asus laptops and has a product key that is embedded in the BIOS (Basic Input Output System) of the laptop. This means that you do not need to enter a product key manually when you install or reinstall Windows 7 on your Asus laptop.

    -

    Asus X16 96072 Iso Rapidshare


    Download File · https://tinourl.com/2uKZ7N



    -

    However, there are some situations where you might need to download Asus X16 96072 Iso Rapidshare from the internet. For example, if your hard drive fails or gets corrupted, if you want to upgrade or replace your hard drive, if you want to perform a clean install of Windows 7, or if you want to create a backup or recovery disk for your system. In these cases, you will need a Windows 7 installation media that matches your product key and your laptop model.

    -

    Unfortunately, finding a legitimate download link for Asus X16 96072 Iso Rapidshare is not easy. Microsoft no longer provides Digital River downloads of Windows 7 ISO files, and most online sources are either unreliable, outdated, or infected with malware. So how can you download Asus X16 96072 Iso Rapidshare safely and legally? Let's find out in the next section.

    -

    How to download Asus X16 96072 Iso Rapidshare?

    -

    As we mentioned earlier, downloading Asus X16 96072 Iso Rapidshare from the internet is challenging and risky. However, there are some possible solutions and alternatives that you can try. Here are some of them:

    -
      -
    • Borrow a Windows 7 Home Premium retail or OEM System Builder DVD from a friend who has one. This is probably the easiest and cheapest option if you know someone who has a genuine copy of Windows 7 Home Premium that matches your product key. You can use their DVD to install Windows 7 on your Asus laptop and activate it with your product key. However, make sure that the DVD is not damaged or scratched, and that it has the same architecture (32-bit or 64-bit) as your laptop.
    • -
    • Request a backup media from Microsoft or Asus. This is another option that might work if you have proof of purchase and warranty for your Asus laptop. You can contact Microsoft or Asus customer support and request a backup media for your system. They might charge you a small fee for shipping and handling, but they will send you an official DVD or USB flash drive that contains Asus X16 96072 Iso Rapidshare. However, this option might take some time and might not be available in all regions.
    • -
    • Use Heidoc.net's Microsoft Windows and Office ISO Download Tool. This is a third-party tool that lets you download official ISO files of various versions of Windows and Office directly from Microsoft's servers. You can use this tool to download Asus X16 96072 Iso Rapidshare by selecting "Windows 7" as the edition, "Home Premium SP1" as the version, "English" as the language, and "x64" as the architecture. However, this tool might not always work properly, and you should scan the downloaded file with an antivirus program before using it.
    • -
    -

    Once you have downloaded Asus X16 96072 Iso Rapidshare from one of these sources, you will need to burn it to a DVD or create a bootable USB flash drive using a tool like Rufus. Then, you can proceed to install it on your Asus laptop following the instructions in the next section.

    -

    How to install Asus X16 96072 Iso Rapidshare?

    -

    Before you install Asus X16 96072 Iso Rapidshare on your Asus laptop, you will need to prepare some things:

    -
      -
    • A valid product key for Windows 7 Home Premium OA X16-96072 (64bit). You can find this product key on a sticker that is attached to the bottom or inside of your laptop. Alternatively, you can use a tool like NirSoft's ProduKey to retrieve it from your BIOS.
    • -
    • A backup of your important data. Installing Windows 7 will erase everything on your hard drive, so make sure that you have backed up all your personal files, documents, photos, music, videos, etc. to an external drive or cloud service before proceeding.
    • -
    • A compatible driver for your network adapter. After installing Windows 7, you will need to connect to the internet to activate it and download updates. However, some network adapters might not work properly with Windows 7 without installing a specific driver first. You can check if your network adapter is compatible with Windows 7 by visiting the manufacturer's website (such as Intel, Realtek, Broadcom, etc.) and downloading the latest driver for your device. Save this driver file to a USB flash drive or another external drive that you can access after installing Windows 7.
    • -
    -

    Once you have prepared these things, you can follow these steps to install Asus X16 96072 Iso Rapidshare on your Asus laptop:

    -
      -
    1. Insert the DVD or USB flash drive that contains Asus X16 96072 Iso Rapidshare into your laptop.
    2. -
    3. Restart your laptop and press F2 repeatedly during boot up to enter BIOS setup.
    4. -
    5. Go to Boot menu and change the boot order so that the DVD or USB flash drive is the first option.
    6. -
    7. Save changes and exit BIOS setup.
    8. -
    9. Your laptop will boot from the DVD or USB flash drive and start loading Windows files.
    10. -
    11. Select your language, time zone, keyboard layout, etc., and click Next.
    12. -
    13. Click Install now.
    14. -
    15. Accept the license terms and click Next.
    16. -
    17. Select Custom (advanced) as the installation type.
    18. -
    19. Delete all partitions on your hard drive by selecting each one and clicking Delete until only unallocated space remains.
    20. -
    21. Select the unallocated space and click Next.
    22. -
    23. The installation process will begin and might take several minutes depending on your hardware configuration.
    24. -
    25. When prompted, enter your product key and click Next.
    26. -
    27. Select whether you want to activate Windows automatically online or later manually by phone.
    28. -
    29. The installation process will continue until it finishes.
    30. -
    31. < b>Your laptop will restart several times during this process.
    32. -
    33. After the final restart, you will see the Windows 7 welcome screen.
    34. -
    35. Follow the on-screen instructions to set up your user account, network settings, time zone, etc.
    36. -
    37. Log in to your Windows 7 desktop and enjoy your new system.
    38. -
    -

    Congratulations, you have successfully installed Asus X16 96072 Iso Rapidshare on your Asus laptop. But you are not done yet. You still need to use it properly and fix any potential issues that might arise. Let's see how in the next section.

    -

    Asus X16 96072 Iso download link
    -How to install Asus X16 96072 Iso on laptop
    -Asus X16 96072 Iso torrent file
    -Asus X16 96072 Iso free full version
    -Asus X16 96072 Iso crack serial keygen
    -Asus X16 96072 Iso activation code
    -Asus X16 96072 Iso product key
    -Asus X16 96072 Iso system requirements
    -Asus X16 96072 Iso review and features
    -Asus X16 96072 Iso troubleshooting guide
    -Asus X16 96072 Iso customer support
    -Asus X16 96072 Iso warranty and refund policy
    -Asus X16 96072 Iso comparison with other models
    -Asus X16 96072 Iso best price and deals
    -Asus X16 96072 Iso discount coupon code
    -Asus X16 96072 Iso user manual and instructions
    -Asus X16 96072 Iso software updates and patches
    -Asus X16 96072 Iso compatible devices and accessories
    -Asus X16 96072 Iso testimonials and feedback
    -Asus X16 96072 Iso forum and community
    -Asus X16 96072 Iso alternatives and competitors
    -Asus X16 96072 Iso benefits and advantages
    -Asus X16 96072 Iso drawbacks and limitations
    -Asus X16 96072 Iso tips and tricks
    -Asus X16 96072 Iso FAQ and Q&A
    -How to backup and restore Asus X16 96072 Iso
    -How to uninstall and remove Asus X16 96072 Iso
    -How to customize and optimize Asus X16 96072 Iso
    -How to fix errors and bugs in Asus X16 96072 Iso
    -How to upgrade and update Asus X16 96072 Iso
    -How to burn and create Asus X16 96072 Iso DVD
    -How to boot and run Asus X16 96072 Iso from USB
    -How to recover and reset Asus X16 96072 Iso password
    -How to change and modify Asus X16 96072 Iso settings
    -How to repair and restore Asus X16 96072 Iso files
    -How to convert and format Asus X16 96072 Iso to other formats
    -How to clone and copy Asus X16 96072 Iso to another device
    -How to share and transfer Asus X16 96072 Iso online
    -How to stream and watch Asus X16 96072 Iso videos
    -How to play and enjoy Asus X16 96072 Iso games
    -How to learn and master Asus X16 96072 Iso skills
    -How to teach and train others with Asus X16 96072 Iso courses
    -How to make money with Asus X16 96072 Iso affiliate program
    -How to get traffic with Asus X16 96072 Iso SEO strategy
    -How to build a website with Asus X16 96072 Iso WordPress theme
    -How to create a blog with Asus X16 96072 Iso Blogger template
    -How to design a logo with Asus X16 96072 Iso Photoshop action
    -How to edit a photo with Asus X16 96072 Iso Lightroom preset
    -How to write a book with Asus X16 96072 Iso Scrivener template
    -How to compose a song with Asus X16 96072 Iso GarageBand loop

    -

    How to use Asus X16 96072 Iso Rapidshare?

    -

    Now that you have installed Asus X16 96072 Iso Rapidshare on your Asus laptop, you can start using it and exploring its features and benefits. Here are some of them:

    -
      -
    • Windows 7 Home Premium OA X16-96072 (64bit) is compatible with your Asus laptop model and product key. This means that you can enjoy a smooth and stable performance, as well as a genuine and legal Windows 7 license.
    • -
    • Windows 7 Home Premium OA X16-96072 (64bit) offers a user-friendly and customizable interface. You can personalize your desktop with themes, wallpapers, gadgets, icons, etc. You can also use the Aero effects, such as transparency, peek, snap, shake, and flip.
    • -
    • Windows 7 Home Premium OA X16-96072 (64bit) supports various multimedia and entertainment features. You can play DVDs, CDs, MP3s, videos, games, etc. You can also use Windows Media Center to watch TV, record shows, stream media, etc.
    • -
    • Windows 7 Home Premium OA X16-96072 (64bit) enhances your security and privacy. You can use Windows Defender, Firewall, Action Center, User Account Control, BitLocker, etc. to protect your system from viruses, malware, hackers, etc. You can also use Parental Controls to monitor and restrict your children's online activities.
    • -
    • Windows 7 Home Premium OA X16-96072 (64bit) improves your productivity and efficiency. You can use Windows Search, Taskbar, Start menu, Libraries, etc. to find and access your files and programs quickly. You can also use Windows Backup, Restore, Recovery, etc. to backup and restore your data and system settings.
    • -
    -

    However, no system is perfect and you might encounter some issues or problems while using Asus X16 96072 Iso Rapidshare on your Asus laptop. Don't worry, there are some ways to troubleshoot and fix them. Here are some of them:

    -
      -
    • Use Windows Update to download and install the latest updates for your system. This can help you fix some bugs, improve performance and compatibility, and enhance security and features. To use Windows Update, go to Start > Control Panel > System and Security > Windows Update > Check for updates.
    • -
    • Use the built-in troubleshooters to diagnose and solve common problems. Windows 7 has various troubleshooters that can help you with issues related to network, sound, display, printer, power, etc. To use them, go to Start > Control Panel > System and Security > Troubleshoot common computer problems > Select a troubleshooter > Run.
    • -
    • Use the System File Checker tool to scan and repair corrupted system files. Sometimes, your system files might get damaged or corrupted due to malware infection or improper shutdown. This can cause errors or crashes in your system. To fix this, you can use the System File Checker tool to scan and repair your system files. To use it, go to Start > All Programs > Accessories > Right-click Command Prompt > Run as administrator > Type sfc /scannow > Press Enter.
    • -
    -

    These are just some of the ways to use and troubleshoot Asus X16 96072 Iso Rapidshare on your Asus laptop. Of course, there are many more things you can do with your system depending on your needs and preferences. The important thing is to keep your system updated and secure, and to enjoy your Asus X16 96072 Iso Rapidshare experience.

    -

    Conclusion

    -

    In this article, we have learned what Asus X16 96072 Iso Rapidshare is, how to download it, how to install it, and how to use it on your Asus laptop. We have also learned some tips and tricks to troubleshoot and optimize your Windows 7 system. We hope that this article has been helpful and informative for you, and that you have gained some valuable knowledge and skills from it.

    -

    If you have any questions, comments, or feedback about this article, please feel free to share them with us. We would love to hear from you and help you with any issues or problems you might have. You can also check out our other articles on Windows 7 and other topics related to computers and technology. Thank you for reading and have a great day!

    -

    FAQs

    -

    Here are some frequently asked questions about Asus X16 96072 Iso Rapidshare and Windows 7:

    -
      -
    1. What is the difference between Windows 7 Home Premium OA and Windows 7 Home Premium?
      -Windows 7 Home Premium OA is a version of Windows 7 Home Premium that comes pre-installed on some laptops from certain manufacturers, such as Asus. OA stands for Original Equipment Manufacturer Activation, which means that the product key is embedded in the BIOS of the laptop and does not need to be entered manually when installing or reinstalling Windows 7. Windows 7 Home Premium is a retail or OEM System Builder version of Windows 7 Home Premium that can be purchased separately and installed on any compatible computer.
    2. -
    3. Can I use Asus X16 96072 Iso Rapidshare on another laptop or computer?
      -No, you cannot use Asus X16 96072 Iso Rapidshare on another laptop or computer, unless it is the same model as your original Asus laptop. This is because Asus X16 96072 Iso Rapidshare is tied to your specific product key and BIOS, which are unique to your laptop. If you try to use it on another laptop or computer, you will get an error message saying that your product key is invalid or not genuine.
    4. -
    5. Can I upgrade from Windows 7 Home Premium OA X16-96072 (64bit) to Windows 10?
      -Yes, you can upgrade from Windows 7 Home Premium OA X16-96072 (64bit) to Windows 10, as long as your laptop meets the minimum system requirements for Windows 10. However, you will need to purchase a valid license for Windows 10, as your existing product key for Windows 7 will not work for Windows 10. You can purchase a license for Windows 10 from Microsoft's website or from a trusted retailer. You can also use Microsoft's Media Creation Tool to create a bootable USB flash drive or DVD with Windows 10 installation files.
    6. -
    7. How can I find out more information about my Asus laptop model and specifications?
      -You can find out more information about your Asus laptop model and specifications by visiting Asus's official website and entering your laptop's serial number or model name in the search box. You can also use a tool like Speccy to scan your laptop's hardware and software details.
    8. -
    9. How can I contact Microsoft or Asus customer support if I need help with Asus X16 96072 Iso Rapidshare or Windows 7?
      -You can contact Microsoft or Asus customer support if you need help with Asus X16 96072 Iso Rapidshare or Windows 7 by visiting their respective websites and following their instructions. You can also call their toll-free numbers or chat with their online agents. Here are some links and numbers for your convenience:
    10. -
    -
      -
    • Microsoft Support: https://support.microsoft.com/en-us/contactus/
      Phone: +1-800-642-7676
    • -
    • Asus Support: https://www.asus.com/support/
      Phone: +1-888-678-3688
    • -
    -

    0a6ba089eb
    -
    -
    \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/BISE Lahore Matric Result 2015 Gazette Download Best Practices and Common Mistakes.md b/spaces/raedeXanto/academic-chatgpt-beta/BISE Lahore Matric Result 2015 Gazette Download Best Practices and Common Mistakes.md deleted file mode 100644 index 35cd167b41b6a614fcdba9cda99998033580fd00..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/BISE Lahore Matric Result 2015 Gazette Download Best Practices and Common Mistakes.md +++ /dev/null @@ -1,91 +0,0 @@ - -

    BISE Lahore Matric Result 2015 Gazette Download

    -

    If you are looking for the BISE Lahore matric result 2015 gazette download, you have come to the right place. In this article, we will tell you what is BISE Lahore, what is matric result gazette, why you should download it, and how to download and view it. So, let's get started.

    -

    Introduction

    -

    Matriculation is a crucial stage in the academic career of every student in Pakistan. It determines their future prospects and opportunities. Therefore, it is important to know your matric result as soon as possible. But how can you do that? Well, one way is to download the matric result gazette from the official website of your board of intermediate and secondary education (BISE).

    -

    bise lahore matric result 2015 gazette download


    Download File ⚹⚹⚹ https://tinourl.com/2uL1JG



    -

    What is BISE Lahore?

    -

    BISE Lahore is one of the nine boards of intermediate and secondary education in Punjab province. It was established in 1954 and is responsible for conducting exams and announcing results for matriculation (class 10) and intermediate (class 12) students in Lahore district and its affiliated areas. BISE Lahore has a reputation for being one of the most transparent and fair boards in Pakistan.

    -

    What is matric result gazette?

    -

    A matric result gazette is a document that contains the complete list of all the students who appeared in the matric exam along with their marks, grades, and positions. It also shows the statistics of pass percentage, merit list, top position holders, and subject-wise analysis. A matric result gazette is issued by each board after announcing the matric result online.

    -

    Why download matric result gazette 2015?

    -

    There are many reasons why you might want to download the matric result gazette 2015 from BISE Lahore. Some of them are:

    -
      -
    • You can check your own result as well as your friends' and classmates' results.
    • -
    • You can compare your performance with other students and see where you stand.
    • -
    • You can verify your marks and grades and report any discrepancy or error to the board.
    • -
    • You can use it as a proof of your result for admission or scholarship purposes.
    • -
    • You can keep it as a record or souvenir of your achievement.
    • -
    -

    How to download BISE Lahore matric result 2015 gazette?

    -

    Downloading the BISE Lahore matric result 2015 gazette is very easy and simple. Just follow these steps:

    -

    How to download bise lahore matric result 2015 gazette
    -Bise lahore matric result 2015 gazette pdf download
    -Bise lahore board matric result 2015 gazette download
    -Bise lahore matric result 2015 gazette online download
    -Bise lahore matric result 2015 gazette free download
    -Bise lahore matric result 2015 gazette download link
    -Bise lahore matric result 2015 gazette download website
    -Bise lahore matric result 2015 gazette download official
    -Bise lahore matric result 2015 gazette download by roll number
    -Bise lahore matric result 2015 gazette download by name
    -Bise lahore matric result 2015 gazette download by school
    -Bise lahore matric result 2015 gazette download by district
    -Bise lahore matric result 2015 gazette download by position
    -Bise lahore matric result 2015 gazette download by marks
    -Bise lahore matric result 2015 gazette download by percentage
    -Bise lahore matric result 2015 gazette download by grade
    -Bise lahore matric result 2015 gazette download by subject
    -Bise lahore matric result 2015 gazette download by group
    -Bise lahore matric result 2015 gazette download by category
    -Bise lahore matric result 2015 gazette download by gender
    -Bise lahore matric result 2015 gazette download with photo
    -Bise lahore matric result 2015 gazette download with signature
    -Bise lahore matric result 2015 gazette download with verification
    -Bise lahore matric result 2015 gazette download with certificate
    -Bise lahore matric result 2015 gazette download with marksheet
    -Bise lahore matric result 2015 gazette download with merit list
    -Bise lahore matric result 2015 gazette download with toppers list
    -Bise lahore matric result 2015 gazette download with statistics
    -Bise lahore matric result 2015 gazette download with analysis
    -Bise lahore matric result 2015 gazette download with comparison
    -Bise lahore matric result 2015 gazette download latest update
    -Bise lahore matric result 2015 gazette download news report
    -Bise lahore matric result 2015 gazette download announcement date
    -Bise lahore matric result 2015 gazette download error fix
    -Bise lahore matric result 2015 gazette download troubleshooting guide
    -Bise lahore matric result 2015 gazette download alternative source
    -Bise lahore matric result 2015 gazette download best method
    -Bise lahore matric result 2015 gazette download tips and tricks
    -Bise lahore matric result 2015 gazette download review and feedback
    -Bise lahore matric result 2015 gazette download pros and cons

    -

    Step 1: Visit the official website of BISE Lahore

    -

    The first step is to visit the official website of BISE Lahore at www.biselahore.com. This is where you will find all the information and updates related to BISE Lahore.

    -

    Step 2: Click on the results tab

    -

    The next step is to click on the results tab on the top menu bar of the website. This will take you to a page where you can access different types of results such as online results, rechecking results, supplementary results, etc.

    -

    Step 3: Select matric result gazette 2015 from the dropdown menu

    -

    The third step is to select matric result gazette 2015 from the dropdown menu under the online results section. This will open a new page where you can download the PDF file of the matric result gazette 2015.

    -

    Step 4: Enter your roll number or name

    -

    The fourth step is to enter your roll number or name in the search box provided on the page. This will help you to find your result quickly and easily. You can also leave the search box blank if you want to download the whole gazette.

    -

    Step 5: Download and save the PDF file

    -

    The final step is to download and save the PDF file of the matric result gazette 2015 on your device. You can do this by clicking on the download button at the bottom right corner of the page. The file size is about 50 MB so it might take some time depending on your internet speed.

    -

    How to view BISE Lahore matric result 2015 gazette?

    -

    Once you have downloaded the BISE Lahore matric result 2015 gazette, you can view it anytime offline. Here is how:

    -

    Open the PDF file with a PDF reader

    -

    To open the PDF file, you need a PDF reader software such as Adobe Acrobat Reader or Foxit Reader. You can install these software for free from their respective websites. Alternatively, you can also use an online PDF viewer such as Google Docs or Microsoft Word Online.

    -

    Search for your roll number or name

    -

    Check your marks, grades, and position

    -

    To check your marks, grades, and position in the PDF file, you can look at the columns next to your roll number or name. The columns show your marks obtained in each subject, total marks obtained out of 1100, percentage obtained out of 100%, grade obtained (A+, A, B, C, D), position obtained in district or board level (if any), remarks (pass/fail), and institution name (if any).

    -

    Conclusion

    -

    In this article, we have explained what is BISE Lahore, what is matric result gazette, why you should download it, and how to download and view it. We hope that this article has helped you to get your BISE Lahore matric result 2015 gazette download easily and conveniently. If you have any questions or feedback, please feel free to leave a comment below. We wish you all the best for your future endeavors.

    -

    FAQs

    -
      -
    1. When was BISE Lahore matric result 2015 announced?
      The BISE Lahore matric result 2015 was announced on July 25th, 2015 at 10:00 am.
    2. -
    3. How many students appeared in BISE Lahore matric exam 2015?
      A total of 312645 students appeared in BISE Lahore matric exam 2015 out of which 226134 passed with a pass percentage of 72.34%.
    4. -
    5. Who were the top position holders in BISE Lahore matric exam 2015?
      The top position holders in BISE Lahore matric exam 2015 were Rana Umar Farman (1087 marks), Muhammad Shayan Waheed (1086 marks), Syed Momin Ali (1086 marks), Rida Amir (1086 marks), Muhammad Omer Saleem (1086 marks), Ayesha Khalid (1086 marks), Anam Faryal (1086 marks), Muhammad Abdullah Saleem (1086 marks), Muhammad Abdullah Tariq (1086 marks), Muhammad Huzaifa Akhtar (1086 marks), Arooj Arshad (1086 marks), Zainab Iftikhar (1086 marks), Zunaira Khan (1086 marks), Ayesha Mustafa (1086 marks), Areeba Fatima (1086 marks).
    6. -
    7. How can I get a hard copy of BISE Lahore matric result gazette 2015?
      You can get a hard copy of BISE Lahore matric result gazette 2015 by visiting the board office or any authorized bookshop. You can also print it from the PDF file if you have a printer.
    8. -
    9. What if I have lost my roll number or name?
      If you have lost your roll number or name, you can still download and view the BISE Lahore matric result gazette 2015 by using the search function of your PDF reader software or online PDF viewer. You can also contact the board office or your institution for assistance.
    10. -
    -

    0a6ba089eb
    -
    -
    \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Deadpool (English) 3 In Hindi Download The Ultimate Guide for Fans of the Deadpool Franchise.md b/spaces/raedeXanto/academic-chatgpt-beta/Deadpool (English) 3 In Hindi Download The Ultimate Guide for Fans of the Deadpool Franchise.md deleted file mode 100644 index cb0a2f3106f551f8c1a5972a851afbee25cc93c3..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Deadpool (English) 3 In Hindi Download The Ultimate Guide for Fans of the Deadpool Franchise.md +++ /dev/null @@ -1,88 +0,0 @@ -
    -

    Deadpool 3 In Hindi Download: Everything You Need to Know

    -

    If you are a fan of superhero movies, especially the ones that are funny, violent, and meta, then you must be excited for Deadpool 3. The third installment of the popular franchise starring Ryan Reynolds as the "merc with a mouth" is coming soon to the big screen, and it promises to be a blast. But what if you want to watch it in Hindi? Don't worry, we have got you covered. In this article, we will tell you everything you need to know about Deadpool 3 in Hindi download, including what it is about, who are the cast and crew, when and where you can watch it, and why you should watch it. So, let's get started!

    -

    What is Deadpool 3 about?

    -

    Deadpool 3 is the sequel to Deadpool (2016) and Deadpool 2 (2018), which are based on the Marvel Comics character of the same name. Deadpool is a former special forces operative turned mercenary who undergoes a rogue experiment that gives him accelerated healing powers and a twisted sense of humor. He uses his abilities and skills to hunt down the people who ruined his life and to save the world from various threats.

    -

    Deadpool (English) 3 In Hindi Download


    Download File » https://tinourl.com/2uL2a0



    -

    Little plot details have been disclosed for Deadpool 3, but we do know some things that will make it different from the previous movies. Here are two of them:

    -

    The return of Wolverine

    -

    One of the most exciting news about Deadpool 3 is that Wolverine will be joining the action. Yes, you heard that right. Hugh Jackman, who played the iconic X-Men character for almost two decades, will reprise his role as Logan for Deadpool 3. This will mark his first appearance in a Marvel movie since Logan (2017), which was his final outing as Wolverine.

    -

    Wolverine and Deadpool have a long history in the comics and the movies. They first met in X-Men Origins: Wolverine (2009), where Deadpool was portrayed as a mute and disfigured experiment of Weapon X. They fought each other in a climactic battle that ended with Wolverine decapitating Deadpool. However, Deadpool survived thanks to his healing factor and made fun of Wolverine's movie at the end credits.

    -

    In Deadpool (2016), Deadpool mentioned Wolverine several times, mocking his accent, his claws, and his popularity. He also tried to get help from the X-Men to fight Ajax, but only Colossus and Negasonic Teenage Warhead showed up. He also joked about having sex with Wolverine in exchange for an Oscar nomination.

    -

    In Deadpool 2 (2018), Deadpool continued to make fun of Wolverine, especially after Logan's death in his own movie. He also traveled back in time to kill his previous version from X-Men Origins: Wolverine and to save Logan from dying in Logan.

    -

    In Deadpool 3, Wolverine and Deadpool will finally team up for some action-packed and hilarious adventures. According to sources, Wolverine's role will be more than just a cameo, and he will have a significant impact on the plot. The movie will be set before the events of Logan, so we will see a younger and more energetic Logan than before.

    -

    Deadpool 3 Hindi Dubbed Full Movie Download
    -Deadpool 3 Dual Audio 720p Download
    -Deadpool 3 (2024) Hindi-English Movie Watch Online
    -How to Download Deadpool 3 in Hindi for Free
    -Deadpool 3 Hindi Trailer and Release Date
    -Deadpool 3 Marvel Studios Movie in Hindi
    -Deadpool 3 and Wolverine Crossover in Hindi
    -Deadpool 3 HD Quality Download in Hindi
    -Deadpool 3 (2024) IMDb Rating and Review in Hindi
    -Deadpool 3 Hindi Subtitles Download
    -Deadpool 3 Full Movie in Hindi on Netflix
    -Deadpool 3 Hindi Audio Track Download
    -Deadpool 3 Director Shawn Levy Interview in Hindi
    -Deadpool 3 Cast and Characters in Hindi
    -Deadpool 3 Movie Story and Plot in Hindi
    -Deadpool 3 Hindi Dubbing Voice Actors
    -Deadpool 3 Filming Locations and Behind the Scenes in Hindi
    -Deadpool 3 Movie Songs and Soundtrack in Hindi
    -Deadpool 3 Movie Memes and Jokes in Hindi
    -Deadpool 3 Movie Quotes and Dialogues in Hindi
    -Deadpool 3 Movie Easter Eggs and References in Hindi
    -Deadpool 3 Movie Fan Theories and Predictions in Hindi
    -Deadpool 3 Movie Spoilers and Ending Explained in Hindi
    -Deadpool 3 Movie Comparison with Comics and Previous Movies in Hindi
    -Deadpool 3 Movie Awards and Nominations in Hindi

    -

    The first R-rated MCU movie

    -

    Another thing that makes Deadpool 3 unique is that it will be the first R-rated movie in the Marvel Cinematic Universe (MCU). The MCU is the shared universe of superhero movies produced by Marvel Studios, which includes franchises like Iron Man, Captain America, Thor, Avengers, Spider-Man, Black Panther, Doctor Strange, Guardians of the Galaxy, Ant-Man, Captain Marvel, Black Widow, Shang-Chi, Eternals, and more.

    -

    The MCU movies are known for their family-friendly tone and PG-13 rating, which means they have some violence, language, and sexual references, but nothing too graphic or explicit. However, Deadpool 3 will break that mold by being rated R, which means it will have more violence, gore, profanity, and nudity than any other MCU movie.

    -

    This is possible because Disney acquired 20th Century Fox in March 2019, which gave them the rights to use characters like Deadpool, X-Men, Fantastic Four, and others that were previously owned by Fox. However, Disney also promised to respect the creative vision of Fox's properties and not interfere with their tone or style.

    -

    Marvel Studios boss Kevin Feige confirmed that Deadpool 3 will be rated R and that it will be part of the MCU. He also said that Ryan Reynolds is overseeing the script and that he is excited to see him bring the character to life.

    -

    Who are the cast and crew of Deadpool 3?

    -

    Deadpool 3 has a talented cast and crew behind it. Here are some of them:

    -

    Ryan Reynolds as Deadpool

    -

    Ryan Reynolds is the star and producer of Deadpool 3. He plays Wade Wilson aka Deadpool, a sarcastic and fourth-wall-breaking antihero who can heal from any injury and has a penchant for violence and humor. Reynolds has been passionate about playing Deadpool for over a decade and has been involved in every aspect of making the movies. He also wrote a Deadpool Christmas movie while waiting for Deadpool 3 to start filming.

    -

    Hugh Jackman as Wolverine

    -

    Hugh Jackman is the guest star of Deadpool 3. He plays James Howlett aka Logan aka

    Shawn Levy as director

    -

    Shawn Levy is the director of Deadpool 3. He is a Canadian film director, producer, writer, and actor, who is best known for his work on comedy and family films like Cheaper by the Dozen, The Pink Panther, Night at the Museum, and The Internship. He is also the founder and principal of 21 Laps Entertainment, a production company that has produced films like Arrival, The Spectacular Now, Love and Monsters, and Free Guy.

    -

    Levy has collaborated with Ryan Reynolds before on Free Guy and The Adam Project, both of which are sci-fi comedy films. He has also worked on several television projects, such as Stranger Things, Shadow and Bone, Dash & Lily, and Unsolved Mysteries. He was hired to direct Deadpool 3 in November 2020, after David Leitch, who directed Deadpool 2, was unavailable due to scheduling conflicts.

    -

    Wendy Molyneux and Lizzie Molyneux-Loeglin as writers

    -

    Wendy Molyneux and Lizzie Molyneux-Loeglin are the writers of Deadpool 3. They are sisters and comedy writers who have been working on the animated sitcom Bob's Burgers since 2012. They have won two Emmy Awards for their work on the show and have also written episodes for The Great North and Solar Opposites.

    -

    The Molyneux sisters were chosen to write Deadpool 3 in November 2020, after Ryan Reynolds met with several writers to find the right fit for the project. They are also working on a live-action adaptation of The Hitchhiker's Guide to the Galaxy for Hulu.

    -

    When and where can you watch Deadpool 3 in Hindi?

    -

    Deadpool 3 is expected to hit theaters on November 8, 2024. However, due to the ongoing COVID-19 pandemic and its impact on the film industry, this date may change in the future. So, keep an eye out for any updates or announcements from Marvel Studios or Disney.

    -

    If you want to watch Deadpool 3 in Hindi, you will have to wait a little longer than the English version. Usually, Hindi-dubbed versions of Hollywood movies are released a few weeks or months after the original release date. For example, Deadpool 2 was released in English on May 18, 2018, but its Hindi version was released on June 1, 2018.

    -

    You can watch Deadpool 3 in Hindi either in theaters or on streaming platforms. However, not all theaters or platforms may offer Hindi-dubbed versions of the movie. So, you will have to check with your local theater or streaming service provider before you book your tickets or subscriptions.

    -

    Some of the streaming platforms that may offer Deadpool 3 in Hindi are Disney+ Hotstar, , Netflix, and YouTube. However, these platforms may have different availability and pricing for Deadpool 3 in Hindi. So, you will have to compare and choose the best option for you.

    -

    Why should you watch Deadpool 3 in Hindi?

    -

    Deadpool 3 in Hindi is not just a translation of the original English version. It is a whole new experience that adds more flavor and fun to the movie. Here are some reasons why you should watch Deadpool 3 in Hindi:

    -

    The humor and action of Deadpool

    -

    Deadpool is known for his witty and irreverent humor that breaks the fourth wall and makes fun of everything and everyone, including himself, other superheroes, pop culture, and even the audience. He also delivers some hilarious one-liners and catchphrases that make you laugh out loud. Watching Deadpool 3 in Hindi will give you a chance to enjoy his humor in a different language and with a different accent.

    -

    But Deadpool is not just about jokes. He is also a badass fighter who can take on any enemy with his swords, guns, and explosives. He also has some amazing stunts and choreography that make the action scenes thrilling and entertaining. Watching Deadpool 3 in Hindi will let you witness his action-packed adventures in a more immersive way.

    -

    The crossover with the MCU

    -

    Deadpool 3 is not just a standalone movie. It is also a crossover with the MCU, which is the biggest and most successful superhero franchise in the world. The MCU has introduced dozens of characters and stories that have captivated millions of fans around the globe. Watching Deadpool 3 in Hindi will allow you to see how Deadpool interacts with the MCU characters and events, and how he brings his own style and flavor to them.

    -

    For example, you will get to see how Deadpool reacts to meeting Wolverine again after their previous encounters. You will also get to see how Deadpool deals with being part of a larger universe that has rules and regulations that he may not like or follow. And you will also get to see how Deadpool references and parodies other MCU movies and characters that you may be familiar with.

    -

    Conclusion

    -

    Deadpool 3 is one of the most anticipated movies of 2024. It is the third movie of the Deadpool franchise and the first R-rated movie of the MCU. It stars Ryan Reynolds as Deadpool and Hugh Jackman as Wolverine, who team up for some hilarious and action-packed adventures. It is directed by Shawn Levy and written by Wendy Molyneux and Lizzie Molyneux-Loeglin.

    -

    If you want to watch Deadpool 3 in Hindi, you will have to wait for its release date on November 8, 2024, and check with your local theater or streaming platform for its availability and pricing. Watching Deadpool 3 in Hindi will give you a different and enjoyable experience that will make you laugh, cheer, and marvel at the movie.

    -

    So, are you ready for Deadpool 3 in Hindi? If yes, then mark your calendars and get ready for some fun!

    -

    FAQs

    -

    Here are some frequently asked questions about Deadpool 3 in Hindi:

    -
      -
    1. Is Deadpool 3 dubbed or subtitled in Hindi?
    2. -

      Deadpool 3 in Hindi is dubbed, which means that the original English dialogue is replaced by Hindi dialogue spoken by different voice actors. Subtitles are also available for those who prefer to read along.

      -
    3. Who are the voice actors for Deadpool 3 in Hindi?
    4. -

      The voice actors for Deadpool 3 in Hindi have not been announced yet, but they are expected to be some of the best and most popular voice actors in India. For example, Sanket Mhatre voiced Deadpool in the previous movies, while Viraj Adhav voiced Wolverine.

      -
    5. Will Deadpool 3 in Hindi have any censorship or cuts?
    6. -of the Central Board of Film Certification (CBFC) in India, which is responsible for rating and certifying movies for public exhibition. The CBFC may require some changes or removals of scenes or dialogues that are considered inappropriate or offensive for the Indian audience. However, these changes or cuts are usually minimal and do not affect the overall quality or enjoyment of the movie.

      -
    7. How can I watch Deadpool 3 in Hindi online?
    8. -

      You can watch Deadpool 3 in Hindi online on various streaming platforms that offer Hindi-dubbed versions of Hollywood movies. Some of these platforms are Disney+ Hotstar, Amazon Prime Video, Netflix, and YouTube. However, you will have to check their availability and pricing for Deadpool 3 in Hindi before you subscribe or rent the movie.

      -
    9. What are some other movies like Deadpool 3 in Hindi?
    10. -

      If you like Deadpool 3 in Hindi, you may also like some other movies that are similar in genre, tone, or style. Some of these movies are Guardians of the Galaxy, Thor: Ragnarok, Kingsman: The Secret Service, Kick-Ass, and Shazam!

      -

      -

      Thank you for reading this article on Deadpool 3 in Hindi download. I hope you found it informative and entertaining. If you have any questions or feedback, please feel free to leave a comment below. And don't forget to share this article with your friends and family who may be interested in watching Deadpool 3 in Hindi. Have a great day!

      0a6ba089eb
      -
      -
      \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Download Desain Kartu Nama Coreldraw 10 Template Kartu Nama Modern dan Minimalis.md b/spaces/raedeXanto/academic-chatgpt-beta/Download Desain Kartu Nama Coreldraw 10 Template Kartu Nama Modern dan Minimalis.md deleted file mode 100644 index a079cd4f3aff3d85293b626e57a988371178236b..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Download Desain Kartu Nama Coreldraw 10 Template Kartu Nama Modern dan Minimalis.md +++ /dev/null @@ -1,153 +0,0 @@ - -

      ESET NOD32 Antivirus v12.1.31.0 Crack: A Review

      -

      If you are looking for a reliable and effective antivirus software for your Windows PC, you might have heard of ESET NOD32 Antivirus. It is one of the most popular antivirus programs in the market, with over 110 million users worldwide. But what if you don't want to pay for it? Is there a way to get it for free? In this article, we will review ESET NOD32 Antivirus v12.1.31.0 Crack, a modified version of the software that claims to bypass the activation process and provide you with unlimited access to all its features. But before we dive into that, let's first understand what ESET NOD32 Antivirus is and why it is so popular.

      -

      What is ESET NOD32 Antivirus?

      -

      ESET NOD32 Antivirus is a comprehensive security solution that protects your PC from various types of malware, such as viruses, worms, trojans, spyware, ransomware, adware, rootkits, and more. It uses advanced heuristic analysis and cloud-based scanning to detect and block new and unknown threats before they can harm your system. It also offers features such as:

      -

      ESET NOD32 Antivirus v12.1.31.0 Crack


      Download Zip ✑ ✑ ✑ https://tinourl.com/2uL4uD



      -

      Features and benefits of ESET NOD32 Antivirus

      -
        -
      • Anti-Phishing: It prevents you from falling victim to phishing scams that try to steal your personal information or money by posing as legitimate websites or emails.
      • -
      • Gamer Mode: It automatically switches to a silent mode when you are playing games or watching videos, so that you can enjoy them without interruptions or slowdowns.
      • -
      • UEFI Scanner: It scans the firmware of your PC for potential threats that could compromise your boot process or data.
      • -
      • Exploit Blocker: It blocks attacks that try to exploit vulnerabilities in your applications or system.
      • -
      • Ransomware Shield: It monitors the behavior of suspicious processes and blocks them from encrypting your files or demanding ransom.
      • -
      • Device Control: It allows you to control which devices can access your PC, such as USB drives, CDs, DVDs, cameras, etc.
      • -
      • Cloud-Powered Scanning: It speeds up the scanning process by using the power of ESET's cloud-based database, which contains information about millions of malware samples.
      • -
      -

      System requirements and compatibility of ESET NOD32 Antivirus

      -

      ESET NOD32 Antivirus is compatible with Windows 10, 8.1, 8, 7, Vista, and XP (Service Pack 3). It requires at least 512 MB of RAM and 320 MB of disk space. It also supports 32-bit and 64-bit systems.

      -

      What is a crack and why do people use it?

      -

      A crack is a modified version of a software that bypasses its activation or licensing process and allows users to use it for free or with unlimited features. People usually use cracks for various reasons, such as:

      -

      Advantages and disadvantages of using a crack

      - - - - - - - - - - - - - - - - - - - - - -
      AdvantagesDisadvantages
      - Saving money on buying the software- Violating the intellectual property rights of the software developers
      - Accessing all the features without any restrictions- Exposing your PC to malware infections or cyberattacks
      - Trying out the software before buying it- Missing out on updates or technical support from the software providers
      - Sharing the software with others who can't afford it- Facing legal consequences or penalties for piracy
      -

      Risks and consequences of using a crack

      -

      Using a crack may seem tempting, but it comes with many risks and consequences that could outweigh its benefits. Some of these are:

      -

      How to download ESET NOD32 Antivirus v12.1.31.0 Crack for free
      -ESET NOD32 Antivirus v12.1.31.0 Crack license key generator
      -ESET NOD32 Antivirus v12.1.31.0 Crack full version download
      -ESET NOD32 Antivirus v12.1.31.0 Crack activation code
      -ESET NOD32 Antivirus v12.1.31.0 Crack serial number
      -ESET NOD32 Antivirus v12.1.31.0 Crack patch
      -ESET NOD32 Antivirus v12.1.31.0 Crack torrent
      -ESET NOD32 Antivirus v12.1.31.0 Crack review
      -ESET NOD32 Antivirus v12.1.31.0 Crack features
      -ESET NOD32 Antivirus v12.1.31.0 Crack system requirements
      -ESET NOD32 Antivirus v12.1.31.0 Crack installation guide
      -ESET NOD32 Antivirus v12.1.31.0 Crack comparison with other antivirus software
      -ESET NOD32 Antivirus v12.1.31.0 Crack pros and cons
      -ESET NOD32 Antivirus v12.1.31.0 Crack customer support
      -ESET NOD32 Antivirus v12.1.31.0 Crack refund policy
      -ESET NOD32 Antivirus v12.1.31.0 Crack discount coupon
      -ESET NOD32 Antivirus v12.1.31.0 Crack alternative
      -ESET NOD32 Antivirus v12.1.31.0 Crack update
      -ESET NOD32 Antivirus v12.1.31.0 Crack malware removal test
      -ESET NOD32 Antivirus v12.1.31.0 Crack performance test
      -ESET NOD32 Antivirus v12.1.31.0 Crack compatibility test
      -ESET NOD32 Antivirus v12.1.31.0 Crack user feedback
      -ESET NOD32 Antivirus v12.1.31.0 Crack ratings and awards
      -ESET NOD32 Antivirus v12.1.31.0 Crack FAQs
      -ESET NOD32 Antivirus v12.1.31.0 Crack troubleshooting tips
      -ESET NOD32 Antivirus v12.1.31 crack vs original version
      -Benefits of using ESET NOD32 Antivirus v12 crack version
      -Risks of using ESET NOD32 Antivirus crack version
      -How to avoid detection by ESET when using crack version
      -How to uninstall ESET NOD32 Antivirus crack version completely
      -How to upgrade from ESET NOD32 Antivirus crack version to official version
      -How to get a free trial of ESET NOD32 Antivirus official version
      -How to renew your subscription for ESET NOD32 Antivirus official version
      -How to contact ESET for technical support or feedback
      -How to join the ESET community and share your experience with other users
      -How to report a false positive or a bug in ESET NOD32 Antivirus software
      -How to submit a sample of a suspicious file or website to ESET for analysis
      -How to enable or disable various features and settings in ESET NOD32 Antivirus software
      -How to scan your computer or device with ESET NOD32 Antivirus software
      -How to schedule a scan or update with ESET NOD32 Antivirus software
      -How to create a custom scan or update profile with ESET NOD32 Antivirus software
      -How to use the quarantine and restore functions in ESET NOD32 Antivirus software
      -How to use the log and report functions in ESET NOD32 Antivirus software
      -How to use the parental control and anti-theft functions in ESET NOD32 Antivirus software (if applicable)
      -How to use the firewall and network protection functions in ESET NOD32 Antivirus software (if applicable)
      -How to use the anti-phishing and anti-spam functions in ESET NOD32 Antivirus software (if applicable)
      -How to use the gamer mode and battery saver mode in ESET NOD32 Antivirus software (if applicable)
      -How to use the cloud-powered reputation system and advanced heuristics in ESET NOD32 Antivirus software (if applicable)

      -
        -
      • Malware infections: Many cracks are infected with malware that can damage your system, steal your data, hijack your browser, display unwanted ads, or even lock your files and demand ransom.
      • -
      • Cyberattacks: Many cracks are hosted on shady websites that can expose your PC to hackers who can exploit its vulnerabilities and gain access to your personal information or financial accounts.
      • -
      • Lack of updates: Many cracks are outdated or incompatible with newer versions of the software or operating system, which can cause errors, crashes, or performance issues.
      • -
      • Lack of support: Many cracks are not supported by the software providers, which means you won't be able to get help if you encounter any problems or issues with the software.
      • -
      • Legal troubles: Many cracks are illegal and violate the intellectual property rights of the software developers, which means you could face lawsuits or fines for piracy.
      • -
      -

      How to download and install ESET NOD32 Antivirus v12.1.31.0 Crack?

      -

      If you still want to download and install ESET NOD32 Antivirus v12.1.31.0 Crack despite its risks and consequences, here are the steps you need to follow:

      -

      Step 1: Download the crack file from a reliable source

      -

      You can find many websites that offer ESET NOD32 Antivirus v12.1.31.0 Crack for free download, but not all of them are trustworthy or safe. Some may contain malware or viruses that can harm your PC or trick you into downloading unwanted programs or extensions. Therefore, you need to be careful and choose a reliable source that has positive reviews and feedback from other users. For example, you can try this website, which claims to provide a working crack file for ESET NOD32 Antivirus v12.1.31.0.

      -

      Step 2: Disable your antivirus and firewall temporarily

      -

      Before you download or install the crack file, you need to disable your antivirus and firewall temporarily, as they may detect it as a threat and block it from running or accessing your system. To do this, you need to go to your antivirus or firewall settings and turn off their protection features for a while. However, this also means that you are exposing your PC to other potential threats that may come from online sources or external devices.

      -

      Step 3: Extract the crack file and run the setup file

      -

      After you download the crack file, you need to extract it using a tool such as WinRAR or 7-Zip. You will find a folder containing several files inside it, such as a setup file, a license key file, an instruction file, etc. You need to run the setup file as an administrator by right-clicking on it and choosing "Run as administrator". This will start the installation process of ESET NOD32 Antivirus v12.1.31.0 Crack on your PC.

      -

      Step 4: Follow the installation wizard and enter the license key

      -

      During the installation process, you need to follow the instructions on the screen and choose the options that suit your preferences. You may also need to enter the license key that is provided in the crack file folder. You can copy and paste it from the license key file or type it manually. The license key is supposed to activate ESET NOD32 Antivirus v12.1.31.0 Crack and give you access to all its features for free.

      -

      Step 5: Restart your computer and enjoy ESET NOD32 Antivirus for free

      -

      After the installation is complete, you need to restart your computer for the changes to take effect. You should also enable your antivirus and firewall again for your safety. Once your PC is rebooted, you can launch ESET NOD32 Antivirus v12.1.31.0 Crack and enjoy its protection and performance for free.

      -

      Is there a better alternative to using a crack?

      -

      While using a crack may seem like a good idea at first, it is not worth the risks and consequences that come with it. There are better and safer ways to get ESET NOD32 Antivirus without breaking the law or compromising your security. Some of these are:

      -

      The official website of ESET NOD32 Antivirus

      -

      The best and most reliable way to get ESET NOD32 Antivirus is to buy it from its official website. There you can find different plans and prices that suit your needs and budget. You can also get discounts and offers if you buy multiple licenses or renew your subscription. By buying from the official website, you can enjoy the following benefits:

      -
        -
      • Legal and ethical: You are supporting the software developers and respecting their intellectual property rights.
      • -
      • Safe and secure: You are getting a clean and verified version of the software that does not contain any malware or viruses.
      • -
      • Updated and supported: You are getting the latest version of the software that is compatible with your system and has new features and improvements. You are also getting technical support and customer service from the software providers.
      • -
      -

      The trial version of ESET NOD32 Antivirus

      -

      If you are not sure whether you want to buy ESET NOD32 Antivirus or not, you can try it for free for 30 days by downloading its trial version from its official website. The trial version gives you access to all the features and functions of the software without any limitations or restrictions. You can use it to test its performance and protection on your PC and see if it meets your expectations. By using the trial version, you can enjoy the following benefits:

      -
        -
      • Free and easy: You don't have to pay anything or enter any credit card information to use the trial version. You just need to download it and install it on your PC.
      • -
      • Fair and honest: You don't have to use any illegal or unethical methods to use the trial version. You just need to follow the terms and conditions of the software providers.
      • -
      • Flexible and convenient: You don't have to commit to anything or sign any contracts to use the trial version. You can use it for as long as you want within the 30-day period and decide whether you want to buy it or not afterwards.
      • -
      -

      The discounted price of ESET NOD32 Antivirus

      -

      If you want to save some money on buying ESET NOD32 Antivirus, you can look for some discounts or coupons that are available online or offline. You can find them on various websites, blogs, forums, social media platforms, newsletters, magazines, etc. You can also ask your friends, family, colleagues, or other users who have bought ESET NOD32 Antivirus before if they have any recommendations or referrals for you. By using a discount or coupon, you can enjoy the following benefits:

      -
        -
      • Cheap and affordable: You can get ESET NOD32 Antivirus for a lower price than its original price by applying a discount or coupon code during checkout.
      • -
      • Smart and savvy: You can get more value for your money by getting a high-quality product for a low price.
      • -
      • Lucky and happy: You can feel good about yourself for finding a great deal and getting a bargain.
      • -
      -

      Conclusion

      -

      ESET NOD32 Antivirus v12.1.31.0 Crack is a modified version of ESET NOD32 Antivirus that claims to provide users with unlimited access to all its features for free by bypassing its activation process. However, using a crack is not a good idea as it comes with many risks and consequences that could harm your PC, compromise your security, violate the law, or cause other problems. There are better and safer ways to get ESET NOD32 Antivirus without using a crack, such as buying it from its official website, trying it for free for 30 days, or looking for discounts or coupons online or offline. These methods are legal, ethical, safe, secure, updated, supported, free, easy, fair, honest, flexible, convenient, cheap, affordable, smart, savvy, lucky, and happy.

      -

      FAQs

      -
        -
      1. What is ESET NOD32 Antivirus?
      2. -

        ESET NOD32 Antivirus is a comprehensive security solution that protects your PC from various types of malware, such as viruses, worms, trojans, spyware, ransomware, adware, rootkits, etc.

        -
      3. What is ESET NOD32 Antivirus v12.1.31.0 Crack?
      4. -

        ESET NOD32 Antivirus v12.1.31.0 Crack is a modified version of ESET NOD32 Antivirus that bypasses its activation process and allows users to use it for free or with unlimited features.

        -
      5. Is ESET NOD32 Antivirus v12.1.31.0 Crack safe?
      6. -

        No, ESET NOD32 Antivirus v12.1.31.0 Crack is not safe as it may contain malware or viruses that can damage your system or steal your data.

        -
      7. Is ESET NOD32 Antivirus v12.1.31.0 Crack legal?
      8. -

        No, ESET NOD32 Antivirus v12.1.31.0 Crack is not legal as it violates the intellectual property rights of the software developers and exposes users to legal consequences or penalties for piracy.

        -
      9. How can I get ESET NOD32 Antivirus without using a crack?
      10. -

        You can get ESET NOD32 Antivirus without using a crack by buying it from its official website, trying it for free for 30 days, or looking for discounts or coupons online or offline.

        -
      -

      0a6ba089eb
      -
      -
      \ No newline at end of file diff --git a/spaces/ramiin2/AutoGPT/autogpt/memory/pinecone.py b/spaces/ramiin2/AutoGPT/autogpt/memory/pinecone.py deleted file mode 100644 index 27fcd62482d0cf44e02fa1c339195be58cb745b0..0000000000000000000000000000000000000000 --- a/spaces/ramiin2/AutoGPT/autogpt/memory/pinecone.py +++ /dev/null @@ -1,75 +0,0 @@ -import pinecone -from colorama import Fore, Style - -from autogpt.llm_utils import create_embedding_with_ada -from autogpt.logs import logger -from autogpt.memory.base import MemoryProviderSingleton - - -class PineconeMemory(MemoryProviderSingleton): - def __init__(self, cfg): - pinecone_api_key = cfg.pinecone_api_key - pinecone_region = cfg.pinecone_region - pinecone.init(api_key=pinecone_api_key, environment=pinecone_region) - dimension = 1536 - metric = "cosine" - pod_type = "p1" - table_name = "auto-gpt" - # this assumes we don't start with memory. - # for now this works. - # we'll need a more complicated and robust system if we want to start with - # memory. - self.vec_num = 0 - - try: - pinecone.whoami() - except Exception as e: - logger.typewriter_log( - "FAILED TO CONNECT TO PINECONE", - Fore.RED, - Style.BRIGHT + str(e) + Style.RESET_ALL, - ) - logger.double_check( - "Please ensure you have setup and configured Pinecone properly for use." - + f"You can check out {Fore.CYAN + Style.BRIGHT}" - "https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup" - f"{Style.RESET_ALL} to ensure you've set up everything correctly." - ) - exit(1) - - if table_name not in pinecone.list_indexes(): - pinecone.create_index( - table_name, dimension=dimension, metric=metric, pod_type=pod_type - ) - self.index = pinecone.Index(table_name) - - def add(self, data): - vector = create_embedding_with_ada(data) - # no metadata here. We may wish to change that long term. - self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})]) - _text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}" - self.vec_num += 1 - return _text - - def get(self, data): - return self.get_relevant(data, 1) - - def clear(self): - self.index.delete(deleteAll=True) - return "Obliviated" - - def get_relevant(self, data, num_relevant=5): - """ - Returns all the data in the memory that is relevant to the given data. - :param data: The data to compare to. - :param num_relevant: The number of relevant data to return. Defaults to 5 - """ - query_embedding = create_embedding_with_ada(data) - results = self.index.query( - query_embedding, top_k=num_relevant, include_metadata=True - ) - sorted_results = sorted(results.matches, key=lambda x: x.score) - return [str(item["metadata"]["raw_text"]) for item in sorted_results] - - def get_stats(self): - return self.index.describe_index_stats() diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/(SDDM909) SOD.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/(SDDM909) SOD.md deleted file mode 100644 index fecf0addc4c5176d979b2f53e57429bea15b604c..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/(SDDM909) SOD.md +++ /dev/null @@ -1,6 +0,0 @@ -

      (SDDM909) SOD


      Download ►►► https://urlgoal.com/2uCM4c



      - -File Name, Size. (SDDM909) SOD p H Ѽֳ q Rhip hop ʷR - L K.avi, 2.48 GB. 99P2P.url, 47 B. SDDM909.jpg, 261 KB. 1fdad05405
      -
      -
      -

      diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Fanuc Pc Fapt Cut FULL Version Download.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Fanuc Pc Fapt Cut FULL Version Download.md deleted file mode 100644 index 120184fa6ed64343a83435ba04b2ed6f4744764c..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Fanuc Pc Fapt Cut FULL Version Download.md +++ /dev/null @@ -1,20 +0,0 @@ - -

      How to Download and Use FANUC PC FAPT Cut Full Version

      -

      If you are looking for a reliable and easy-to-use software for programming CNC lathes, you might want to check out FANUC PC FAPT Cut. This is a Windows based system that is based on the already successful FAPT machine control option. FANUC PC FAPT Cut allows you to produce programs quickly and efficiently, with features such as automatic tool path generation, simulation, verification, and optimization. In this article, we will show you how to download and use FANUC PC FAPT Cut full version for free.

      -

      fanuc pc fapt cut FULL Version download


      Download Zip ··· https://urlgoal.com/2uCKLw



      -

      What is FANUC PC FAPT Cut?

      -

      FANUC PC FAPT Cut is a software that is designed by FANUC, the world's largest lathe control manufacturer. It is compatible with most of the FANUC CNC systems, such as Series 0i, 15, 16, 18, 21, 30i, 31i, and 32i. It supports various types of lathe operations, such as turning, facing, threading, grooving, drilling, tapping, boring, and milling. It also supports multiple turrets, sub-spindles, C-axis, Y-axis, and B-axis.

      -

      FANUC PC FAPT Cut has a user-friendly interface that guides you through the programming process step by step. You can input the geometry data of the workpiece and the tool data manually or import them from CAD files. You can also select the cutting conditions and machining sequences from predefined menus or customize them according to your needs. You can then generate the tool path automatically or edit it manually. You can also simulate the machining process on the screen and verify the accuracy and quality of the program. You can also optimize the program by adjusting the feed rate, spindle speed, tool life, and cutting time.

      -

      How to Download FANUC PC FAPT Cut Full Version for Free?

      -

      If you want to download FANUC PC FAPT Cut full version for free, you can follow these steps:

      -
        -
      1. Go to https://en.freedownloadmanager.org/Windows-PC/FANUC-PC-FAPT-FREE.html and click on the green "Download" button.
      2. -
      3. Wait for the download to complete and then run the installer file.
      4. -
      5. Follow the instructions on the screen to install FANUC PC FAPT Cut on your computer.
      6. -
      7. Launch FANUC PC FAPT Cut and enjoy programming CNC lathes.
      8. -
      -

      Conclusion

      -

      FANUC PC FAPT Cut is a powerful and convenient software for programming CNC lathes. It can help you create programs faster and easier than ever before. It can also help you improve the quality and efficiency of your machining process. If you want to try it out for free, you can download it from the link above and start using it right away.

      -

      d5da3c52bf
      -
      -
      \ No newline at end of file diff --git a/spaces/rizam/literature-research-tool/lrt/clustering/__init__.py b/spaces/rizam/literature-research-tool/lrt/clustering/__init__.py deleted file mode 100644 index 5e1a3dadad381a487c2131f273d4ae064c759fd0..0000000000000000000000000000000000000000 --- a/spaces/rizam/literature-research-tool/lrt/clustering/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .clustering_pipeline import ClusterPipeline, ClusterList -from .config import Configuration,BaselineConfig diff --git a/spaces/rizam/literature-research-tool/lrt/clustering/clustering_pipeline.py b/spaces/rizam/literature-research-tool/lrt/clustering/clustering_pipeline.py deleted file mode 100644 index 37d68a8e6eb5d7d32e3e6b05d56fe2f89d387745..0000000000000000000000000000000000000000 --- a/spaces/rizam/literature-research-tool/lrt/clustering/clustering_pipeline.py +++ /dev/null @@ -1,108 +0,0 @@ -from typing import List -from .config import BaselineConfig, Configuration -from ..utils import __create_model__ -import numpy as np -# from sklearn.cluster import KMeans -from sklearn.preprocessing import StandardScaler -# from yellowbrick.cluster import KElbowVisualizer -from .clusters import ClusterList -from unsupervised_learning.clustering import GaussianMixture, Silhouette - -class ClusterPipeline: - def __init__(self, config:Configuration = None): - if config is None: - self.__setup__(BaselineConfig()) - else: - self.__setup__(config) - - def __setup__(self, config:Configuration): - self.PTM = __create_model__(config.plm) - self.dimension_reduction = __create_model__(config.dimension_reduction) - self.clustering = __create_model__(config.clustering) - self.keywords_extraction = __create_model__(config.keywords_extraction) - - def __1_generate_word_embeddings__(self, documents: List[str]): - ''' - - :param documents: a list of N strings: - :return: np.ndarray: Nx384 (sentence-transformers) - ''' - print(f'>>> start generating word embeddings...') - print(f'>>> successfully generated word embeddings...') - return self.PTM.encode(documents) - - def __2_dimenstion_reduction__(self, embeddings): - ''' - - :param embeddings: NxD - :return: Nxd, d<>> start dimension reduction...') - embeddings = self.dimension_reduction.dimension_reduction(embeddings) - print(f'>>> finished dimension reduction...') - return embeddings - - def __3_clustering__(self, embeddings, return_cluster_centers = False, max_k: int =10, standarization = False): - ''' - - :param embeddings: Nxd - :return: - ''' - if self.clustering is None: - return embeddings - else: - print(f'>>> start clustering...') - - ######## new: standarization ######## - if standarization: - print(f'>>> start standardization...') - scaler = StandardScaler() - embeddings = scaler.fit_transform(embeddings) - print(f'>>> finished standardization...') - ######## new: standarization ######## - - best_k_algo = Silhouette(GaussianMixture,2,max_k) - best_k = best_k_algo.get_best_k(embeddings) - print(f'>>> The best K is {best_k}.') - - labels, cluster_centers = self.clustering(embeddings, k=best_k) - clusters = ClusterList(best_k) - clusters.instantiate(labels) - print(f'>>> finished clustering...') - - if return_cluster_centers: - return clusters, cluster_centers - return clusters - - def __4_keywords_extraction__(self, clusters: ClusterList, documents: List[str]): - ''' - - :param clusters: N documents - :return: clusters, where each cluster has added keyphrases - ''' - if self.keywords_extraction is None: - return clusters - else: - print(f'>>> start keywords extraction') - for cluster in clusters: - doc_ids = cluster.elements() - input_abstracts = [documents[i] for i in doc_ids] #[str] - keyphrases = self.keywords_extraction(input_abstracts) #[{keys...}] - cluster.add_keyphrase(keyphrases) - # for doc_id in doc_ids: - # keyphrases = self.keywords_extraction(documents[doc_id]) - # cluster.add_keyphrase(keyphrases) - print(f'>>> finished keywords extraction') - return clusters - - - def __call__(self, documents: List[str], max_k:int, standarization = False): - print(f'>>> pipeline starts...') - x = self.__1_generate_word_embeddings__(documents) - x = self.__2_dimenstion_reduction__(x) - clusters = self.__3_clustering__(x,max_k=max_k,standarization=standarization) - outputs = self.__4_keywords_extraction__(clusters, documents) - print(f'>>> pipeline finished!\n') - return outputs diff --git a/spaces/rizam/literature-research-tool/lrt/utils/functions.py b/spaces/rizam/literature-research-tool/lrt/utils/functions.py deleted file mode 100644 index 0f2b8f503807ab6afdae90d8d333cc3b81c83d80..0000000000000000000000000000000000000000 --- a/spaces/rizam/literature-research-tool/lrt/utils/functions.py +++ /dev/null @@ -1,159 +0,0 @@ -from typing import List -from sentence_transformers import SentenceTransformer -from kmeans_pytorch import kmeans -import torch -from sklearn.cluster import KMeans -from transformers import AutoTokenizer, AutoModelForSeq2SeqLM,Text2TextGenerationPipeline -from inference_hf import InferenceHF -from .dimension_reduction import PCA -from unsupervised_learning.clustering import GaussianMixture - -class Template: - def __init__(self): - self.PLM = { - 'sentence-transformer-mini': '''sentence-transformers/all-MiniLM-L6-v2''', - 'sentence-t5-xxl': '''sentence-transformers/sentence-t5-xxl''', - 'all-mpnet-base-v2':'''sentence-transformers/all-mpnet-base-v2''' - } - self.dimension_reduction = { - 'pca': PCA, - 'vae': None, - 'cnn': None - } - - self.clustering = { - 'kmeans-cosine': kmeans, - 'kmeans-euclidean': KMeans, - 'gmm': GaussianMixture - } - - self.keywords_extraction = { - 'keyphrase-transformer': '''snrspeaks/KeyPhraseTransformer''', - 'KeyBartAdapter': '''Adapting/KeyBartAdapter''', - 'KeyBart': '''bloomberg/KeyBART''' - } - -template = Template() - -def __create_model__(model_ckpt): - ''' - - :param model_ckpt: keys in Template class - :return: model/function: callable - ''' - if model_ckpt == '''sentence-transformer-mini''': - return SentenceTransformer(template.PLM[model_ckpt]) - elif model_ckpt == '''sentence-t5-xxl''': - return SentenceTransformer(template.PLM[model_ckpt]) - elif model_ckpt == '''all-mpnet-base-v2''': - return SentenceTransformer(template.PLM[model_ckpt]) - elif model_ckpt == 'none': - return None - elif model_ckpt == 'kmeans-cosine': - def ret(x,k): - tmp = template.clustering[model_ckpt]( - X=torch.from_numpy(x), num_clusters=k, distance='cosine', - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - ) - return tmp[0].cpu().detach().numpy(), tmp[1].cpu().detach().numpy() - return ret - elif model_ckpt == 'pca': - pca = template.dimension_reduction[model_ckpt](0.95) - return pca - - elif model_ckpt =='kmeans-euclidean': - def ret(x,k): - tmp = KMeans(n_clusters=k,random_state=50).fit(x) - return tmp.labels_, tmp.cluster_centers_ - return ret - elif model_ckpt == 'gmm': - def ret(x,k): - model = GaussianMixture(k,50) - model.fit(x) - return model.getLabels(), model.getClusterCenters() - return ret - - elif model_ckpt == 'keyphrase-transformer': - model_ckpt = template.keywords_extraction[model_ckpt] - - def ret(texts: List[str]): - # first try inference API - response = InferenceHF.inference( - inputs=texts, - model_name=model_ckpt - ) - - # inference failed: - if not isinstance(response, list): - tokenizer = AutoTokenizer.from_pretrained(model_ckpt) - model = AutoModelForSeq2SeqLM.from_pretrained(model_ckpt) - pipe = Text2TextGenerationPipeline(model=model, tokenizer=tokenizer) - - tmp = pipe(texts) - results = [ - set( - map(str.strip, - x['generated_text'].split('|') # [str...] - ) - ) - for x in tmp] # [{str...}...] - - return results - - # inference sucsess - else: - results = [ - set( - map(str.strip, - x['generated_text'].split('|') # [str...] - ) - ) - for x in response] # [{str...}...] - - return results - - return ret - - elif model_ckpt == 'KeyBartAdapter' or model_ckpt == 'KeyBart': - model_ckpt = template.keywords_extraction[model_ckpt] - def ret(texts: List[str]): - # first try inference API - response = InferenceHF.inference( - inputs=texts, - model_name=model_ckpt - ) - - # inference failed: - if not isinstance(response,list): - tokenizer = AutoTokenizer.from_pretrained(model_ckpt) - model = AutoModelForSeq2SeqLM.from_pretrained(model_ckpt) - pipe = Text2TextGenerationPipeline(model=model, tokenizer=tokenizer) - - - tmp = pipe(texts) - results = [ - set( - map(str.strip, - x['generated_text'].split(';') # [str...] - ) - ) - for x in tmp] # [{str...}...] - - return results - - # inference sucsess - else: - results = [ - set( - map(str.strip, - x['generated_text'].split(';') # [str...] - ) - ) - for x in response] # [{str...}...] - - return results - - return ret - else: - raise RuntimeError(f'The model {model_ckpt} is not supported. Please open an issue on the GitHub about the model.') - diff --git a/spaces/robin0307/MMOCR/configs/_base_/det_pipelines/fcenet_pipeline.py b/spaces/robin0307/MMOCR/configs/_base_/det_pipelines/fcenet_pipeline.py deleted file mode 100644 index badb4536b10bd74760fdf519fe03f5c8d2bd7767..0000000000000000000000000000000000000000 --- a/spaces/robin0307/MMOCR/configs/_base_/det_pipelines/fcenet_pipeline.py +++ /dev/null @@ -1,118 +0,0 @@ -img_norm_cfg = dict( - mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) - -# for icdar2015 -leval_prop_range_icdar2015 = ((0, 0.4), (0.3, 0.7), (0.6, 1.0)) -train_pipeline_icdar2015 = [ - dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), - dict( - type='LoadTextAnnotations', - with_bbox=True, - with_mask=True, - poly2mask=False), - dict( - type='ColorJitter', - brightness=32.0 / 255, - saturation=0.5, - contrast=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='RandomScaling', size=800, scale=(3. / 4, 5. / 2)), - dict( - type='RandomCropFlip', crop_ratio=0.5, iter_num=1, min_area_ratio=0.2), - dict( - type='RandomCropPolyInstances', - instance_key='gt_masks', - crop_ratio=0.8, - min_side_ratio=0.3), - dict( - type='RandomRotatePolyInstances', - rotate_ratio=0.5, - max_angle=30, - pad_with_fixed_color=False), - dict(type='SquareResizePad', target_size=800, pad_ratio=0.6), - dict(type='RandomFlip', flip_ratio=0.5, direction='horizontal'), - dict(type='Pad', size_divisor=32), - dict( - type='FCENetTargets', - fourier_degree=5, - level_proportion_range=leval_prop_range_icdar2015), - dict( - type='CustomFormatBundle', - keys=['p3_maps', 'p4_maps', 'p5_maps'], - visualize=dict(flag=False, boundary_key=None)), - dict(type='Collect', keys=['img', 'p3_maps', 'p4_maps', 'p5_maps']) -] - -img_scale_icdar2015 = (2260, 2260) -test_pipeline_icdar2015 = [ - dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), - dict( - type='MultiScaleFlipAug', - img_scale=img_scale_icdar2015, # used by Resize - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] - -# for ctw1500 -leval_prop_range_ctw1500 = ((0, 0.25), (0.2, 0.65), (0.55, 1.0)) -train_pipeline_ctw1500 = [ - dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), - dict( - type='LoadTextAnnotations', - with_bbox=True, - with_mask=True, - poly2mask=False), - dict( - type='ColorJitter', - brightness=32.0 / 255, - saturation=0.5, - contrast=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='RandomScaling', size=800, scale=(3. / 4, 5. / 2)), - dict( - type='RandomCropFlip', crop_ratio=0.5, iter_num=1, min_area_ratio=0.2), - dict( - type='RandomCropPolyInstances', - instance_key='gt_masks', - crop_ratio=0.8, - min_side_ratio=0.3), - dict( - type='RandomRotatePolyInstances', - rotate_ratio=0.5, - max_angle=30, - pad_with_fixed_color=False), - dict(type='SquareResizePad', target_size=800, pad_ratio=0.6), - dict(type='RandomFlip', flip_ratio=0.5, direction='horizontal'), - dict(type='Pad', size_divisor=32), - dict( - type='FCENetTargets', - fourier_degree=5, - level_proportion_range=leval_prop_range_ctw1500), - dict( - type='CustomFormatBundle', - keys=['p3_maps', 'p4_maps', 'p5_maps'], - visualize=dict(flag=False, boundary_key=None)), - dict(type='Collect', keys=['img', 'p3_maps', 'p4_maps', 'p5_maps']) -] - -img_scale_ctw1500 = (1080, 736) -test_pipeline_ctw1500 = [ - dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), - dict( - type='MultiScaleFlipAug', - img_scale=img_scale_ctw1500, # used by Resize - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] diff --git a/spaces/robin0307/MMOCR/configs/textdet/fcenet/fcenet_r50_fpn_1500e_icdar2015.py b/spaces/robin0307/MMOCR/configs/textdet/fcenet/fcenet_r50_fpn_1500e_icdar2015.py deleted file mode 100644 index d4a9c642307466c86f667d64bbeb4057db571b66..0000000000000000000000000000000000000000 --- a/spaces/robin0307/MMOCR/configs/textdet/fcenet/fcenet_r50_fpn_1500e_icdar2015.py +++ /dev/null @@ -1,33 +0,0 @@ -_base_ = [ - '../../_base_/default_runtime.py', - '../../_base_/schedules/schedule_sgd_1500e.py', - '../../_base_/det_models/fcenet_r50_fpn.py', - '../../_base_/det_datasets/icdar2015.py', - '../../_base_/det_pipelines/fcenet_pipeline.py' -] - -train_list = {{_base_.train_list}} -test_list = {{_base_.test_list}} - -train_pipeline_icdar2015 = {{_base_.train_pipeline_icdar2015}} -test_pipeline_icdar2015 = {{_base_.test_pipeline_icdar2015}} - -data = dict( - samples_per_gpu=8, - workers_per_gpu=2, - val_dataloader=dict(samples_per_gpu=1), - test_dataloader=dict(samples_per_gpu=1), - train=dict( - type='UniformConcatDataset', - datasets=train_list, - pipeline=train_pipeline_icdar2015), - val=dict( - type='UniformConcatDataset', - datasets=test_list, - pipeline=test_pipeline_icdar2015), - test=dict( - type='UniformConcatDataset', - datasets=test_list, - pipeline=test_pipeline_icdar2015)) - -evaluation = dict(interval=10, metric='hmean-iou') diff --git a/spaces/robosapiens/color-range-classifier/README.md b/spaces/robosapiens/color-range-classifier/README.md deleted file mode 100644 index 0699c10a620aebd746e98aa9a6f88ed6299aafc1..0000000000000000000000000000000000000000 --- a/spaces/robosapiens/color-range-classifier/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Color Range Classifier -emoji: 📈 -colorFrom: pink -colorTo: green -sdk: gradio -sdk_version: 3.16.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/rorallitri/biomedical-language-models/logs/Download Italian Movie Streamer House and Enjoy Unlimited Access to Italian Films.md b/spaces/rorallitri/biomedical-language-models/logs/Download Italian Movie Streamer House and Enjoy Unlimited Access to Italian Films.md deleted file mode 100644 index ffd9a9a16e3f86e4941716f476394833d140ee83..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Download Italian Movie Streamer House and Enjoy Unlimited Access to Italian Films.md +++ /dev/null @@ -1,13 +0,0 @@ - -

      Selection of TV shows and movies: Choices for streaming and downloading (including audio/subtitle options) vary by country. Also, My List and Continue Watching titles may not be available.

      -

      Download Italian Movie Streamer House


      Download File ☆☆☆☆☆ https://tinurll.com/2uznKt



      -

      Start reading, listening or watching instantly with e-books, audiobooks, e-magazines, and streaming movies. Most titles are available online with just an internet connection and a library card. An e-reader app is required for downloading to your personal device.

      -

      Go Into the Story is the official blog for The Blacklist, the screenwriting community famous for its annual top ten list of unproduced scripts. One useful feature of Go Into the Story is its bank of downloadable movie scripts.

      -

      Paramount+ is $5 per month (or $50 annually) for the ad-supported Essential plan or $10 for the Premium package ($100 annually), which only has ads on live TV and a handful of shows. Both plans include NFL games on CBS, 24/7 live news on CBSN and tens of thousands of movies and TV episodes. However, the Premium option lets you watch your local CBS channel and download content to watch later. In addition to live sports, your subscription also gives you access to the hit Yellowstone prequel series 1883, Star Trek Discovery, A Quiet Place Part II and more exclusive and original content.

      -

      -

      CenturyLink is one of the largest Internet Server Providers (ISPs) in the United States, offering coverage to an estimated 48.6 million people, primarily in Arizona, Colorado, North Carolina and Washington. It offers both DSL broadband coverage and extensive fiber services, the latter providing a great option for gamers or streamers looking for high download or upload speeds.

      -

      The best method in making sure you can watch your favorite Disney Plus content is to download the content for offline viewing before you leave. To get started launch the Disney Plus app on your phone or tablet and head to the movie or show you want to download. Then tap the download button next to the Play button.

      -

      No time to wait? Instantly stream movies, music, and television shows or download audiobooks, comics, and eBooks. New titles are added daily. Titles for all age groups available. Library card required.

      -

      Use your library card to stream free indie films, documentaries, Great Courses, art house films, and more in multiple languages. Watch from any computer, television, or mobile device by downloading the Kanopy app from your favorite app store.

      aaccfb2cb3
      -
      -
      \ No newline at end of file diff --git a/spaces/rorallitri/biomedical-language-models/logs/Free Download Foxit Reader 9.0.1.1049 Final Portable Crack - The Ultimate PDF Solution.md b/spaces/rorallitri/biomedical-language-models/logs/Free Download Foxit Reader 9.0.1.1049 Final Portable Crack - The Ultimate PDF Solution.md deleted file mode 100644 index c8912e2412126bfcbfb9b0430289f7b1e13df495..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Free Download Foxit Reader 9.0.1.1049 Final Portable Crack - The Ultimate PDF Solution.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Foxit Reader 9.0.1.1049 Final Portable Crack [Free Download]


      Download File ✒ ✒ ✒ https://tinurll.com/2uzoHO



      - - aaccfb2cb3
      -
      -
      -

      diff --git a/spaces/rorallitri/biomedical-language-models/logs/Johnny English Reborn Full __HOT__ Movie Malay Subtitles Download.md b/spaces/rorallitri/biomedical-language-models/logs/Johnny English Reborn Full __HOT__ Movie Malay Subtitles Download.md deleted file mode 100644 index ee50122ba815be7d4d1534c16af8dd986f10cb86..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Johnny English Reborn Full __HOT__ Movie Malay Subtitles Download.md +++ /dev/null @@ -1,80 +0,0 @@ - -

      Johnny English Reborn Full Movie Malay Subtitles Download

      - -

      If you are a fan of spy comedy movies, you might have heard of Johnny English Reborn, the sequel to the 2003 film Johnny English. The movie stars Rowan Atkinson as the titular character, a clumsy and incompetent British secret agent who has to stop a group of international assassins from killing the Chinese premier.

      -

      Johnny English Reborn Full Movie Malay Subtitles Download


      Download File ✒ ✒ ✒ https://tinurll.com/2uznm0



      - -

      The movie was released in 2011 and received mixed reviews from critics, but was a commercial success, grossing over $160 million worldwide. It also features some hilarious scenes and stunts, such as Johnny English's chase on a wheelchair, his fight with a cleaner in a Hong Kong hotel, and his encounter with a Tibetan monk.

      - -

      But what if you want to watch Johnny English Reborn with Malay subtitles? Maybe you are a Malay speaker who wants to enjoy the movie in your native language, or maybe you are learning Malay and want to improve your skills by watching movies. Whatever your reason, you might be wondering where you can find and download Johnny English Reborn full movie with Malay subtitles.

      - -

      How to Download Johnny English Reborn Full Movie with Malay Subtitles

      - -

      Fortunately, there are some websites that offer Johnny English Reborn full movie with Malay subtitles for free. You can download the movie file and the subtitle file separately, and then play them together using a media player that supports subtitles, such as VLC or KMPlayer. Here are some of the websites that you can try:

      - -
        -
      • SUBDL: This website has a large collection of subtitles for various movies and TV shows in different languages. You can find Johnny English Reborn Malay subtitles in different formats and qualities, such as Webdl, Dvdrip, Bluray, etc. You can also filter the subtitles by language, release type, uploader, and more.
      • -
      • OpenSubtitles: This website is one of the most popular sources of subtitles on the internet. You can find Johnny English Reborn Malay subtitles in various formats and qualities, such as BRRip, DVDRip, BluRay, etc. You can also search for subtitles by movie name, genre, year, rating, and more.
      • -
      • Bilibili: This website is a video streaming platform that offers various content, such as movies, TV shows, anime, music, games, etc. You can watch Johnny English Reborn full movie with Malay subtitles online for free on this website. You can also download the video and the subtitles using a third-party tool.
      • -
      - -

      These are some of the websites that you can use to download Johnny English Reborn full movie with Malay subtitles. However, you should be careful when downloading files from unknown sources, as they might contain viruses or malware that can harm your device or compromise your privacy. You should also respect the intellectual property rights of the movie makers and distributors, and only use these websites for personal and educational purposes.

      -

      - -

      Conclusion

      - -

      Johnny English Reborn is a fun and entertaining spy comedy movie that you can watch with Malay subtitles. You can find and download Johnny English Reborn full movie with Malay subtitles from some of the websites mentioned above. However, you should be cautious when downloading files from unknown sources, and only use these websites for personal and educational purposes.

      - -

      We hope this article has helped you find what you are looking for. If you have any questions or suggestions, feel free to leave a comment below. Thank you for reading!

      -

      Why You Should Watch Johnny English Reborn Full Movie with Malay Subtitles

      - -

      Johnny English Reborn is a movie that will make you laugh out loud with its witty jokes, hilarious situations, and absurd characters. The movie is a parody of the spy genre, especially the James Bond films, and it mocks the clichés and tropes of espionage movies. The movie also has some exciting action scenes, such as car chases, helicopter fights, and rooftop battles.

      - -

      But what makes Johnny English Reborn even more enjoyable is watching it with Malay subtitles. By doing so, you can appreciate the movie in your own language, or learn a new language by following the dialogue. You can also catch some of the subtle humor and references that might be lost in translation. Moreover, you can share the movie with your friends and family who speak Malay, and have a fun time together.

      - -

      Where to Watch Johnny English Reborn Full Movie with Malay Subtitles

      - -

      If you are interested in watching Johnny English Reborn full movie with Malay subtitles, you have several options to choose from. You can either buy or rent the DVD or Blu-ray of the movie, which usually comes with multiple subtitle options, including Malay. You can also stream or download the movie online from various platforms, such as Netflix, Amazon Prime Video, iTunes, Google Play Movies, etc. However, you might need to check if the movie is available in your region and if it has Malay subtitles.

      - -

      Another option is to use a VPN service to access geo-restricted content and watch Johnny English Reborn full movie with Malay subtitles from any country. A VPN is a software that encrypts your internet traffic and changes your IP address to make it appear as if you are browsing from another location. This way, you can bypass censorship and geo-blocks and access any website or service that you want. For example, you can use a VPN to connect to a server in Malaysia and watch Johnny English Reborn full movie with Malay subtitles on Netflix Malaysia.

      - -

      However, not all VPNs are reliable and secure. Some VPNs might leak your personal information, slow down your connection speed, or contain malware. Therefore, you should choose a VPN that has a good reputation, fast servers, strong encryption, and a no-logs policy. Some of the best VPNs that you can use to watch Johnny English Reborn full movie with Malay subtitles are ExpressVPN , NordVPN , Surfshark , CyberGhost , and IPVanish .

      -

      What Critics and Audiences Say About Johnny English Reborn Full Movie with Malay Subtitles

      - -

      Johnny English Reborn received mixed reviews from critics and audiences when it was released in 2011. The movie has a 38% rating on Rotten Tomatoes, based on 92 reviews, with an average score of 4.9/10. The critics consensus reads: \"Arguably a marginal improvement on its mostly-forgotten predecessor, Johnny English Reborn nonetheless remains mired in broad, tired spy spoofing that wastes Rowan Atkinson's once considerable comedic talent.\"

      - -

      On the other hand, the movie has a 45% audience score on Rotten Tomatoes, based on more than 25,000 ratings, with an average score of 3/5. Some of the audience reviews praise the movie for its funny moments, entertaining action scenes, and Rowan Atkinson's performance. Others criticize the movie for its predictable plot, childish humor, and lack of originality.

      - -

      On IMDb, the movie has a 6.3/10 rating, based on more than 120,000 votes. Some of the user reviews highlight the movie's improvement over the first one, its clever references to other spy movies, and its enjoyable cast. Others complain about the movie's lowbrow jokes, unrealistic situations, and wasted potential.

      - -

      How to Enjoy Johnny English Reborn Full Movie with Malay Subtitles

      - -

      If you want to watch Johnny English Reborn full movie with Malay subtitles, you should keep in mind that this is not a serious spy thriller, but a spoof of the genre. The movie is meant to be a light-hearted comedy that makes fun of the clichés and tropes of espionage movies. The movie is also a showcase of Rowan Atkinson's physical comedy skills, which might not appeal to everyone's taste.

      - -

      Therefore, to enjoy Johnny English Reborn full movie with Malay subtitles, you should not expect a realistic or sophisticated plot, but rather a silly and absurd story that serves as a backdrop for Johnny English's antics. You should also not take the movie too seriously, but rather laugh at its ridiculous situations and characters. You should also appreciate the movie's homage to other spy movies, such as James Bond, Mission: Impossible, and Bourne.

      - -

      Finally, you should watch Johnny English Reborn full movie with Malay subtitles with an open mind and a sense of humor. You might find some of the jokes hilarious, some of them lame, and some of them offensive. But if you are a fan of Rowan Atkinson or spy comedies in general, you might have a good time watching this movie.

      -

      Some Interesting Trivia and Facts About Johnny English Reborn Full Movie with Malay Subtitles

      - -

      Johnny English Reborn is not only a funny and entertaining movie, but also a movie that has some interesting trivia and facts behind it. Here are some of them:

      - -
        -
      • The movie was originally going to be filmed in 2006, but Rowan Atkinson decided to do Mr. Bean's Holiday (2007) instead.
      • -
      • The golf course where Johnny English and Simon Ambrose play is the same golf course where James Bond and Auric Goldfinger played in Goldfinger (1964).
      • -
      • The cat Philby was named after Kim Philby, a British spy who betrayed his country to the Soviet Union.
      • -
      • Rowan Atkinson and Rosamund Pike both made their movie debuts in James Bond movies, Atkinson in Never Say Never Again (1983) and Pike in Die Another Day (2002).
      • -
      • The search for the unknown third man in the spy ring is a reference to the real-life search for the fifth man in the Cambridge Five, a British spy ring that worked for the Soviet Union.
      • -
      • The Rolls-Royce Phantom Coupe that Johnny English drives was specially made for the movie, with a V16 engine instead of a V12.
      • -
      • The wine that Johnny English and Simon Ambrose drink at the restaurant is Romanée-Conti, one of the most expensive wines in the world.
      • -
      • Dominic West, who plays Simon Ambrose, actually attended Eton College, the prestigious school that his character mentions.
      • -
      • Gillian Anderson accidentally punched Burn Gorman in the face for real during a fight scene.
      • -
      • A scene was filmed but cut where Kate Sumner kisses Johnny English after tending to his leg wound.
      • -
      - -

      Conclusion

      - -

      Johnny English Reborn is a movie that you can watch with Malay subtitles if you are looking for a fun and hilarious spy comedy. The movie has a simple but amusing plot, a great cast, and some exciting action scenes. The movie also has some clever references to other spy movies and some interesting trivia and facts behind it. You can download Johnny English Reborn full movie with Malay subtitles from some of the websites that we have mentioned above, or use a VPN service to access geo-restricted content. However, you should be careful when downloading files from unknown sources and respect the intellectual property rights of the movie makers and distributors.

      - -

      We hope this article has helped you find what you are looking for. If you have any questions or suggestions, feel free to leave a comment below. Thank you for reading!

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/runa91/bite_gradio/src/stacked_hourglass/datasets/samplers/custom_gc_sampler_noclasses.py b/spaces/runa91/bite_gradio/src/stacked_hourglass/datasets/samplers/custom_gc_sampler_noclasses.py deleted file mode 100644 index 3887502b350730f1e32a7ac049dbc07d383cbcd8..0000000000000000000000000000000000000000 --- a/spaces/runa91/bite_gradio/src/stacked_hourglass/datasets/samplers/custom_gc_sampler_noclasses.py +++ /dev/null @@ -1,163 +0,0 @@ - -import numpy as np -import random -import copy -import time -import warnings -import random - -from torch.utils.data import Sampler -from torch._six import int_classes as _int_classes - -class CustomGCSamplerNoCLass(Sampler): - """Wraps another sampler to yield a mini-batch of indices. - The structure of this sampler is way to complicated because it is a shorter/simplified version of - CustomBatchSampler. The relations between breeds are not relevant for the cvpr 2022 paper, but we kept - this structure which we were using for the experiments with clade related losses. ToDo: restructure - this sampler. - Args: - data_sampler_info (dict): a dictionnary, containing information about the dataset and breeds. - batch_size (int): Size of mini-batch. - """ - - def __init__(self, data_sampler_info_gc, batch_size, add_nonflat=False): - if not isinstance(batch_size, _int_classes) or isinstance(batch_size, bool) or \ - batch_size <= 0: - assert (batch_size == 12 and add_nonflat==False) or (batch_size == 14 and add_nonflat==True) - raise ValueError("batch_size should be a positive integer value, " - "but got batch_size={}".format(batch_size)) - self.data_sampler_info_gc = data_sampler_info_gc - self.batch_size = batch_size - self.add_nonflat = add_nonflat - - self.n_images_tot = len(self.data_sampler_info_gc['name_list']) # 4305 - - # get full sorted image list - self.pose_dict = {} - self.dict_name_to_idx = {} - for ind_img, img in enumerate(self.data_sampler_info_gc['name_list']): - self.dict_name_to_idx[img] = ind_img - pose = self.data_sampler_info_gc['gc_annots_categories'][img]['pose'] - if pose in self.pose_dict.keys(): - self.pose_dict[pose].append(img) - else: - self.pose_dict[pose] = [img] - - # prepare non-flat images - if self.add_nonflat: - self.n_images_nonflat_tot = len(self.data_sampler_info_gc['name_list_nonflat']) - - # self.n_desired_batches = int(np.floor(len(self.data_sampler_info_gc['name_list']) / batch_size)) # 157 - self.n_desired_batches = 160 - - def get_description(self): - description = "\ - This sampler returns stanext data such that poses are more balanced. \n\ - -> works on top of stanext24_withgc_v2" - return description - - def get_nonflat_idx_list(self, shuffle=True): - all_nonflat_idxs = list(range(self.n_images_tot, self.n_images_tot + self.n_images_nonflat_tot)) - if shuffle: - random.shuffle(all_nonflat_idxs) - return all_nonflat_idxs - - def get_list_for_group_index(self, ind_g, n_groups=1, shuffle=True, return_info=False): - # availabe poses - # sitting_sym: 561 - # lying_sym: 199 - # jumping_touching: 21 - # standing_4paws: 1999 - # running: 132 - # sitting_comp: 306 - # onhindlegs: 16 - # walking: 325 - # lying_comp: 596 - # standing_fewpaws: 98 - # otherpose: 22 - # downwardfacingdog: 14 - # jumping_nottouching: 16 - # - # available groups (7 groups) - # 89: 'otherpose', 'downwardfacingdog', 'jumping_nottouching', 'onhindlegs', 'jumping_touching' - # 561: 'sitting_sym' - # 306: 'sitting_comp' - # 199: 'lying_sym' - # 596: 'lying_comp' - # 555: 'standing_fewpaws', 'running', 'walking' - # 1999: 'standing_4paws' - # -> sample: 2, 1.5, 1.5, 1.5, 1.5, 2, 2 - # - # available groups (5 groups) - # 89: 'otherpose', 'downwardfacingdog', 'jumping_nottouching', 'onhindlegs', 'jumping_touching' - # 867: 'sitting_sym', 'sitting_comp' - # 795: 'lying_sym', 'lying_comp' - # 555: 'standing_fewpaws', 'running', 'walking' - # 1999: 'standing_4paws' - # -> sample: 2, 3, 3, 2, 2 - assert (n_groups == 1) - if ind_g == 0: - n_samples_per_batch = 12 - pose_names = ['otherpose', 'downwardfacingdog', 'jumping_nottouching', 'onhindlegs', 'jumping_touching', 'sitting_sym', 'sitting_comp', 'lying_sym', 'lying_comp', 'standing_fewpaws', 'running', 'walking', 'standing_4paws'] - all_imgs_this_group = [] - for pose_name in pose_names: - all_imgs_this_group.extend(self.pose_dict[pose_name]) - if shuffle: - random.shuffle(all_imgs_this_group) - if return_info: - return all_imgs_this_group, pose_names, n_samples_per_batch - else: - return all_imgs_this_group - - - def __iter__(self): - - n_groups = 1 - group_lists = {} - n_samples_per_batch = {} - for ind_g in range(n_groups): - group_lists[ind_g], pose_names, n_samples_per_batch[ind_g] = self.get_list_for_group_index(ind_g, n_groups=1, shuffle=True, return_info=True) - if self.add_nonflat: - nonflat_idx_list = self.get_nonflat_idx_list() - - # we want to sample all sitting poses at least once per batch (and ths all other - # images except standing on 4 paws) - all_batches = [] - for ind in range(self.n_desired_batches): - batch_with_idxs = [] - for ind_g in range(n_groups): - for ind_s in range(n_samples_per_batch[ind_g]): - if len(group_lists[ind_g]) == 0: - group_lists[ind_g] = self.get_list_for_group_index(ind_g, n_groups=1, shuffle=True) - name = group_lists[ind_g].pop(0) - idx = self.dict_name_to_idx[name] - batch_with_idxs.append(idx) - if self.add_nonflat: - for ind_x in range(2): - if len(nonflat_idx_list) == 0: - nonflat_idx_list = self.get_nonflat_idx_list() - idx = nonflat_idx_list.pop(0) - batch_with_idxs.append(idx) - all_batches.append(batch_with_idxs) - - for batch in all_batches: - yield batch - - - def __len__(self): - # Since we are sampling pairs of dogs and not each breed has an even number of dogs, we can not - # guarantee to show each dog exacly once. What we do instead, is returning the same amount of - # batches as we would return with a standard sampler which is not based on dog pairs. - '''if self.drop_last: - return len(self.sampler) // self.batch_size # type: ignore - else: - return (len(self.sampler) + self.batch_size - 1) // self.batch_size # type: ignore''' - return self.n_desired_batches - - - - - - - - diff --git a/spaces/sarinam/speaker-anonymization-gan/app.py b/spaces/sarinam/speaker-anonymization-gan/app.py deleted file mode 100644 index e168024b06d1d543405fd5d7870b665d70da9925..0000000000000000000000000000000000000000 --- a/spaces/sarinam/speaker-anonymization-gan/app.py +++ /dev/null @@ -1,119 +0,0 @@ -import os -import gradio as gr -import numpy as np -import torch -from pathlib import Path - -os.system("pip uninstall -y gradio") -os.system("pip install gradio==3.2") - -from demo_inference.demo_tts import DemoTTS -from demo_inference.demo_asr import DemoASR -from demo_inference.demo_anonymization import DemoAnonymizer - - -def pcm2float(sig, dtype='float32'): - """ - https://gist.github.com/HudsonHuang/fbdf8e9af7993fe2a91620d3fb86a182 - """ - sig = np.asarray(sig) - if sig.dtype.kind not in 'iu': - raise TypeError("'sig' must be an array of integers") - dtype = np.dtype(dtype) - if dtype.kind != 'f': - raise TypeError("'dtype' must be a floating point type") - - i = np.iinfo(sig.dtype) - abs_max = 2 ** (i.bits - 1) - offset = i.min + abs_max - return (sig.astype(dtype) - offset) / abs_max - - -def float2pcm(sig, dtype='int16'): - """ - https://gist.github.com/HudsonHuang/fbdf8e9af7993fe2a91620d3fb86a182 - """ - sig = np.asarray(sig) - if sig.dtype.kind != 'f': - raise TypeError("'sig' must be a float array") - dtype = np.dtype(dtype) - if dtype.kind not in 'iu': - raise TypeError("'dtype' must be an integer type") - i = np.iinfo(dtype) - abs_max = 2 ** (i.bits - 1) - offset = i.min + abs_max - return (sig * abs_max + offset).clip(i.min, i.max).astype(dtype) - - -class VPInterface: - - def __init__(self): - self.device = 'cuda' if torch.cuda.is_available() else 'cpu' - - self.path_to_tts_models = Path('models', 'tts') - self.path_to_asr_model = Path('models', 'asr') - self.path_to_anon_model = Path('models', 'anonymization') - - self.synthesis_model = DemoTTS(model_paths=self.path_to_tts_models, device=self.device) - self.asr_model = DemoASR(model_path=self.path_to_asr_model, device=self.device) - self.anon_model = DemoAnonymizer(model_path=self.path_to_anon_model, model_tag='gan', device=self.device) - - def read(self, recording, anon_model_tag): - sr, audio = recording - audio = pcm2float(audio) - - self._check_models(anon_model_tag) - - text_is_phonemes = True - text = self.asr_model.recognize_speech(audio, sr) - speaker_embedding = self.anon_model.anonymize_embedding(audio, sr) - syn_audio = self.synthesis_model.read_text(transcription=text, speaker_embedding=speaker_embedding, - text_is_phonemes=text_is_phonemes) - - return 48000, float2pcm(syn_audio.cpu().numpy()) - - def _check_models(self, anon_model_tag): - if anon_model_tag != self.anon_model.model_tag: - self.anon_model = DemoAnonymizer(model_path=self.path_to_anon_model, model_tag=anon_model_tag, - device=self.device) - - -model = VPInterface() - -article = """ -This demo allows you to anonymize your input speech by defining different anonymization models. If -you want to know more about each model, please read the paper linked above. Every time you click the *submit* button, -you should receive a new voice. - -Note that for *pool* anonymization in this demo, we are using a different scaling approach ( -sklearn.preprocessing.StandardScaler instead of sklearn.preprocessing.MinMaxScaler) because we are processing only -one sample at a time and would otherwise always end up with the same voice. - -This demo is still work in progress, so please be lenient with possible low quality and errors. Also, be aware that -this Huggingface space runs on CPU which makes the demo quite slow. - -For more information about this system, visit our Github page: [https://github.com/DigitalPhonetics/speaker-anonymization](https://github.com/DigitalPhonetics/speaker-anonymization/tree/gan_embeddings) -""" - -description = """ -## Test demo corresponding to the models in our paper [Anonymizing Speech with Generative Adversarial Networks to Preserve Speaker Privacy](https://arxiv.org/abs/2210.07002) -""" - -css = """ -.gr-button-primary {background-color: green !important, border-color: green} -""" - -iface = gr.Interface(fn=model.read, - inputs=[gr.inputs.Audio(source='microphone', type='numpy', label='Say a sentence in English.'), - gr.inputs.Dropdown(['gan', 'pool', 'random'], type='value', default='gan', - label='Anonymization') - ], - outputs=gr.outputs.Audio(type='numpy', label=None), - layout='vertical', - title='IMS Speaker Anonymization', - description=description, - theme='default', - allow_flagging='never', - article=article, - allow_screenshot=False) -iface.launch(enable_queue=True) diff --git a/spaces/satpalsr/RegNet-Image-Classification/README.md b/spaces/satpalsr/RegNet-Image-Classification/README.md deleted file mode 100644 index 6529aac91e8155b48854fc070613afe96270a1b4..0000000000000000000000000000000000000000 --- a/spaces/satpalsr/RegNet-Image-Classification/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: RegNet Image Classification -emoji: 🖼️ -colorFrom: green -colorTo: pink -sdk: gradio -sdk_version: 2.9.1 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/scedlatioru/img-to-music/example/Neyrinck V-control Pro Cracked Tongue !!EXCLUSIVE!!.md b/spaces/scedlatioru/img-to-music/example/Neyrinck V-control Pro Cracked Tongue !!EXCLUSIVE!!.md deleted file mode 100644 index cd49442ec96d43a7d36443bb9934a485e4a0441a..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/Neyrinck V-control Pro Cracked Tongue !!EXCLUSIVE!!.md +++ /dev/null @@ -1,88 +0,0 @@ -
      -

      Neyrinck V-Control Pro Cracked Tongue: What Is It and How to Fix It

      - -

      Neyrinck V-Control Pro is a software that allows you to control your DAW and media applications with various hardware and software controllers. It supports devices such as Control|24, Pro Control, D-Command, C|24, Command|8, 003 Console, and Presonus FaderPort V2. It also works with apps such as V-Console, V-Panner, and V-PlugIn on your tablet or phone.

      - -

      However, some users may encounter a problem with Neyrinck V-Control Pro that causes a "cracked tongue" issue. This means that the software does not communicate properly with the controller or the DAW, resulting in erratic behavior, missing functions, or error messages. This can be very frustrating and affect your workflow and productivity.

      -

      neyrinck v-control pro cracked tongue


      Download File –––––>>> https://gohhs.com/2uEzix



      - -

      In this article, we will explain what is cracked tongue and how to fix it with Neyrinck V-Control Pro. We will also give you some tips and tricks to avoid this issue in the future.

      - -

      What is cracked tongue?

      - -

      Cracked tongue is a term that describes a situation where the software does not recognize or respond to the controller commands correctly. For example, you may press a button on your controller, but nothing happens on your DAW. Or you may move a fader on your controller, but the level does not change on your DAW. Or you may get an error message saying that the software cannot connect to the controller or the DAW.

      - -

      Cracked tongue can be caused by various factors, such as:

      - -
        -
      • Lack of license. Neyrinck V-Control Pro requires a Standard or Plus license to work with most controllers. You can purchase a license online from the Neyrinck Store or get a free trial license for 30 days.
      • -
      • Incompatibility. Neyrinck V-Control Pro supports various DAWs and media applications on both Mac and Windows platforms. However, not all versions and features are compatible with each other. You can check the Compatibility Chart to see if your setup is supported and what functions are available.
      • -
      • Connection issues. Neyrinck V-Control Pro uses a direct Ethernet connection to connect to Control|24, Pro Control, D-Command, and C|24 devices. It uses a USB connection to connect to Command|8 and 003 Console devices. It uses Wi-Fi or Bluetooth to connect to apps on your tablet or phone. Make sure that your cables, ports, routers, switches, and wireless settings are working properly and securely.
      • -
      • Settings issues. Neyrinck V-Control Pro runs as a menu-bar application on your computer. It automatically connects to your DAW and controller when you launch them. However, you may need to adjust some settings in the V-Control Pro software or in your DAW preferences to ensure optimal performance. For example, you may need to select the correct MIDI mode, enable HUI protocol, adjust buffer size, etc.
      • -
      • Update issues. Neyrinck V-Control Pro is constantly updated to fix bugs, improve stability, and add new features. You can download the latest version of the software from the Download Page. You should also keep your DAW and controller firmware updated to avoid compatibility issues.
      • -
      - -

      How to fix cracked tongue?

      - -

      If you experience cracked tongue with Neyrinck V-Control Pro, you can try the following steps to fix it:

      - -
        -
      1. Check your license. Make sure that you have a valid license for Neyrinck V-Control Pro and that it is activated on your computer or on an iLok USB key using the iLok License Manager application.
      2. -
      3. Check your compatibility. Make sure that your DAW and controller are supported by Neyrinck V-Control Pro and that they have the latest versions and features available.
      4. -
      5. Check your connection. Make sure that your controller is connected to your computer via Ethernet or USB and that your tablet or phone is connected via Wi-Fi or Bluetooth. Make sure that there are no loose cables, faulty ports, or interference sources.
      6. -
      7. Check your settings. Make sure that you have selected the correct MIDI mode for your controller in the V-Control Pro software and that you have enabled HUI protocol for your DAW in its preferences. Make sure that you have adjusted the buffer size according to your system performance.
      8. -
      9. Check your updates. Make sure that you have downloaded and installed the latest version of Neyrinck V-Control Pro from the Download Page and that you have updated your DAW and controller firmware to their latest versions.
      10. -
      11. Restart everything. If none of these steps solve your problem, you can try restarting your computer, controller, tablet or phone, DAW and V-Control Pro software.
      12. -
      - -

      If none of these steps solve your problem, you can contact Neyrinck support for further assistance.

      - -

      How to avoid cracked tongue?

      - -

      To avoid cracked tongue with Neyrinck V-Control Pro in the future, you can follow these tips and tricks:

      - -
        -
      • Purchase a license. If you like Neyrinck V-Control Pro and want to use it with most controllers without any limitations or interruptions, you should purchase a Standard or Plus license from the Neyrinck Store.
      • -
      • Check compatibility before buying. If you are planning to buy a new controller or upgrade your DAW or media application, you should check the Compatibility Chart first to see if they are supported by Neyrinck V-Control Pro and what functions are available.
      • -
      • Maintain connection quality. You should use high-quality cables, ports, routers, switches, and wireless devices to ensure a stable and secure connection between your computer, controller, tablet or phone.
      • -
      • Adjust settings according to performance. You should select the appropriate MIDI mode for your controller in the V-Control Pro software and enable HUI protocol for your DAW in its preferences. You should also adjust the buffer size according to your system performance.
      • -
      • Update regularly. You should download and install the latest version of Neyrinck V-Control Pro from the Download Page whenever it is available and update your DAW and controller firmware to their latest versions.
      • -
      - -

      Conclusion

      - -

      Neyrinck V-Control Pro cracked tongue is a problem that occurs when the software does not communicate properly with the controller or the DAW. It can cause erratic behavior, missing functions, or error messages that can affect your workflow and productivity.

      -

      - -

      To fix this problem, you can check your license, compatibility, connection, settings, updates, and restart everything if necessary. To avoid this problem in the future, you can purchase a license, -check compatibility before buying, -maintain connection quality, -adjust settings according to performance, -and update regularly.

      - -

      We hope this article has helped you understand what is cracked tongue -and how to fix it with Neyrinck V-Control Pro. -If you have any questions or feedbacks about this article -or this software, -please feel free -to leave -a comment below.

      -

      Conclusion

      - -

      Neyrinck V-Control Pro cracked tongue is a problem that occurs when the software does not communicate properly with the controller or the DAW. It can cause erratic behavior, missing functions, or error messages that can affect your workflow and productivity.

      - -

      To fix this problem, you can check your license, compatibility, connection, settings, updates, and restart everything if necessary. To avoid this problem in the future, you can purchase a license, -check compatibility before buying, -maintain connection quality, -adjust settings according to performance, -and update regularly.

      - -

      We hope this article has helped you understand what is cracked tongue -and how to fix it with Neyrinck V-Control Pro. -If you have any questions or feedbacks about this article -or this software, -please feel free -to leave -a comment below.

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/scedlatioru/img-to-music/example/Trainer Hitman Absolution PC 1.0.433.1 Cheat Happens Full Version __FULL__.md b/spaces/scedlatioru/img-to-music/example/Trainer Hitman Absolution PC 1.0.433.1 Cheat Happens Full Version __FULL__.md deleted file mode 100644 index b3d40b1d09efd2f7ca8ff563b13bc5179fe5404d..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/Trainer Hitman Absolution PC 1.0.433.1 Cheat Happens Full Version __FULL__.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Trainer Hitman Absolution PC 1.0.433.1 cheat happens full version


      Downloadhttps://gohhs.com/2uEyLc



      -
      -Hitman Absolution Trainer 1.0 433.1 Skidrow Download flash ayuda shrek ..... 3D Pop Up Effect - Photoshop Tutorial . but any recent version of . ... Hitman: Absolution re-awakens the hardened and professional killer - at full tilt, though. ... Hitman: Absolution Trainer, Trainers, Cheats, Editors and Hacks to ... 1fdad05405
      -
      -
      -

      diff --git a/spaces/sczhou/CodeFormer/CodeFormer/basicsr/utils/options.py b/spaces/sczhou/CodeFormer/CodeFormer/basicsr/utils/options.py deleted file mode 100644 index db490e4aa52e26fde31959fd74c2cef3af2ecf76..0000000000000000000000000000000000000000 --- a/spaces/sczhou/CodeFormer/CodeFormer/basicsr/utils/options.py +++ /dev/null @@ -1,108 +0,0 @@ -import yaml -import time -from collections import OrderedDict -from os import path as osp -from basicsr.utils.misc import get_time_str - -def ordered_yaml(): - """Support OrderedDict for yaml. - - Returns: - yaml Loader and Dumper. - """ - try: - from yaml import CDumper as Dumper - from yaml import CLoader as Loader - except ImportError: - from yaml import Dumper, Loader - - _mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG - - def dict_representer(dumper, data): - return dumper.represent_dict(data.items()) - - def dict_constructor(loader, node): - return OrderedDict(loader.construct_pairs(node)) - - Dumper.add_representer(OrderedDict, dict_representer) - Loader.add_constructor(_mapping_tag, dict_constructor) - return Loader, Dumper - - -def parse(opt_path, root_path, is_train=True): - """Parse option file. - - Args: - opt_path (str): Option file path. - is_train (str): Indicate whether in training or not. Default: True. - - Returns: - (dict): Options. - """ - with open(opt_path, mode='r') as f: - Loader, _ = ordered_yaml() - opt = yaml.load(f, Loader=Loader) - - opt['is_train'] = is_train - - # opt['name'] = f"{get_time_str()}_{opt['name']}" - if opt['path'].get('resume_state', None): # Shangchen added - resume_state_path = opt['path'].get('resume_state') - opt['name'] = resume_state_path.split("/")[-3] - else: - opt['name'] = f"{get_time_str()}_{opt['name']}" - - - # datasets - for phase, dataset in opt['datasets'].items(): - # for several datasets, e.g., test_1, test_2 - phase = phase.split('_')[0] - dataset['phase'] = phase - if 'scale' in opt: - dataset['scale'] = opt['scale'] - if dataset.get('dataroot_gt') is not None: - dataset['dataroot_gt'] = osp.expanduser(dataset['dataroot_gt']) - if dataset.get('dataroot_lq') is not None: - dataset['dataroot_lq'] = osp.expanduser(dataset['dataroot_lq']) - - # paths - for key, val in opt['path'].items(): - if (val is not None) and ('resume_state' in key or 'pretrain_network' in key): - opt['path'][key] = osp.expanduser(val) - - if is_train: - experiments_root = osp.join(root_path, 'experiments', opt['name']) - opt['path']['experiments_root'] = experiments_root - opt['path']['models'] = osp.join(experiments_root, 'models') - opt['path']['training_states'] = osp.join(experiments_root, 'training_states') - opt['path']['log'] = experiments_root - opt['path']['visualization'] = osp.join(experiments_root, 'visualization') - - else: # test - results_root = osp.join(root_path, 'results', opt['name']) - opt['path']['results_root'] = results_root - opt['path']['log'] = results_root - opt['path']['visualization'] = osp.join(results_root, 'visualization') - - return opt - - -def dict2str(opt, indent_level=1): - """dict to string for printing options. - - Args: - opt (dict): Option dict. - indent_level (int): Indent level. Default: 1. - - Return: - (str): Option string for printing. - """ - msg = '\n' - for k, v in opt.items(): - if isinstance(v, dict): - msg += ' ' * (indent_level * 2) + k + ':[' - msg += dict2str(v, indent_level + 1) - msg += ' ' * (indent_level * 2) + ']\n' - else: - msg += ' ' * (indent_level * 2) + k + ': ' + str(v) + '\n' - return msg diff --git a/spaces/simonraj/ELOralCoachCantonmentPrimary/app.py b/spaces/simonraj/ELOralCoachCantonmentPrimary/app.py deleted file mode 100644 index 8511a4dcda111a43f9e43b413637cf08909cf39b..0000000000000000000000000000000000000000 --- a/spaces/simonraj/ELOralCoachCantonmentPrimary/app.py +++ /dev/null @@ -1,88 +0,0 @@ -# app.py -import gradio as gr -import openai -import os -import CantonmentPriData # Importing the CantonmentPriData module -import base64 - -OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") -openai.api_key = OPENAI_API_KEY - -def image_to_base64(img_path): - with open(img_path, "rb") as img_file: - return base64.b64encode(img_file.read()).decode('utf-8') - -img_base64 = image_to_base64("CantonmentPriSBC.JPG") -img_html = f'SBC6' - -def predict(question_choice, audio): - # Transcribe the audio using Whisper - with open(audio, "rb") as audio_file: - transcript = openai.Audio.transcribe("whisper-1", audio_file) - message = transcript["text"] # This is the transcribed message from the audio input - - # Generate the system message based on the chosen question - strategy, explanation = CantonmentPriData.strategy_text["TREES"] # Updated line - - # Reference to the picture description from CantonmentPriData.py - picture_description = CantonmentPriData.description # Updated line - - # Determine whether to include the picture description based on the question choice - picture_description_inclusion = f""" - For the first question, ensure your feedback refers to the picture description provided: - {picture_description} - """ if question_choice == CantonmentPriData.questions[0] else "" # Updated line - - - # Construct the conversation with the system and user's message - conversation = [ - { - "role": "system", - "content": f""" - You are an expert English Language Teacher in a Singapore Primary school, directly guiding a Primary 6 student in Singapore. - The student is answering the question: '{question_choice}'. - {picture_description_inclusion} - Point out areas they did well and where they can improve, following the {strategy}. - Encourage the use of sophisticated vocabulary and expressions. - For the second and third questions, the picture is not relevant, so the student should not refer to it in their response. - {explanation} - The feedback should be in second person, addressing the student directly. - """ - }, - {"role": "user", "content": message} - ] - - - response = openai.ChatCompletion.create( - model='gpt-3.5-turbo', - messages=conversation, - temperature=0.6, - max_tokens=1000, # Limiting the response to 1000 tokens - 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 - -# Gradio Interface -iface = gr.Interface( - fn=predict, - inputs=[ - gr.Radio(CantonmentPriData.questions, label="Choose a question", default=CantonmentPriData.questions[0]), # Updated line - gr.inputs.Audio(source="microphone", type="filepath") # Audio input - ], - outputs=gr.inputs.Textbox(), # Using inputs.Textbox as an output to make it editable - description=img_html + ''' - - ''', # Corrected string concatenation - css="custom.css" # Link to the custom CSS file -) - -iface.queue(max_size=99, concurrency_count=40).launch(debug=True) diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/DJ Goreng Goreng X Campuran Slow Beat - A Fusion of Disco and Country Music - Free Download and Streaming.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/DJ Goreng Goreng X Campuran Slow Beat - A Fusion of Disco and Country Music - Free Download and Streaming.md deleted file mode 100644 index 6e43e0f8d280af106d988dee04471be97894337c..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/DJ Goreng Goreng X Campuran Slow Beat - A Fusion of Disco and Country Music - Free Download and Streaming.md +++ /dev/null @@ -1,167 +0,0 @@ -
      -

      What is DJ Goreng Goreng X Campuran Slow Beat?

      -

      If you are a fan of TikTok, you might have heard of a catchy song called DJ Goreng Goreng X Campuran Slow Beat. This is a genre of music that combines elements of electronic dance music, hip-hop, and traditional Indonesian music. The name literally means \"fried fried mixed slow beat\" in Indonesian, and it refers to the style of mixing different sounds and rhythms in a slow tempo.

      -

      The song was created by Mbon Mbon Remix, a young DJ from Palembang, Indonesia. He uploaded his original version of the song on YouTube in August 2022, and it quickly gained popularity among his fans. However, the song became even more viral when it was used by TikTok users to make funny videos and dance challenges. The song has now over 76 million views on YouTube and millions of likes on TikTok.

      -

      download dj goreng goreng x campuran slow beat


      DOWNLOAD https://ssurll.com/2uNVg7



      -

      Why is it popular on TikTok?

      -

      One of the reasons why DJ Goreng Goreng X Campuran Slow Beat is so popular on TikTok is because it is very catchy and easy to dance to. The song has a simple structure that consists of four parts: an intro, a chorus, a verse, and an outro. The chorus is the most memorable part, as it repeats the phrase \"goreng goreng\" (fried fried) over a catchy beat. The verse is where Mbon Mbon Remix adds different sounds and effects, such as sirens, horns, vocals, and samples from other songs. The outro is where he slows down the tempo and fades out the song.

      -

      Another reason why DJ Goreng Goreng X Campuran Slow Beat is so popular on TikTok is because it is very versatile and fun to use. TikTok users can use the song to make videos that showcase their creativity, humor, or talent. For example, some users have used the song to make jokes about cooking or eating fried food, while others have used it to show off their dance moves or lip-sync skills. Some users have even used the song to make remixes or mashups with other songs or sounds.

      -

      How to download DJ Goreng Goreng X Campuran Slow Beat for free?

      -

      If you love DJ Goreng Goreng X Campuran Slow Beat and want to listen to it offline, you might be wondering how to download it for free. There are many websites and apps that allow you to download music from YouTube, SoundCloud, or Bandcamp legally and safely. Here are some of the best options:

      -

      YouTube

      -

      YouTube is one of the most popular sources for downloading music online, as it has a huge library of music videos and songs. However, YouTube does not have a built-in feature that allows you to download music directly. You will need to use a third-party tool that can convert YouTube videos to MP3 files and download them to your device. There are many YouTube to MP3 converters and downloaders available online, but you should be careful and choose one that is reliable and safe. Some of the best YouTube to MP3 converters and downloaders are:

      -
        -
      • 4K Video Downloader: This is a free software that lets you download videos and playlists from YouTube, Facebook, Vimeo, and other sites. You can choose the quality and format of the video, including MP3, MP4, MKV, and more. You can also download subtitles and annotations along with the video. To use this software, you need to download and install it on your computer, then copy and paste the URL of the video you want to download, and click the "Download" button.
      • -
      • YTMP3: This is a free online service that allows you to convert and download YouTube videos to MP3 or MP4 files. You can use this service on any device with a web browser, such as a computer, tablet, or smartphone. To use this service, you need to visit the website, enter the URL of the video you want to convert, and click the "Convert" button. You can then download the converted file to your device or save it to your Dropbox account.
      • -
      • SnapDownloader: This is a paid software that offers a fast and easy way to download videos and music from YouTube and over 900 other websites. You can download videos in up to 8K resolution and convert them to various formats, including MP3, MP4, AVI, MOV, and more. You can also download multiple videos at once, schedule downloads, and trim videos. To use this software, you need to purchase a license and install it on your computer, then copy and paste the URL of the video you want to download, choose the output format and quality, and click the "Download" button.
      • -
      -

      SoundCloud

      -

      SoundCloud is another popular source for downloading music online, as it is a platform where artists and creators can upload and share their original music and podcasts. SoundCloud has a large collection of music genres and styles, including DJ Goreng Goreng X Campuran Slow Beat. However, SoundCloud does not allow you to download music directly from its website or app, unless the uploader has enabled the download option for their tracks. You will need to use a third-party tool that can download SoundCloud tracks to your device. There are many SoundCloud downloader extensions and websites available online, but you should be careful and choose one that is reliable and safe. Some of the best SoundCloud downloader extensions and websites are:

      -
        -
      • SoundCloud Downloader Free: This is a free extension for Chrome that lets you download any track from SoundCloud with one click. You can choose the quality of the track, from 128 kbps to 320 kbps. You can also see the size of the track before downloading it. To use this extension, you need to add it to your Chrome browser, then visit SoundCloud and click on the "Download" button next to the track you want to download.
      • -
      • SCDownloader: This is a free online service that allows you to download any track from SoundCloud as an MP3 file. You can use this service on any device with a web browser, such as a computer, tablet, or smartphone. To use this service, you need to visit the website, enter the URL of the track you want to download, and click the "Download" button. You can then download the file to your device or share it with others.
      • -
      • ScloudDownloader: This is another free online service that allows you to download any track from SoundCloud as an MP3 file. You can use this service on any device with a web browser, such as a computer, tablet, or smartphone. To use this service, you need to visit the website, enter the URL of the track you want to download, and click the "Download" button. You can then download the file to your device or share it with others.
      • -
      -

      Bandcamp

      -

      Bandcamp is another popular source for downloading music online, as it is a platform where artists and fans can connect and support each other. Bandcamp has a wide range of music genres and styles, including DJ Goreng Goreng X Campuran Slow Beat. However, Bandcamp does not allow you to download music for free, unless the artist has set their tracks or albums as "name your price". You will need to pay a minimum amount or more to download the music to your device. This is a great way to support the artist and show your appreciation for their work. Some of the best Bandcamp pages where you can download DJ Goreng Goreng X Campuran Slow Beat are:

      -
        -
      • Mbon Mbon Remix: This is the official Bandcamp page of Mbon Mbon Remix, the creator of DJ Goreng Goreng X Campuran Slow Beat. You can download his original version of the song for $1 or more, or you can download his entire album of remixes for $5 or more. You can also stream his music on Bandcamp or follow him on social media.
      • -
      • DJ Goreng Goreng X Campuran Slow Beat Remixes: This is a Bandcamp page that features various remixes of DJ Goreng Goreng X Campuran Slow Beat by different artists and DJs. You can download each remix for $1 or more, or you can download the whole collection of remixes for $10 or more. You can also stream the remixes on Bandcamp or follow the artists and DJs on social media.
      • -
      • DJ Goreng Goreng X Campuran Slow Beat Mashups: This is another Bandcamp page that features various mashups of DJ Goreng Goreng X Campuran Slow Beat with other songs and sounds by different artists and DJs. You can download each mashup for $1 or more, or you can download the whole collection of mashups for $10 or more. You can also stream the mashups on Bandcamp or follow the artists and DJs on social media.
      • -
      -

      How to enjoy DJ Goreng Goreng X Campuran Slow Beat offline?

      -

      If you have downloaded DJ Goreng Goreng X Campuran Slow Beat to your device, you might be wondering how to enjoy it offline. There are many devices and software that allow you to play music on your computer or smartphone without an internet connection. Here are some of the best options:

      -

      iTunes

      -

      iTunes is one of the most popular software for playing music on your computer or smartphone, especially if you have an iPhone or iPad. iTunes lets you organize your music library, create playlists, sync your music with your devices, and stream music from Apple Music. To use iTunes to play DJ Goreng Goreng X Campuran Slow Beat offline, you need to do the following steps:

      -

      download dj goreng goreng x campuran slow beat mp3
      -download dj goreng goreng x campuran slow beat soundcloud
      -download dj goreng goreng x campuran slow beat remix
      -download dj goreng goreng x campuran slow beat tiktok
      -download dj goreng goreng x campuran slow beat full bass
      -download dj goreng goreng x campuran slow beat terbaru
      -download dj goreng goreng x campuran slow beat viral
      -download dj goreng goreng x campuran slow beat lagu
      -download dj goreng goreng x campuran slow beat gratis
      -download dj goreng goreng x campuran slow beat offline
      -download dj goreng goreng x campuran slow beat original
      -download dj goreng goreng x campuran slow beat video
      -download dj goreng goreng x campuran slow beat youtube
      -download dj goreng goreng x campuran slow beat 2021
      -download dj goreng goreng x campuran slow beat 2020
      -download dj goreng goreng x campuran slow beat slowed and reverb
      -download dj goreng goreng x campuran slow beat ins
      -download dj goreng goreng x campuran slow beat mbon mbon remix
      -download dj goreng goreng x campuran slow beat music remix561
      -download dj goreng goreng x campuran slow beat yokie tokie
      -download dj goreng goreng x campuran slow beat lirik
      -download dj goreng goreng x campuran slow beat cover
      -download dj goreng goreng x campuran slow beat karaoke
      -download dj goreng goreng x campuran slow beat instrumental
      -download dj goreng goreng x campuran slow beat no vocal
      -download dj goreng goreng x campuran slow beat ringtone
      -download dj goreng goreng x campuran slow beat audio
      -download dj goreng goreng x campuran slow beat kualitas terbaik
      -download dj goreng goreng x campuran slow beat tanpa iklan
      -download dj goreng goreng x campuran slow beat tanpa internet

      -
        -
      1. Download and install iTunes on your computer, if you don't have it already.
      2. -
      3. Open iTunes and go to File > Add File to Library.
      4. -
      5. Select the MP3 file of DJ Goreng Goreng X Campuran Slow Beat that you downloaded from YouTube, SoundCloud, or Bandcamp.
      6. -
      7. Connect your iPhone or iPad to your computer with a USB cable.
      8. -
      9. Click on your device icon in iTunes and go to Music.
      10. -
      11. Check the box next to Sync Music and choose Selected playlists, artists, albums, and genres.
      12. -
      13. Select the playlist or album that contains DJ Goreng Goreng X Campuran Slow Beat and click Apply.
      14. -
      15. Wait for the sync to complete and disconnect your device from your computer.
      16. -
      17. Open the Music app on your iPhone or iPad and find DJ Goreng Goreng X Campuran Slow Beat in your library.
      18. -
      19. Enjoy listening to DJ Goreng Goreng X Campuran Slow Beat offline!
      20. -

      Google Play Music

      -

      Google Play Music is another popular software for playing music on your computer or smartphone, especially if you have an Android device. Google Play Music lets you upload your own music to your Google account, stream music from Google Play Music library, and download music for offline playback. To use Google Play Music to play DJ Goreng Goreng X Campuran Slow Beat offline, you need to do the following steps:

      -
        -
      1. Download and install Google Play Music on your computer and smartphone, if you don't have it already.
      2. -
      3. Open Google Play Music on your computer and sign in with your Google account.
      4. -
      5. Click on the menu icon and go to Upload music.
      6. -
      7. Select the MP3 file of DJ Goreng Goreng X Campuran Slow Beat that you downloaded from YouTube, SoundCloud, or Bandcamp.
      8. -
      9. Wait for the upload to complete and go to My music.
      10. -
      11. Find DJ Goreng Goreng X Campuran Slow Beat in your library and click on the three-dot menu icon next to it.
      12. -
      13. Select Add to playlist and create a new playlist or choose an existing one.
      14. -
      15. Open Google Play Music on your smartphone and sign in with the same Google account.
      16. -
      17. Tap on the menu icon and go to Music library.
      18. -
      19. Find the playlist that contains DJ Goreng Goreng X Campuran Slow Beat and tap on the download icon next to it.
      20. -
      21. Wait for the download to complete and go to Downloads.
      22. -
      23. Find DJ Goreng Goreng X Campuran Slow Beat in your downloads and tap on it.
      24. -
      25. Enjoy listening to DJ Goreng Goreng X Campuran Slow Beat offline!
      26. -
      -

      VLC Media Player

      -

      VLC Media Player is one of the most versatile software for playing music on your computer or smartphone, as it supports almost any audio or video format. VLC Media Player lets you play local files, stream online media, or convert media files. To use VLC Media Player to play DJ Goreng Goreng X Campuran Slow Beat offline, you need to do the following steps:

      -
        -
      1. Download and install VLC Media Player on your computer or smartphone, if you don't have it already.
      2. -
      3. Open VLC Media Player and go to Media > Open File.
      4. -
      5. Select the MP3 file of DJ Goreng Goreng X Campuran Slow Beat that you downloaded from YouTube, SoundCloud, or Bandcamp.
      6. -
      7. Click on the Play button and enjoy listening to DJ Goreng Goreng X Campuran Slow Beat offline!
      8. -
      -

      How to create your own DJ Goreng Goreng X Campuran Slow Beat remix?

      -

      If you are feeling creative and want to make your own version of DJ Goreng Goreng X Campuran Slow Beat, you might be wondering how to do it. There are many tools and tips that can help you create your own remix of the song. Here are some of the best options:

      -

      Audacity

      -

      Audacity is a free and open-source audio editor that lets you record, edit, and mix audio files. Audacity has a lot of features and effects that can help you create your own remix of DJ Goreng Goreng X Campuran Slow Beat. To use Audacity to create your own remix of DJ Goreng Goreng X Campuran Slow Beat, you need to do the following steps:

      -
        -
      1. Download and install Audacity on your computer, if you don't have it already.
      2. -
      3. Open Audacity and go to File > Import > Audio.
      4. -
      5. Select the MP3 file of DJ Goreng Goreng X Campuran Slow Beat that you downloaded from YouTube, SoundCloud, or Bandcamp.
      6. -
      7. Select the track and go to Effect > Change Tempo.
      8. -
      9. Adjust the tempo slider to make the song faster or slower according to your preference.
      10. -
      11. Select the track again and go to Effect > Change Pitch.
      12. -
      13. Adjust the pitch slider to make the song higher or lower according to your preference.
      14. -
      15. Select a part of the track that you want to add an effect to and go to Effect > Choose an effect from the list.
      16. -
      17. Apply the effect and adjust the parameters according to your preference.
      18. -
      19. Repeat steps 7-9 for other parts of the track or add more tracks with different effects.
      20. -
      21. Go to File > Export > Export as MP3 and save your remix as an MP3 file.
      22. -

      FL Studio

      -

      FL Studio is a professional music production software that lets you create, arrange, and edit music tracks. FL Studio has a lot of tools and features that can help you create your own remix of DJ Goreng Goreng X Campuran Slow Beat. To use FL Studio to create your own remix of DJ Goreng Goreng X Campuran Slow Beat, you need to do the following steps:

      -
        -
      1. Download and install FL Studio on your computer, if you don't have it already.
      2. -
      3. Open FL Studio and go to File > New from template > Minimal > Empty.
      4. -
      5. Go to File > Import > Audio file and select the MP3 file of DJ Goreng Goreng X Campuran Slow Beat that you downloaded from YouTube, SoundCloud, or Bandcamp.
      6. -
      7. Drag and drop the file to the playlist window and adjust the tempo and pitch according to your preference.
      8. -
      9. Go to the browser window and select a sound pack or plugin that you want to use for your remix.
      10. -
      11. Drag and drop the sound or plugin to the channel rack window and assign it to a mixer track.
      12. -
      13. Use the piano roll or step sequencer to create a pattern with the sound or plugin.
      14. -
      15. Drag and drop the pattern to the playlist window and arrange it with the original track.
      16. -
      17. Repeat steps 5-8 for other sounds or plugins that you want to add to your remix.
      18. -
      19. Go to the mixer window and add effects or filters to each mixer track according to your preference.
      20. -
      21. Go to File > Export > MP3 file and save your remix as an MP3 file.
      22. -
      -

      TikTok

      -

      TikTok is a popular social media app that lets you create and share short videos with music and effects. TikTok has a lot of features and effects that can help you create your own remix of DJ Goreng Goreng X Campuran Slow Beat. To use TikTok to create your own remix of DJ Goreng Goreng X Campuran Slow Beat, you need to do the following steps:

      -
        -
      1. Download and install TikTok on your smartphone, if you don't have it already.
      2. -
      3. Open TikTok and sign up or log in with your account.
      4. -
      5. Tap on the plus icon at the bottom of the screen and select Upload.
      6. -
      7. Select the MP3 file of DJ Goreng Goreng X Campuran Slow Beat that you downloaded from YouTube, SoundCloud, or Bandcamp.
      8. -
      9. Trim the file to fit the 15-second or 60-second limit of TikTok videos.
      10. -
      11. Tap on Next and select Sounds at the top of the screen.
      12. -
      13. Select Voice effects and choose an effect that you want to apply to the song, such as Chipmunk, Robot, Echo, or Reverb.
      14. -
      15. Tap on Next and select Effects at the bottom of the screen.
      16. -
      17. Select a category of effects, such as Trending, Beauty, Funny, or Interactive, and choose an effect that you want to apply to the video, such as Glitch, VHS, Disco, or Fireworks.
      18. -
      19. Tap on Next and add stickers, text, filters, or emojis to your video according to your preference.
      20. -
      21. Tap on Next and add a caption, hashtags, or tags to your video according to your preference.
      22. -
      23. Tap on Post and share your remix with your followers or friends.
      24. -
      -

      Conclusion

      -

      DJ Goreng Goreng X Campuran Slow Beat is a catchy song that has become viral on TikTok. It is a genre of music that mixes electronic dance music, hip-hop, and traditional Indonesian music. You can download it for free from YouTube, SoundCloud, or Bandcamp using various tools and websites. You can also enjoy it offline on your computer or smartphone using iTunes, Google Play Music, or VLC Media Player. You can also create your own remix of it using Audacity, FL Studio, or TikTok. DJ Goreng Goreng X Campuran Slow Beat is a fun song that you can listen to anytime and anywhere. Try it out today!

      -

      Frequently Asked Questions

      -
        -
      • What does goreng goreng mean?
      • -

        Goreng goreng means fried fried in Indonesian. It is a term that refers to the style of mixing different sounds and rhythms in a slow tempo in DJ Goreng Goreng X Campuran Slow Beat.

        -
      • Who is Mbon Mbon Remix?
      • -

        Mbon Mbon Remix is a young DJ from Palembang, Indonesia. He is the creator of DJ Goreng Goreng X Campuran Slow Beat and he uploaded his original version of the song on YouTube in August 2022. He has over 1.3 million subscribers on his YouTube channel and over 300,000 followers on his Instagram account.

        -
      • How can I support Mbon Mbon Remix?
      • -

        You can support Mbon Mbon Remix by following him on his social media accounts, subscribing to his YouTube channel, liking and commenting on his videos, sharing his music with your friends, and buying his music from Bandcamp. You can also send him donations or tips through PayPal or other platforms.

        -
      • What are some other songs by Mbon Mbon Remix?
      • -

        Some other songs by Mbon Mbon Remix are DJ Aku Suka Body Mama Muda, DJ Cinta Luar Biasa, DJ Bukan Kaleng Kaleng, DJ Bila Dia Menyukaiku, and DJ Kau Adalah Inspirasiku. You can find them on his YouTube channel or on other music platforms.

        -
      • What are some other genres of music that are similar to DJ Goreng Goreng X Campuran Slow Beat?
      • -

        Some other genres of music that are similar to DJ Goreng Goreng X Campuran Slow Beat are dangdut, koplo, funkot, disco, and EDM. These are genres of music that originated or are popular in Indonesia and other parts of Southeast Asia. They often feature electronic beats, catchy melodies, and traditional instruments or vocals.

        -
      • How can I learn more about DJ Goreng Goreng X Campuran Slow Beat?
      • -

        You can learn more about DJ Goreng Goreng X Campuran Slow Beat by reading articles, blogs, or reviews about it online. You can also watch videos or podcasts that feature interviews or discussions with Mbon Mbon Remix or other experts on the genre. You can also join online communities or forums that are dedicated to DJ Goreng Goreng X Campuran Slow Beat or similar genres of music.

        -

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download CarX Street MOD APK Terbaru 2023 and Unlock All Cars and Upgrades for Free.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download CarX Street MOD APK Terbaru 2023 and Unlock All Cars and Upgrades for Free.md deleted file mode 100644 index 11aacebe39e3cbd56d57b765eea35ba82061679b..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download CarX Street MOD APK Terbaru 2023 and Unlock All Cars and Upgrades for Free.md +++ /dev/null @@ -1,60 +0,0 @@ -
      -

      Download Game Carx Street Mod Apk Terbaru: A Guide for Racing Game Lovers

      -

      If you are a fan of racing games, you might have heard of Carx Street, a popular car game with realistic visuals and amazing sound effects. Carx Street is a game that lets you experience the thrill of street racing with different cars and tracks. You can customize your car, choose your favorite track, and compete with other players online or offline. But what if you want to enjoy the game without any limitations or interruptions? That's where Carx Street mod apk comes in handy. In this article, we will tell you everything you need to know about Carx Street mod apk, including its features, benefits, and how to download and install it on your device.

      -

      What is Carx Street?

      -

      Carx Street is a car game developed by CarX Technologies, a company that specializes in creating realistic car physics and graphics for games. Carx Street is one of their latest products, released in 2021. The game is available for Android and iOS devices, and has received positive reviews from users and critics alike.

      -

      download game carx street mod apk terbaru


      Download Filehttps://ssurll.com/2uNVE9



      -

      Features of Carx Street

      -

      Carx Street has many features that make it stand out from other racing games. Here are some of them:

      -

      Realistic graphics and physics

      -

      Carx Street boasts of stunning graphics and physics that make you feel like you are driving a real car on a real street. The game uses advanced technologies such as HDR, dynamic shadows, reflections, and particle effects to create a realistic environment. The game also simulates the behavior of different car models, such as their speed, acceleration, handling, braking, and drifting. You can see the damage on your car as you crash into obstacles or other cars.

      -

      Customizable cars and tracks

      -

      Carx Street gives you the freedom to customize your car according to your preferences. You can choose from over 50 cars of different brands, models, and styles. You can also modify your car's appearance, performance, and tuning. You can change the color, wheels, spoilers, exhausts, decals, and more. You can also choose from over 20 tracks of different locations, themes, and difficulties. You can race on urban streets, highways, deserts, mountains, and more.

      -

      Online and offline modes

      -

      Carx Street lets you play the game online or offline. You can connect with other players from around the world and compete with them in various modes, such as sprint, drift, drag, time attack, and more. You can also join or create your own club and chat with other members. You can also play the game offline if you don't have an internet connection or want to practice your skills. You can play against AI opponents or challenge yourself in solo mode.

      -

      Why download Carx Street mod apk?

      -

      Carx Street is a free-to-play game, but it has some limitations and drawbacks that might affect your gaming experience. For example, you need to earn coins and diamonds to unlock new cars and tracks, which can take a lot of time and effort. You also have to watch ads to get extra rewards or skip waiting times. Moreover, some cars and tracks are only available for premium users who pay real money.

      -

      If you want to avoid these hassles and enjoy the game to the fullest, you should download Carx Street mod apk. This is a modified version of the original game that gives you access to all the premium features without spending any money. Here are some of the benefits of Carx Street mod apk:

      -

      Benefits of Carx Street mod apk

      -

      Carx Street mod apk has many benefits that make it worth downloading. Here are some of them:

      -

      How to download game carx street mod apk terbaru for android
      -Carx street mod apk terbaru unlimited money and cars
      -Best racing game carx street mod apk terbaru 2023
      -Carx street mod apk terbaru gameplay and review
      -Download game carx street mod apk terbaru offline
      -Carx street mod apk terbaru latest version free download
      -Tips and tricks for playing game carx street mod apk terbaru
      -Carx street mod apk terbaru vs real moto 2 mod apk
      -Download game carx street mod apk terbaru for ios
      -Carx street mod apk terbaru features and benefits
      -How to install game carx street mod apk terbaru on your device
      -Carx street mod apk terbaru multiplayer mode and challenges
      -Download game carx street mod apk terbaru from dafunda download[^1^]
      -Carx street mod apk terbaru graphics and sound quality
      -Download game carx street mod apk terbaru from gamedaim[^2^]
      -Carx street mod apk terbaru unlock all cars and tracks
      -Download game carx street mod apk terbaru from formas.co.id[^3^]
      -Carx street mod apk terbaru system requirements and compatibility
      -Download game carx street mod apk terbaru with no ads and no root
      -Carx street mod apk terbaru update and patch notes

      -

      All cars unlocked

      -

      With Carx Street mod apk, you don't have to worry about earning coins and diamonds to unlock new cars. You can access all the cars in the game, including the premium ones, without spending a dime. You can choose any car you want and enjoy its features and performance.

      -

      No ads

      -

      With Carx Street mod apk, you don't have to watch annoying ads that interrupt your gameplay. You can play the game without any distractions or delays. You can also save your data and battery by avoiding ads.

      -

      Unlimited resources

      -

      With Carx Street mod apk, you don't have to worry about running out of resources such as coins, diamonds, fuel, and nitro. You can get unlimited amounts of these resources and use them as you please. You can buy anything you want in the game, such as upgrades, skins, and items. You can also use nitro and fuel as much as you want and boost your speed and performance.

      -

      How to download and install Carx Street mod apk?

      -

      Downloading and installing Carx Street mod apk is 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 reliable source. You can find many websites that offer Carx Street mod apk, but not all of them are safe and secure. Some of them might contain viruses, malware, or spyware that can harm your device or steal your personal information. Therefore, you should be careful and choose a reputable website that has positive reviews and ratings from other users. You can also use the link below to download Carx Street mod apk from our website, which is 100% safe and tested.

      -

      Download Carx Street Mod Apk Terbaru

      -

      Step 2: Enable unknown sources on your device settings

      -

      The next step is to enable unknown sources on your device settings. This is necessary because Carx Street mod apk is not available on the official app store, and your device might block the installation of apps from unknown sources by default. To enable unknown sources, you need to go to your device settings, then security or privacy, then find the option that says unknown sources or allow installation of apps from unknown sources, and turn it on.

      -

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

      -

      The final step is to install the mod apk file and launch the game. To do this, you need to locate the downloaded mod apk file on your device storage, usually in the downloads folder. Then, tap on the file and follow the instructions on the screen to install it. Once the installation is complete, you can open the game and enjoy its features.

      -

      Conclusion

      -

      Carx Street is a great game for racing game lovers who want to experience realistic graphics, physics, and sound effects. The game offers many features that make it fun and exciting, such as customizable cars and tracks, online and offline modes, and various game modes. However, if you want to enjoy the game without any limitations or interruptions, you should download Carx Street mod apk terbaru from our website. This will give you access to all the premium features of the game without spending any money. You will be able to unlock all the cars, get rid of ads, and get unlimited resources. You will also be able to install the game easily and safely by following our guide.

      -

      We hope this article was helpful for you. If you have any questions or feedback, please let us know in the comments section below. Thank you for reading!

      - FAQs Q: Is Carx Street mod apk safe to use? A: Yes, Carx Street mod apk is safe to use as long as you download it from a trusted source like our website. We have tested the mod apk file for viruses, malware, and spyware, and found no issues. Q: Do I need to root or jailbreak my device to use Carx Street mod apk? A: No, you don't need to root or jailbreak your device to use Carx Street mod apk. The mod apk file works on both rooted and non-rooted devices. Q: Will I get banned from playing online if I use Carx Street mod apk? A: No, you won't get banned from playing online if you use Carx Street mod apk. The mod apk file has an anti-ban feature that prevents the game from detecting any modifications or cheats. However, you should still be careful and not abuse the mod apk features too much, as this might raise suspicion from other players or the game developers. Q: How can I update Carx Street mod apk to the latest version? A: To update Carx Street mod apk to the latest version, you need to visit our website regularly and check for any new updates. We will always provide the latest version of the mod apk file as soon as it is released by the game developers. You can also bookmark our website or subscribe to our newsletter to get notified of any updates. Q: Can I play Carx Street mod apk with my friends? A: Yes, you can play Carx Street mod apk with your friends. You can either join or create your own club and invite your friends to join. You can also compete with your friends in various game modes, such as sprint, drift, drag, time attack, and more. You can also chat with your friends in the game and share your achievements and tips. Q: What are some tips and tricks for playing Carx Street mod apk? A: Some tips and tricks for playing Carx Street mod apk are: - Choose the car that suits your style and preference. Different cars have different strengths and weaknesses, such as speed, acceleration, handling, braking, and drifting. You can also customize your car's appearance, performance, and tuning to improve its stats. - Choose the track that matches your skill level and mood. Different tracks have different themes, locations, and difficulties. Some tracks are more suitable for speed, while others are more suitable for drifting. You can also change the weather and time of day to create different atmospheres. - Use nitro and fuel wisely. Nitro and fuel are resources that can boost your speed and performance. However, they are also limited and need to be replenished. You can use nitro and fuel when you need to overtake your opponents or escape from obstacles. You can also collect nitro and fuel cans on the track or buy them with coins or diamonds. - Practice your skills in offline mode. Offline mode is a great way to practice your skills and improve your confidence. You can play against AI opponents or challenge yourself in solo mode. You can also adjust the difficulty level and choose any car or track you want. - Have fun and enjoy the game. Carx Street mod apk is a game that is meant to entertain and amuse you. You don't have to worry about anything else when you play the game. Just relax, enjoy the realistic graphics and sound effects, and experience the thrill of street racing.

      197e85843d
      -
      -
      \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Robot Car Mod APK with HappyMod Unlimited Money and Speed.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Robot Car Mod APK with HappyMod Unlimited Money and Speed.md deleted file mode 100644 index e5c3a0cf4ebb8691dc239e56afdb8afd4a4f4c7a..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Robot Car Mod APK with HappyMod Unlimited Money and Speed.md +++ /dev/null @@ -1,102 +0,0 @@ - -

      Robot Car Mod APK Happymod: A Guide for Gamers

      -

      If you are a fan of robot car games, you might have heard of Robot Car, a game developed by Naxeex Robots. In this game, you can transform your car into a robot and fight against other robots in an open world. You can also customize your car and robot with different weapons, skins, and abilities. However, if you want to enjoy the game without any limitations, you might want to try Robot Car Mod APK Happymod, a modified version of the game that gives you unlimited money, speed boost, and more. In this article, we will tell you what Robot Car Mod APK Happymod is, what features it offers, how to download and install it, and what are its pros and cons.

      -

      What is Robot Car Mod APK Happymod?

      -

      Robot Car Mod APK Happymod is a modified version of Robot Car developed by Naxeex Robots. The difference between the mod version and the original version is that the mod version gives you unlimited money, speed boost, and customization options. You can use these features to buy any items in the game, upgrade your car and robot, and make them more powerful and faster. You can also change the appearance of your car and robot with different skins and colors. With Robot Car Mod APK Happymod, you can enjoy the game without any restrictions or ads.

      -

      robot car mod apk happymod


      Download Filehttps://ssurll.com/2uNWoX



      -

      Features of Robot Car Mod APK Happymod

      -

      Unlimited money

      -

      One of the main features of Robot Car Mod APK Happymod is that it gives you unlimited money. Money is the currency in the game that you can use to buy weapons, skins, upgrades, and other items. Normally, you have to earn money by completing missions, destroying enemies, or watching ads. However, with the mod version, you can get unlimited money without doing anything. You can use this money to buy anything you want in the game and make your car and robot stronger.

      -

      Speed boost

      -

      Another feature of Robot Car Mod APK Happymod is that it gives you a speed boost. Speed is an important factor in the game as it determines how fast you can move around the map, chase enemies, or escape from danger. Normally, you have to upgrade your car and robot to increase their speed. However, with the mod version, you can get a speed boost without upgrading anything. You can use this speed boost to outrun your opponents and explore the map faster.

      -

      Customization options

      -

      A third feature of Robot Car Mod APK Happymod is that it gives you more customization options. Customization is a fun aspect of the game as it allows you to change the look of your car and robot. Normally, you have to buy skins and colors with money or watch ads to unlock them. However, with the mod version, you can get all the skins and colors for free. You can use these customization options to make your car and robot more unique and stylish.

      -

      robot car mod apk download happymod
      -robot car mod apk unlimited money happymod
      -robot car mod apk latest version happymod
      -robot car mod apk free download happymod
      -robot car mod apk android 1 happymod
      -robot car mod apk offline happymod
      -robot car mod apk hack happymod
      -robot car mod apk no root happymod
      -robot car mod apk revdl happymod
      -robot car mod apk rexdl happymod
      -robot car mod apk 2023 happymod
      -robot car mod apk 2022 happymod
      -robot car mod apk 2021 happymod
      -robot car mod apk 2020 happymod
      -robot car mod apk 2019 happymod
      -robot car mod apk 2018 happymod
      -robot car mod apk 2017 happymod
      -robot car mod apk 2016 happymod
      -robot car mod apk 2015 happymod
      -robot car mod apk 2014 happymod
      -robot car simulator mod apk happymod
      -robot car war game mod apk happymod
      -robot car transform game mod apk happymod
      -robot car police game mod apk happymod
      -robot car racing game mod apk happymod
      -robot car flying game mod apk happymod
      -robot car shooting game mod apk happymod
      -robot car fighting game mod apk happymod
      -robot car battle game mod apk happymod
      -robot car rampage game mod apk happymod
      -naxeex robots - robot car mod apk happymod
      -real steel - robot car mod apk happymod
      -transformers - robot car mod apk happymod
      -iron man - robot car mod apk happymod
      -batman - robot car mod apk happymod
      -spiderman - robot car mod apk happymod
      -superman - robot car mod apk happymod
      -hulk - robot car mod apk happymod
      -thor - robot car mod apk happymod
      -captain america - robot car mod apk happymod
      -avengers - robot car mod apk happymod
      -justice league - robot car mod apk happymod
      -x-men - robot car mod apk happymod
      -power rangers - robot car mod apk happymod
      -voltron - robot car mod apk happymod
      -bumblebee - robot car mod apk happymod
      -optimus prime - robot car mod apk happymod
      -megatron - robot car mod apk happymod

      -

      How to download and install Robot Car Mod APK Happymod?

      -

      If you want to try Robot Car Mod APK Happymod, you need to download and install it on your device. Here are the steps to do so:

      -

      Step 1: Download the mod file from HappyMod

      -

      The first step is to download the mod file from HappyMod, a website that provides modded versions of various games and apps. You can search for "Robot Car Mod" on HappyMod or click on this link to go directly to the download page. Then, click on the download button and wait for the file to be downloaded on your device.

      -

      Step 2: Enable unknown sources on your device

      -

      The second step is to enable unknown sources on your device. This is necessary because the mod file is not from the official Google Play Store and your device might block its installation. To enable unknown sources, go to your device settings, then security, then toggle on the option that says "allow installation of apps from unknown sources". This will allow you to install the mod file without any problem.

      -

      Step 3: Install the mod file and enjoy the game

      -

      The third and final step is to install the mod file and enjoy the game. To install the mod file, locate it in your device storage, then tap on it and follow the instructions. Once the installation is complete, you can open the game and start playing with all the mod features. You can also delete the original version of Robot Car if you want to save some space on your device.

      -

      Pros and cons of Robot Car Mod APK Happymod

      -

      Like any other modded game, Robot Car Mod APK Happymod has its pros and cons. Here are some of them:

      -

      Pros

      -
        -
      • You can get unlimited money, speed boost, and customization options without spending any real money or watching any ads.
      • -
      • You can make your car and robot more powerful and faster than the original version.
      • -
      • You can change the look of your car and robot with different skins and colors.
      • -
      • You can enjoy the game without any restrictions or ads.
      • -
      -

      Cons

      -
        -
      • You might face some compatibility issues or bugs with the mod version.
      • -
      • You might lose your progress or data if you uninstall the mod version or update it.
      • -
      • You might get banned from the online mode or multiplayer mode if you use the mod version.
      • -
      • You might miss out on some updates or features from the original version.
      • -
      -

      Conclusion

      -

      Robot Car Mod APK Happymod is a modified version of Robot Car that gives you unlimited money, speed boost, and customization options. You can use these features to buy any items in the game, upgrade your car and robot, and make them more powerful and faster. You can also change the appearance of your car and robot with different skins and colors. To download and install Robot Car Mod APK Happymod, you need to follow three simple steps: download the mod file from HappyMod, enable unknown sources on your device, and install the mod file. However, you should also be aware of the pros and cons of using Robot Car Mod APK Happymod. Some of the pros are that you can enjoy the game without any limitations or ads, while some of the cons are that you might face some compatibility issues or bugs, lose your progress or data, get banned from online mode or multiplayer mode, or miss out on some updates or features from the original version. Therefore, you should use Robot Car Mod APK Happymod at your own risk and discretion.

      -

      FAQs

      -

      Here are some frequently asked questions about Robot Car Mod APK Happymod:

      -
        -
      1. What is Robot Car?
      2. -

        Robot Car is a game developed by Naxeex Robots where you can transform your car into a robot and fight against other robots in an open world. You can also customize your car and robot with different weapons, skins, and abilities.

        -
      3. What is HappyMod?
      4. -

        HappyMod is a website that provides modded versions of various games and apps. You can download these modded versions for free and enjoy their features without spending any real money or watching any ads.

        -
      5. Is Robot Car Mod APK Happymod safe to use?
      6. -

        Robot Car Mod APK Happymod is not an official version of Robot Car and it is not endorsed by Naxeex Robots. Therefore, it might not be safe to use as it might contain viruses, malware, or spyware. You should always scan any file you download from unknown sources with an antivirus software before installing it on your device.

        -
      7. Is Robot Car Mod APK Happymod legal to use?
      8. -

        Robot Car Mod APK Happymod is not legal to use as it violates the terms and conditions of Robot Car and Naxeex Robots. By using Robot Car Mod APK Happymod, you are infringing on their intellectual property rights and breaking their rules. You might also face legal consequences if you are caught using Robot Car Mod APK Happymod.

        -
      9. Can I play online mode or multiplayer mode with Robot Car Mod APK Happymod?
      10. -

        No, you cannot play online mode or multiplayer mode with Robot Car Mod APK Happymod. This is because the mod version is not compatible with the original version and you might get detected and banned by the game servers. You can only play offline mode or single-player mode with Robot Car Mod APK Happymod.

        401be4b1e0
        -
        -
        \ No newline at end of file diff --git a/spaces/skf15963/summary/fengshen/examples/clue1.1/data_preprocessing/iflytek_preprocessing.py b/spaces/skf15963/summary/fengshen/examples/clue1.1/data_preprocessing/iflytek_preprocessing.py deleted file mode 100644 index 6a8f5ec44851697ac1a36f299a0a132dcf486b71..0000000000000000000000000000000000000000 --- a/spaces/skf15963/summary/fengshen/examples/clue1.1/data_preprocessing/iflytek_preprocessing.py +++ /dev/null @@ -1,188 +0,0 @@ -import json -from tqdm import tqdm -import os -import argparse - -label2desc={ - '银行': '银行', - '社区服务': '社区', - '电商': '电商', - '支付': '支付', - '经营养成': '养成', - '卡牌': '卡牌', - '借贷': '借贷', - '驾校': '驾校', - '理财': '理财', - '职考': '职考', - '新闻': '新闻', - '旅游资讯': '旅游', - '公共交通': '交通', - '魔幻': '魔幻', - '医疗服务': '医疗', - '影像剪辑': '影像', - '动作类': '动作', - '工具': '工具', - '体育竞技': '体育', - '小说': '小说', - '运动健身': '运动', - '相机': '相机', - '辅助工具': '辅助', - '快递物流': '快递', - '高等教育': '教育', - '股票': '股票', - '菜谱': '菜谱', - '行车辅助': '行车', - '仙侠': '仙侠', - '亲子儿童': '亲子', - '购物咨询': '购物', - '射击游戏': '射击', - '漫画': '漫画', - '中小学': '小学', - '同城服务': '同城', - '成人教育': '成人', - '求职': '求职', - '电子产品': '电子', - '艺术': '艺术', - '薅羊毛': '赚钱', - '约会社交': '约会', - '经营': '经营', - '兼职': '兼职', - '短视频': '短视', - '音乐': '音乐', - '英语': '英语', - '棋牌中心': '棋牌', - '摄影修图': '摄影', - '养生保健': '养生', - '办公': '办公', - '政务': '政务', - '视频': '视频', - '论坛圈子': '论坛', - '彩票': '彩票', - '直播': '直播', - '其他': '其他', - '休闲益智': '休闲', - '策略': '策略', - '即时通讯': '通讯', - '汽车交易': '买车', - '违章': '违章', - '地图导航': '地图', - '民航': '民航', - '电台': '电台', - '语言(非英语)': '语言', - '搞笑': '搞笑', - '婚恋社交': '婚恋', - '社区超市': '超市', - '日常养车': '养车', - '杂志': '杂志', - '视频教育': '在线', - '家政': '家政', - '影视娱乐': '影视', - '装修家居': '装修', - '体育咨讯': '资讯', - '社交工具': '社交', - '餐饮店': '餐饮', - '美颜': '美颜', - '问诊挂号': '挂号', - '飞行空战': '飞行', - '综合预定': '预定', - '电影票务': '票务', - '笔记': '笔记', - '买房': '买房', - '外卖': '外卖', - '母婴': '母婴', - '打车': '打车', - '情侣社交': '情侣', - '日程管理': '日程', - '租车': '租车', - '微博博客': '博客', - '百科': '百科', - '绘画': '绘画', - '铁路': '铁路', - '生活社交': '生活', - '租房': '租房', - '酒店': '酒店', - '保险': '保险', - '问答交流': '问答', - '收款': '收款', - 'MOBA': '竞技', - 'K歌': '唱歌', - '技术': '技术', - '减肥瘦身': '减肥', - '工作社交': '工作', - '团购': '团购', - '记账': '记账', - '女性': '女性', - '公务员': '公务', - '二手': '二手', - '美妆美业': '美妆', - '汽车咨询': '汽车', - '行程管理': '行程', - '免费WIFI': '免费', - '教辅': '教辅', - '成人': '两性', - '出国': '出国', - '婚庆': '婚庆', - '民宿短租': '民宿'} - -choice = [k for k,v in label2desc.items()] -print('1'.join(choice)) -print(len('1'.join(choice))) - - -def load_data(file_path,is_training=False): - with open(file_path, 'r', encoding='utf8') as f: - lines = f.readlines() - result=[] - for line in tqdm(lines): - data = json.loads(line) - texta = data['sentence'] - textb = '' - question = '请问app应用属于?' - - choice = [v for k,v in label2desc.items()] - answer = label2desc[data['label_des']] if 'label_des' in data.keys() else '' - - # choice = [k for k,v in label2desc.items()] - # answer = data['label_des'] if 'label_des' in data.keys() else '' - - label = choice.index(answer) if 'label_des' in data.keys() else 0 - text_id = data['id'] if 'id' in data.keys() else 0 - result.append({'texta':texta, - 'textb':textb, - 'question':question, - 'choice':choice, - 'answer':answer, - 'label':label, - 'id':text_id}) - # for i in range(5): - # print(result[i]) - return result - - -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') - - - -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() - - - data_path = args.data_path - save_path = args.save_path - - if not os.path.exists(save_path): - os.makedirs(save_path) - - file_list = ['train','dev','test'] - for file in file_list: - file_path = os.path.join(data_path,file+'.json') - output_path = os.path.join(save_path,file+'.json') - save_data(load_data(file_path),output_path) \ No newline at end of file diff --git a/spaces/skf15963/summary/fengshen/examples/clue1.1/predict2submit/ocnli_submit.py b/spaces/skf15963/summary/fengshen/examples/clue1.1/predict2submit/ocnli_submit.py deleted file mode 100644 index 89849f49476fdfd2fbde7ce3422ca25f203e5e8c..0000000000000000000000000000000000000000 --- a/spaces/skf15963/summary/fengshen/examples/clue1.1/predict2submit/ocnli_submit.py +++ /dev/null @@ -1,32 +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') - -def submit(file_path): - id2label={0:'contradiction',1:'neutral',2:'entailment'} - 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':id2label[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/skf15963/summary/fengshen/examples/pretrain_erlangshen_bert/pretrain_erlangshen.py b/spaces/skf15963/summary/fengshen/examples/pretrain_erlangshen_bert/pretrain_erlangshen.py deleted file mode 100644 index 1487abb15a7419b6c00056b6fcd78e96c8125d8b..0000000000000000000000000000000000000000 --- a/spaces/skf15963/summary/fengshen/examples/pretrain_erlangshen_bert/pretrain_erlangshen.py +++ /dev/null @@ -1,237 +0,0 @@ -from dataclasses import dataclass -from transformers import ( - MegatronBertConfig, - MegatronBertForPreTraining, - AutoTokenizer, -) -from pytorch_lightning import ( - LightningModule, - Trainer, -) -from pytorch_lightning.callbacks import ( - LearningRateMonitor, -) -import argparse -import torch -import os -import numpy as np -import time -from fengshen.data.universal_datamodule import UniversalDataModule -from fengshen.data.data_utils.sop_utils import get_a_and_b_segments -from fengshen.data.data_utils.truncate_utils import truncate_segments -from fengshen.data.data_utils.token_type_utils import create_tokens_and_tokentypes -from fengshen.data.data_utils.mask_utils import create_masked_lm_predictions -from fengshen.models.model_utils import ( - add_module_args, - configure_optimizers, - get_total_steps, -) -from fengshen.utils.universal_checkpoint import UniversalCheckpoint -from torch.utils.data._utils.collate import default_collate - -SHOW_DATA = False - - -@dataclass -class ErLangShenCollator: - ''' - 由input处理成samples,也就是最终模型的输入 - 其中主要处理逻辑在__call__里 - 包含Mask和Sop任务 - ''' - tokenizer: None # 分词 - max_seq_length: 512 - masked_lm_prob: 0.15 - content_key: str = 'text' - # 一些预处理操作 - - def setup(self): - from fengshen.data.data_utils.sentence_split import ChineseSentenceSplitter - self.sentence_split = ChineseSentenceSplitter() - self.np_rng = np.random.RandomState(seed=((int(time.time()) % 2**32))) - inv_vocab = {v: k for k, v in self.tokenizer.vocab.items()} - self.vocab_id_list = list(inv_vocab.keys()) - self.vocab_id_to_token_dict = inv_vocab - - def __call__(self, samples): - ''' - samples: 一个sample长这样{"text": "hello world"} - ''' - model_inputs = [] - for s in samples: - sentences = self.sentence_split.tokenize(s[self.content_key]) - # Divide sample into two segments (A and B). - tokenized_sentences = [self.tokenizer.convert_tokens_to_ids( - self.tokenizer.tokenize(sent)) for sent in sentences] - if len(tokenized_sentences) == 0: - print('find empty sentence') - continue - if len(tokenized_sentences) > 1: - tokens_a, tokens_b, is_next_random = get_a_and_b_segments(tokenized_sentences, - self.np_rng) - else: - tokens_a = tokenized_sentences[0] - tokens_b = [] - is_next_random = False - # max_seq_length - 3因为还需要拼上[CLS] [SEP] [SEP] - if len(tokens_a) == 0: - continue - _ = truncate_segments(tokens_a, tokens_b, len(tokens_a), - len(tokens_b), self.max_seq_length-3, self.np_rng) - # Build tokens and toketypes. - tokens, tokentypes = create_tokens_and_tokentypes(tokens_a, tokens_b, - self.tokenizer.cls_token_id, self.tokenizer.sep_token_id) - # Masking. - max_predictions_per_seq = self.masked_lm_prob * len(tokens) - (tokens, masked_positions, masked_labels, _, _) = create_masked_lm_predictions( - tokens, self.vocab_id_list, self.vocab_id_to_token_dict, self.masked_lm_prob, - self.tokenizer.cls_token_id, self.tokenizer.sep_token_id, self.tokenizer.mask_token_id, - max_predictions_per_seq, self.np_rng, - masking_style='bert') - - # Some checks. - num_tokens = len(tokens) - padding_length = self.max_seq_length - num_tokens - assert padding_length >= 0 - assert len(tokentypes) == num_tokens - assert len(masked_positions) == len(masked_labels) - - # Tokens and token types. - filler = [self.tokenizer.pad_token_id] * padding_length - tokens_np = np.array(tokens + filler, dtype=np.int64) - tokentypes_np = np.array(tokentypes + filler, dtype=np.int64) - - # Padding mask. - padding_mask_np = np.array([1] * num_tokens + [0] * padding_length, - dtype=np.int64) - - # Lables and loss mask. - labels = [-100] * self.max_seq_length - for i in range(len(masked_positions)): - assert masked_positions[i] < num_tokens - labels[masked_positions[i]] = masked_labels[i] - labels_np = np.array(labels, dtype=np.int64) - model_inputs.append( - { - 'input_ids': tokens_np, - 'attention_mask': padding_mask_np, - 'token_type_ids': tokentypes_np, - 'labels': labels_np, - 'next_sentence_label': int(is_next_random) - } - ) - return default_collate(model_inputs) - - -class ErLangShenBert(LightningModule): - @staticmethod - def add_module_specific_args(parent_parser): - parser = parent_parser.add_argument_group('Erlangshen Bert') - parser.add_argument('--masked_lm_prob', type=float, default=0.15) - parser.add_argument('--max_seq_length', type=int, default=512) - parser.add_argument('--sample_content_key', type=str, default='text') - return parent_parser - - def __init__(self, args, tokenizer, **kwargs) -> None: - super().__init__() - self.save_hyperparameters(args) - config = MegatronBertConfig.from_pretrained(args.model_path) - self.config = config - self.tokenizer = tokenizer - self.model = MegatronBertForPreTraining(config) - - def setup(self, stage) -> None: - if stage == 'fit': - self.total_steps = get_total_steps(self.trainer, self.hparams) - print('Total steps: {}' .format(self.total_steps)) - - def configure_optimizers(self): - return configure_optimizers(self) - - def forward(self, **batch): - return self.model(**batch) - - def detokenize(self, token_ids): - toks = self.tokenizer.convert_ids_to_tokens(token_ids) - return self.tokenizer.convert_tokens_to_string(toks) - - def comput_metrix(self, logits, labels): - y_pred = torch.argmax(logits, dim=-1) - y_pred = y_pred.view(size=(-1,)) - y_true = labels.view(size=(-1,)).float() - corr = torch.eq(y_pred, y_true) - acc = torch.sum(corr.float())/labels.shape[0] - return acc - - def training_step(self, batch, batch_idx): - if self.trainer.global_rank == 0: - global SHOW_DATA - if not SHOW_DATA: - print(self.config) - print(self.model) - SHOW_DATA = True - print('source: {}'.format(batch['input_ids'][0])) - print('target: {}'.format(batch['labels'][0])) - print('source: {}'.format(self.detokenize(batch['input_ids'][0]))) - label_idx = batch['labels'][0] != -100 - print('target: {}'.format(self.detokenize( - batch['labels'][0][label_idx]))) - output = self(**batch) - self.log('train_loss', output.loss, sync_dist=True) - label_idx = batch['labels'] != -100 - acc = self.comput_metrix( - output.prediction_logits[label_idx].view(-1, output.prediction_logits.size(-1)), batch['labels'][label_idx]) - self.log('train_acc', acc, sync_dist=True) - return output.loss - - def validation_step(self, batch, batch_idx): - output = self(**batch) - self.log('val_loss', output.loss, sync_dist=True) - return output.loss - - def on_load_checkpoint(self, checkpoint) -> None: - # 兼容低版本lightning,低版本lightning从ckpt起来时steps数会被重置为0 - global_step_offset = checkpoint["global_step"] - if 'global_samples' in checkpoint: - self.consumed_samples = checkpoint['global_samples'] - self.trainer.fit_loop.epoch_loop._batches_that_stepped = global_step_offset - - -if __name__ == '__main__': - args_parser = argparse.ArgumentParser() - args_parser = add_module_args(args_parser) - args_parser = UniversalDataModule.add_data_specific_args(args_parser) - args_parser = Trainer.add_argparse_args(args_parser) - args_parser = ErLangShenBert.add_module_specific_args(args_parser) - args_parser = UniversalCheckpoint.add_argparse_args(args_parser) - args = args_parser.parse_args() - - tokenizer = AutoTokenizer.from_pretrained(args.model_path) - collate_fn = ErLangShenCollator( - tokenizer=tokenizer, - max_seq_length=args.max_seq_length, - masked_lm_prob=args.masked_lm_prob, - content_key=args.sample_content_key, - ) - collate_fn.setup() - data_module = UniversalDataModule(tokenizer=tokenizer, args=args, collate_fn=collate_fn) - print('data load complete') - - model = ErLangShenBert(args, tokenizer=tokenizer) - print('model load complete') - - lr_monitor = LearningRateMonitor(logging_interval='step') - checkpoint_callback = UniversalCheckpoint(args) - - # 做兼容,如果目录不存在的话把这个参数去掉,不然会报错 - if args.load_ckpt_path is not None and \ - not os.path.exists(args.load_ckpt_path): - print('--------warning no checkpoint found--------, remove args') - args.load_ckpt_path = None - - trainer = Trainer.from_argparse_args(args, - callbacks=[ - lr_monitor, - checkpoint_callback]) - - trainer.fit(model, data_module, ckpt_path=args.load_ckpt_path) diff --git a/spaces/skf15963/summary/fengshen/examples/wenzhong_qa/finetune_wenzhong.sh b/spaces/skf15963/summary/fengshen/examples/wenzhong_qa/finetune_wenzhong.sh deleted file mode 100644 index 0100377bf5c54c0eba3088e3b09368a5b31f9c06..0000000000000000000000000000000000000000 --- a/spaces/skf15963/summary/fengshen/examples/wenzhong_qa/finetune_wenzhong.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=finetune_wenzhong -#SBATCH --cpus-per-task=50 -#SBATCH --nodes=1 -#SBATCH --ntasks-per-node=1 -#SBATCH --gres=gpu:1 # number of gpus -#SBATCH -o %x-%j.log -#SBATCH -e %x-%j.err - -set -x -e - -export MASTER_PORT=$[RANDOM%10000+50000] -export TORCH_EXTENSIONS_DIR=/cognitive_comp/gaoxinyu/torch_extendsions - -echo "START TIME: $(date)" -MICRO_BATCH_SIZE=1 -ROOT_DIR=/cognitive_comp/gaoxinyu/FS/fengshen/fengshen - -ZERO_STAGE=3 - -config_json="$ROOT_DIR/ds_config.$SLURM_JOBID.json" -#config_json="$ROOT_DIR/ds_config.wzw.json" -# Deepspeed figures out GAS dynamically from dynamic GBS via set_train_batch_size() -cat < $config_json -{ - "train_micro_batch_size_per_gpu":1, - "steps_per_print":100, - "gradient_clipping":1, - "zero_optimization":{ - "stage": $ZERO_STAGE, - "offload_optimizer":{ - "device":"cpu", - "pin_memory":true - }, - "offload_param":{ - "device":"cpu", - "pin_memory":true - }, - "overlap_comm":true, - "contiguous_gradients":true, - "sub_group_size":1000000000, - "stage3_max_live_parameters":1000000000, - "stage3_max_reuse_distance":1000000000, - "stage3_gather_fp16_weights_on_model_save":true - }, - "optimizer":{ - "type":"Adam", - "params":{ - "lr": 1e-5, - "weight_decay":0.01 - } - }, - "scheduler":{ - "type":"WarmupLR", - "params":{ - "warmup_min_lr":5e-6, - "warmup_max_lr":1e-5 - } - }, - "zero_allow_untested_optimizer":false, - "fp16":{ - "enabled":true, - "loss_scale":0, - "loss_scale_window":1000, - "hysteresis":2, - "min_loss_scale":1 - }, - "activation_checkpointing":{ - "partition_activations":false, - "contiguous_memory_optimization":false - }, - "wall_clock_breakdown":false -} -EOT - -export PL_DEEPSPEED_CONFIG_PATH=$config_json - -TRAINER_ARGS=" - --max_epochs 2 \ - --gpus 1 \ - --num_nodes 1 \ - --strategy deepspeed_stage_3 \ - --precision 16 \ - --default_root_dir $ROOT_DIR \ - --dirpath $ROOT_DIR/ckpt \ - --save_top_k 3 \ - --monitor train_loss \ - --mode min \ - --save_last \ -" -DATA_DIR=/cognitive_comp/gaoxinyu/data/yuyuan -DATA_ARGS=" - --data_dir $DATA_DIR \ - --train_batchsize $MICRO_BATCH_SIZE \ - --valid_batchsize $MICRO_BATCH_SIZE \ - --train_data train.txt \ - --valid_data valid.txt \ - --test_data test.txt -" - -MODEL_ARGS=" - --pretrained_model_path /cognitive_comp/gaoxinyu/hf_model/wenzhong \ - --output_save_path $ROOT_DIR/predict.json \ - --learning_rate 1e-4 \ - --weight_decay 0.1 \ - --warmup 0.01 \ -" - -SCRIPTS_PATH=/cognitive_comp/gaoxinyu/FS/fengshen/finetune_wenzhong.py - -export CMD=" \ - $SCRIPTS_PATH \ - $TRAINER_ARGS \ - $MODEL_ARGS \ - $DATA_ARGS \ - " - -echo $CMD - -SINGULARITY_PATH=/cognitive_comp/gaoxinyu/docker/pytorch21_06_py3_docker_image_v2.sif - -# to debug - add echo (it exits and prints what it would have launched) -#run_cmd="$PY_LAUNCHER $CMD" - -clear; srun --jobid $SLURM_JOBID singularity exec --nv -B /cognitive_comp/:/cognitive_comp/ $SINGULARITY_PATH bash -c 'python $CMD' -# bash -c 'python $CMD' \ No newline at end of file diff --git a/spaces/sklearn-docs/Caching-Nearest-Neighbors/app.py b/spaces/sklearn-docs/Caching-Nearest-Neighbors/app.py deleted file mode 100644 index 0076b96ef0e2a430141fd2d9dc3e02d579f1d045..0000000000000000000000000000000000000000 --- a/spaces/sklearn-docs/Caching-Nearest-Neighbors/app.py +++ /dev/null @@ -1,67 +0,0 @@ -import gradio as gr -import matplotlib.pyplot as plt -from tempfile import NamedTemporaryFile - -from sklearn.neighbors import KNeighborsTransformer, KNeighborsClassifier -from sklearn.model_selection import GridSearchCV -from sklearn.datasets import load_digits -from sklearn.pipeline import Pipeline - -def classify_digits(n_neighbors): - X, y = load_digits(return_X_y=True) - n_neighbors_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] - - graph_model = KNeighborsTransformer(n_neighbors=max(n_neighbors_list), mode="distance") - classifier_model = KNeighborsClassifier(metric="precomputed") - - full_model = Pipeline( - steps=[("graph", graph_model), ("classifier", classifier_model)] - ) - - param_grid = {"classifier__n_neighbors": n_neighbors_list} - grid_model = GridSearchCV(full_model, param_grid) - grid_model.fit(X, y) - - # Plot the results of the grid search. - fig, axes = plt.subplots(1, 2, figsize=(8, 4)) - axes[0].errorbar( - x=n_neighbors_list, - y=grid_model.cv_results_["mean_test_score"], - yerr=grid_model.cv_results_["std_test_score"], - ) - axes[0].set(xlabel="n_neighbors", title="Classification accuracy") - axes[1].errorbar( - x=n_neighbors_list, - y=grid_model.cv_results_["mean_fit_time"], - yerr=grid_model.cv_results_["std_fit_time"], - color="r", - ) - axes[1].set(xlabel="n_neighbors", title="Fit time (with caching)") - fig.tight_layout() - - # Save the plot to a temporary file - with NamedTemporaryFile(suffix=".png", delete=False) as temp_file: - plot_path = temp_file.name - plt.savefig(plot_path) - - plt.close() - - return plot_path - -# Create a Gradio interface with adjustable parameters -n_neighbors_input = gr.inputs.Slider(minimum=1, maximum=10, default=5, step=1, label="Number of Neighbors") -plot_output = gr.outputs.Image(type="pil") - -iface = gr.Interface( - fn=classify_digits, - inputs=n_neighbors_input, - outputs=plot_output, - title="Digits Classifier", - description="This example demonstrates how to precompute the k nearest neighbors before using them in KNeighborsClassifier. KNeighborsClassifier can compute the nearest neighbors internally, but precomputing them can have several benefits, such as finer parameter control, caching for multiple use, or custom implementations. See the original scikit-learn example [here](https://scikit-learn.org/stable/auto_examples/neighbors/plot_caching_nearest_neighbors.html).", - examples=[ - ["2"], # Example 1 - ["7"], # Example 2 - ["4"], # Example 3 - ] -) -iface.launch() \ No newline at end of file diff --git a/spaces/society-ethics/model-card-regulatory-check/tests/cards/xlm-roberta-large.md b/spaces/society-ethics/model-card-regulatory-check/tests/cards/xlm-roberta-large.md deleted file mode 100644 index a749564881a1c85d29145d1656def13ee913d8e7..0000000000000000000000000000000000000000 --- a/spaces/society-ethics/model-card-regulatory-check/tests/cards/xlm-roberta-large.md +++ /dev/null @@ -1,99 +0,0 @@ -# XLM-RoBERTa (large-sized model) - -XLM-RoBERTa model pre-trained on 2.5TB of filtered CommonCrawl data containing 100 languages. It was introduced in the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Conneau et al. and first released in [this repository](https://github.com/pytorch/fairseq/tree/master/examples/xlmr). - -Disclaimer: The team releasing XLM-RoBERTa did not write a model card for this model so this model card has been written by the Hugging Face team. - -## Model description - -XLM-RoBERTa is a multilingual version of RoBERTa. It is pre-trained on 2.5TB of filtered CommonCrawl data containing 100 languages. - -RoBERTa is a transformers model pretrained on a large corpus in a self-supervised fashion. This means it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts. - -More precisely, it was pretrained with the Masked language modeling (MLM) objective. Taking a sentence, the model randomly masks 15% of the words in the input then run the entire masked sentence through the model and has to predict the masked words. This is different from traditional recurrent neural networks (RNNs) that usually see the words one after the other, or from autoregressive models like GPT which internally mask the future tokens. It allows the model to learn a bidirectional representation of the sentence. - -This way, the model learns an inner representation of 100 languages that can then be used to extract features useful for downstream tasks: if you have a dataset of labeled sentences for instance, you can train a standard classifier using the features produced by the XLM-RoBERTa model as inputs. - -## Intended uses & limitations - -You can use the raw model for masked language modeling, but it's mostly intended to be fine-tuned on a downstream task. See the [model hub](https://huggingface.co/models?search=xlm-roberta) to look for fine-tuned versions on a task that interests you. - -Note that this model is primarily aimed at being fine-tuned on tasks that use the whole sentence (potentially masked) to make decisions, such as sequence classification, token classification or question answering. For tasks such as text generation, you should look at models like GPT2. - -## Usage - -You can use this model directly with a pipeline for masked language modeling: - -```python ->>> from transformers import pipeline ->>> unmasker = pipeline('fill-mask', model='xlm-roberta-large') ->>> unmasker("Hello I'm a model.") - -[{'score': 0.10563907772302628, - 'sequence': "Hello I'm a fashion model.", - 'token': 54543, - 'token_str': 'fashion'}, - {'score': 0.08015287667512894, - 'sequence': "Hello I'm a new model.", - 'token': 3525, - 'token_str': 'new'}, - {'score': 0.033413201570510864, - 'sequence': "Hello I'm a model model.", - 'token': 3299, - 'token_str': 'model'}, - {'score': 0.030217764899134636, - 'sequence': "Hello I'm a French model.", - 'token': 92265, - 'token_str': 'French'}, - {'score': 0.026436051353812218, - 'sequence': "Hello I'm a sexy model.", - 'token': 17473, - 'token_str': 'sexy'}] -``` - -Here is how to use this model to get the features of a given text in PyTorch: - -```python -from transformers import AutoTokenizer, AutoModelForMaskedLM - -tokenizer = AutoTokenizer.from_pretrained('xlm-roberta-large') -model = AutoModelForMaskedLM.from_pretrained("xlm-roberta-large") - -# prepare input -text = "Replace me by any text you'd like." -encoded_input = tokenizer(text, return_tensors='pt') - -# forward pass -output = model(**encoded_input) -``` - -### BibTeX entry and citation info - -```bibtex -@article{DBLP:journals/corr/abs-1911-02116, - author = {Alexis Conneau and - Kartikay Khandelwal and - Naman Goyal and - Vishrav Chaudhary and - Guillaume Wenzek and - Francisco Guzm{\'{a}}n and - Edouard Grave and - Myle Ott and - Luke Zettlemoyer and - Veselin Stoyanov}, - title = {Unsupervised Cross-lingual Representation Learning at Scale}, - journal = {CoRR}, - volume = {abs/1911.02116}, - year = {2019}, - url = {http://arxiv.org/abs/1911.02116}, - eprinttype = {arXiv}, - eprint = {1911.02116}, - timestamp = {Mon, 11 Nov 2019 18:38:09 +0100}, - biburl = {https://dblp.org/rec/journals/corr/abs-1911-02116.bib}, - bibsource = {dblp computer science bibliography, https://dblp.org} -} -``` - - - - \ No newline at end of file diff --git a/spaces/songwy/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c b/spaces/songwy/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c deleted file mode 100644 index 5631d20a9a00db29e143a6e8e4e5c378d6bb850a..0000000000000000000000000000000000000000 --- a/spaces/songwy/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/songwy/VITS-Umamusume-voice-synthesizer/text/english.py b/spaces/songwy/VITS-Umamusume-voice-synthesizer/text/english.py deleted file mode 100644 index 6817392ba8a9eb830351de89fb7afc5ad72f5e42..0000000000000000000000000000000000000000 --- a/spaces/songwy/VITS-Umamusume-voice-synthesizer/text/english.py +++ /dev/null @@ -1,188 +0,0 @@ -""" from https://github.com/keithito/tacotron """ - -''' -Cleaners are transformations that run over the input text at both training and eval time. - -Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" -hyperparameter. Some cleaners are English-specific. You'll typically want to use: - 1. "english_cleaners" for English text - 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using - the Unidecode library (https://pypi.python.org/pypi/Unidecode) - 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update - the symbols in symbols.py to match your data). -''' - - -# Regular expression matching whitespace: - - -import re -import inflect -from unidecode import unidecode -import eng_to_ipa as ipa -_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]+') - -# 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'), -]] - - -# List of (ipa, lazy ipa) pairs: -_lazy_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('r', 'ɹ'), - ('æ', 'e'), - ('ɑ', 'a'), - ('ɔ', 'o'), - ('ð', 'z'), - ('θ', 's'), - ('ɛ', 'e'), - ('ɪ', 'i'), - ('ʊ', 'u'), - ('ʒ', 'ʥ'), - ('ʤ', 'ʥ'), - ('ˈ', '↓'), -]] - -# List of (ipa, lazy ipa2) pairs: -_lazy_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('r', 'ɹ'), - ('ð', 'z'), - ('θ', 's'), - ('ʒ', 'ʑ'), - ('ʤ', 'dʑ'), - ('ˈ', '↓'), -]] - -# List of (ipa, ipa2) pairs -_ipa_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('r', 'ɹ'), - ('ʤ', 'dʒ'), - ('ʧ', 'tʃ') -]] - - -def expand_abbreviations(text): - for regex, replacement in _abbreviations: - text = re.sub(regex, replacement, text) - return text - - -def collapse_whitespace(text): - return re.sub(r'\s+', ' ', text) - - -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 mark_dark_l(text): - return re.sub(r'l([^aeiouæɑɔəɛɪʊ ]*(?: |$))', lambda x: 'ɫ'+x.group(1), text) - - -def english_to_ipa(text): - text = unidecode(text).lower() - text = expand_abbreviations(text) - text = normalize_numbers(text) - phonemes = ipa.convert(text) - phonemes = collapse_whitespace(phonemes) - return phonemes - - -def english_to_lazy_ipa(text): - text = english_to_ipa(text) - for regex, replacement in _lazy_ipa: - text = re.sub(regex, replacement, text) - return text - - -def english_to_ipa2(text): - text = english_to_ipa(text) - text = mark_dark_l(text) - for regex, replacement in _ipa_to_ipa2: - text = re.sub(regex, replacement, text) - return text.replace('...', '…') - - -def english_to_lazy_ipa2(text): - text = english_to_ipa(text) - for regex, replacement in _lazy_ipa2: - text = re.sub(regex, replacement, text) - return text diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/rxf/rxf_src/label_smoothed_cross_entropy_r3f.py b/spaces/sriramelango/Social_Classification_Public/fairseq/examples/rxf/rxf_src/label_smoothed_cross_entropy_r3f.py deleted file mode 100644 index 079db13e61c5ef46d1b1d288012145148eb0be04..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/rxf/rxf_src/label_smoothed_cross_entropy_r3f.py +++ /dev/null @@ -1,157 +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 -from fairseq.criterions.label_smoothed_cross_entropy import label_smoothed_nll_loss - - -@register_criterion("label_smoothed_cross_entropy_r3f") -class LabelSmoothedCrossEntropyR3FCriterion(FairseqCriterion): - def __init__( - self, task, sentence_avg, label_smoothing, eps, r3f_lambda, noise_type - ): - super().__init__(task) - self.sentence_avg = sentence_avg - self.label_smoothing = label_smoothing - self.eps = eps - self.r3f_lambda = r3f_lambda - self.noise_type = noise_type - if self.noise_type in {"normal"}: - self.noise_sampler = torch.distributions.normal.Normal( - loc=0.0, scale=self.eps - ) - elif self.noise_type == "uniform": - self.noise_sampler = torch.distributions.uniform.Uniform( - low=-self.eps, high=self.eps - ) - else: - raise Exception(f"unrecognized noise type {self.noise_type}") - - @staticmethod - def add_args(parser): - """Add criterion-specific arguments to the parser.""" - # fmt: off - parser.add_argument('--label-smoothing', default=0., type=float, metavar='D', - help='epsilon for label smoothing, 0 means no label smoothing') - parser.add_argument('--eps', type=float, default=1e-5, - help='noise eps') - parser.add_argument('--r3f-lambda', type=float, default=1.0, - help='lambda for combining logistic loss and noisy KL loss') - parser.add_argument('--noise-type', type=str, default='normal', - choices=['normal', 'uniform'], - help='type of noises') - # fmt: on - - def _get_symm_kl(self, noised_logits, input_logits): - return ( - F.kl_div( - F.log_softmax(noised_logits, dim=-1, dtype=torch.float32), - F.softmax(input_logits, dim=-1, dtype=torch.float32), - None, - None, - "sum", - ) - + F.kl_div( - F.log_softmax(input_logits, dim=-1, dtype=torch.float32), - F.softmax(noised_logits, dim=-1, dtype=torch.float32), - None, - None, - "sum", - ) - ) / noised_logits.size(0) - - 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 - """ - token_embeddings = model.encoder.embed_tokens(sample["net_input"]["src_tokens"]) - input_logits, extra = model(**sample["net_input"]) - loss, nll_loss = self.compute_loss( - model, (input_logits, extra), sample, reduce=reduce - ) - sample_size = ( - sample["target"].size(0) if self.sentence_avg else sample["ntokens"] - ) - - if model.training: - noise = self.noise_sampler.sample(sample_shape=token_embeddings.shape).to( - token_embeddings - ) - noised_embeddings = token_embeddings.clone() + noise - - noised_logits, _ = model( - **sample["net_input"], token_embeddings=noised_embeddings - ) - symm_kl = self._get_symm_kl(noised_logits, input_logits) - - if model.training: - symm_kl = symm_kl * sample_size - loss = loss + self.r3f_lambda * symm_kl - - logging_output = { - "loss": loss.data, - "nll_loss": nll_loss.data, - "ntokens": sample["ntokens"], - "nsentences": sample["target"].size(0), - "sample_size": sample_size, - } - - if model.training: - logging_output.update( - symm_kl=utils.item(symm_kl.data) if reduce else symm_kl.data - ) - - return loss, sample_size, logging_output - - def compute_loss(self, model, net_output, sample, reduce=True): - lprobs = model.get_normalized_probs(net_output, log_probs=True) - lprobs = lprobs.view(-1, lprobs.size(-1)) - target = model.get_targets(sample, net_output).view(-1, 1) - loss, nll_loss = label_smoothed_nll_loss( - lprobs, - target, - self.label_smoothing, - ignore_index=self.padding_idx, - reduce=reduce, - ) - return loss, nll_loss - - @staticmethod - def reduce_metrics(logging_outputs) -> None: - """Aggregate logging outputs from data parallel training.""" - loss_sum = sum(log.get("loss", 0) for log in logging_outputs) - nll_loss_sum = sum(log.get("nll_loss", 0) for log in logging_outputs) - ntokens = sum(log.get("ntokens", 0) for log in logging_outputs) - sample_size = sum(log.get("sample_size", 0) for log in logging_outputs) - symm_kl_sum = sum(log.get("symm_kl", 0) for log in logging_outputs) - - metrics.log_scalar("symm_kl", symm_kl_sum / sample_size, sample_size, round=3) - metrics.log_scalar( - "loss", loss_sum / sample_size / math.log(2), sample_size, round=3 - ) - metrics.log_scalar( - "nll_loss", nll_loss_sum / ntokens / math.log(2), ntokens, round=3 - ) - metrics.log_derived( - "ppl", lambda meters: utils.get_perplexity(meters["nll_loss"].avg) - ) - - @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/sriramelango/Social_Classification_Public/fairseq/fairseq/binarizer.py b/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/binarizer.py deleted file mode 100644 index ae4d02a6dbbb523b76eb8684e87e38c74fe7c4a1..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/binarizer.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from collections import Counter -from typing import Dict - -import torch - -from fairseq.file_chunker_utils import Chunker -from fairseq.file_io import PathManager -from fairseq.tokenizer import tokenize_line - - -class Binarizer: - @staticmethod - def binarize( - filename, - dict, - consumer, - tokenize=tokenize_line, - append_eos=True, - reverse_order=False, - offset=0, - end=-1, - already_numberized=False, - ) -> Dict[str, int]: - nseq, ntok = 0, 0 - replaced = Counter() - - def replaced_consumer(word, idx): - if idx == dict.unk_index and word != dict.unk_word: - replaced.update([word]) - - with Chunker( - PathManager.get_local_path(filename), offset, end - ) as line_iterator: - for line in line_iterator: - if already_numberized: - id_strings = line.strip().split() - id_list = [int(id_string) for id_string in id_strings] - if reverse_order: - id_list.reverse() - if append_eos: - id_list.append(dict.eos()) - ids = torch.IntTensor(id_list) - else: - ids = dict.encode_line( - line=line, - line_tokenizer=tokenize, - add_if_not_exist=False, - consumer=replaced_consumer, - append_eos=append_eos, - reverse_order=reverse_order, - ) - nseq += 1 - ntok += len(ids) - consumer(ids) - return { - "nseq": nseq, - "nunk": sum(replaced.values()), - "ntok": ntok, - "replaced": replaced, - } - - @staticmethod - def binarize_alignments( - filename, alignment_parser, consumer, offset=0, end=-1 - ) -> Dict[str, int]: - nseq = 0 - - with Chunker( - PathManager.get_local_path(filename), offset, end - ) as line_iterator: - for line in line_iterator: - ids = alignment_parser(line) - nseq += 1 - consumer(ids) - return {"nseq": nseq} diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/modules/conv_tbc.py b/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/modules/conv_tbc.py deleted file mode 100644 index 65e17ec94f7e595cb657b3d2daaa1052a95d0677..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/modules/conv_tbc.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch -from torch import nn -from torch.nn.modules.utils import _single -from torch import Tensor - - -class ConvTBC(torch.nn.Module): - """1D convolution over an input of shape (time x batch x channel) - - The implementation uses gemm to perform the convolution. This implementation - is faster than cuDNN for small kernel sizes. - """ - - def __init__(self, in_channels, out_channels, kernel_size, padding=0): - super(ConvTBC, self).__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.kernel_size = _single(kernel_size) - self.padding = _single(padding) - - self.weight = torch.nn.Parameter( - torch.Tensor(self.kernel_size[0], in_channels, out_channels) - ) - self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) - - self.reset_parameters() - - def reset_parameters(self): - nn.init.xavier_normal_(self.weight) - nn.init.zeros_(self.bias) - - def conv_tbc(self, input: Tensor): - return torch.conv_tbc( - input.contiguous(), self.weight, self.bias, self.padding[0] - ) - - def forward(self, input: Tensor): - return self.conv_tbc(input) - - def __repr__(self): - s = ( - "{name}({in_channels}, {out_channels}, kernel_size={kernel_size}" - ", padding={padding}" - ) - if self.bias is None: - s += ", bias=False" - s += ")" - return s.format(name=self.__class__.__name__, **self.__dict__) diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/scripts/split_train_valid_docs.py b/spaces/sriramelango/Social_Classification_Public/fairseq/scripts/split_train_valid_docs.py deleted file mode 100644 index ff159785284a13b44626b207d84430c592acaf8f..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/scripts/split_train_valid_docs.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. -""" -Split a large file into a train and valid set while respecting document -boundaries. Documents should be separated by a single empty line. -""" - -import argparse -import random -import sys - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("input") - parser.add_argument("sample_output", help="train output file") - parser.add_argument("remainder_output", help="valid output file") - parser.add_argument("-k", type=int, help="remainder size") - parser.add_argument( - "--lines", action="store_true", help="split lines instead of docs" - ) - args = parser.parse_args() - - assert args.k is not None - - sample = [] - remainder = [] - num_docs = [0] - - def update_sample(doc): - if len(sample) < args.k: - sample.append(doc.copy()) - else: - i = num_docs[0] - j = random.randrange(i + 1) - if j < args.k: - remainder.append(sample[j]) - sample[j] = doc.copy() - else: - remainder.append(doc.copy()) - num_docs[0] += 1 - doc.clear() - - with open(args.input, "r", encoding="utf-8") as h: - doc = [] - for i, line in enumerate(h): - if line.strip() == "": # empty line indicates new document - update_sample(doc) - else: - doc.append(line) - if args.lines: - update_sample(doc) - if i % 1000000 == 0: - print(i, file=sys.stderr, end="", flush=True) - elif i % 100000 == 0: - print(".", file=sys.stderr, end="", flush=True) - if len(doc) > 0: - update_sample(doc) - print(file=sys.stderr, flush=True) - - assert len(sample) == args.k - - with open(args.sample_output, "w", encoding="utf-8") as out: - first = True - for doc in sample: - if not first and not args.lines: - out.write("\n") - first = False - for line in doc: - out.write(line) - - with open(args.remainder_output, "w", encoding="utf-8") as out: - first = True - for doc in remainder: - if not first and not args.lines: - out.write("\n") - first = False - for line in doc: - out.write(line) - - -if __name__ == "__main__": - main() diff --git a/spaces/sub314xxl/MetaGPT/metagpt/document_store/chromadb_store.py b/spaces/sub314xxl/MetaGPT/metagpt/document_store/chromadb_store.py deleted file mode 100644 index ee14fb2f0573bda824165f8aeeb8dd590abaa172..0000000000000000000000000000000000000000 --- a/spaces/sub314xxl/MetaGPT/metagpt/document_store/chromadb_store.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -@Time : 2023/5/29 14:46 -@Author : alexanderwu -@File : chromadb_store.py -""" -import chromadb - - -class ChromaStore: - """如果从BaseStore继承,或者引入metagpt的其他模块,就会Python异常,很奇怪""" - def __init__(self, name): - client = chromadb.Client() - collection = client.create_collection(name) - self.client = client - self.collection = collection - - def search(self, query, n_results=2, metadata_filter=None, document_filter=None): - # kwargs can be used for optional filtering - results = self.collection.query( - query_texts=[query], - n_results=n_results, - where=metadata_filter, # optional filter - where_document=document_filter # optional filter - ) - return results - - def persist(self): - """chroma建议使用server模式,不本地persist""" - raise NotImplementedError - - def write(self, documents, metadatas, ids): - # This function is similar to add(), but it's for more generalized updates - # It assumes you're passing in lists of docs, metadatas, and ids - return self.collection.add( - documents=documents, - metadatas=metadatas, - ids=ids, - ) - - def add(self, document, metadata, _id): - # This function is for adding individual documents - # It assumes you're passing in a single doc, metadata, and id - return self.collection.add( - documents=[document], - metadatas=[metadata], - ids=[_id], - ) - - def delete(self, _id): - return self.collection.delete([_id]) diff --git a/spaces/sub314xxl/MusicGen-Continuation/tests/data/test_audio_dataset.py b/spaces/sub314xxl/MusicGen-Continuation/tests/data/test_audio_dataset.py deleted file mode 100644 index b69c9c397830738b73d6c229009f84b867cda801..0000000000000000000000000000000000000000 --- a/spaces/sub314xxl/MusicGen-Continuation/tests/data/test_audio_dataset.py +++ /dev/null @@ -1,352 +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 functools import partial -from itertools import product -import json -import math -import os -import random -import typing as tp - -import pytest -import torch -from torch.utils.data import DataLoader - -from audiocraft.data.audio_dataset import ( - AudioDataset, - AudioMeta, - _get_audio_meta, - load_audio_meta, - save_audio_meta -) -from audiocraft.data.zip import PathInZip - -from ..common_utils import TempDirMixin, get_white_noise, save_wav - - -class TestAudioMeta(TempDirMixin): - - def test_get_audio_meta(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(duration * sample_rate) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path('sample.wav') - save_wav(path, wav, sample_rate) - m = _get_audio_meta(path, minimal=True) - assert m.path == path, 'path does not match' - assert m.sample_rate == sample_rate, 'sample rate does not match' - assert m.duration == duration, 'duration does not match' - assert m.amplitude is None - assert m.info_path is None - - def test_save_audio_meta(self): - audio_meta = [ - AudioMeta("mypath1", 1., 16_000, None, None, PathInZip('/foo/bar.zip:/relative/file1.json')), - AudioMeta("mypath2", 2., 16_000, None, None, PathInZip('/foo/bar.zip:/relative/file2.json')) - ] - empty_audio_meta = [] - for idx, meta in enumerate([audio_meta, empty_audio_meta]): - path = self.get_temp_path(f'data_{idx}_save.jsonl') - save_audio_meta(path, meta) - with open(path, 'r') as f: - lines = f.readlines() - read_meta = [AudioMeta.from_dict(json.loads(line)) for line in lines] - assert len(read_meta) == len(meta) - for m, read_m in zip(meta, read_meta): - assert m == read_m - - def test_load_audio_meta(self): - try: - import dora - except ImportError: - dora = None # type: ignore - - audio_meta = [ - AudioMeta("mypath1", 1., 16_000, None, None, PathInZip('/foo/bar.zip:/relative/file1.json')), - AudioMeta("mypath2", 2., 16_000, None, None, PathInZip('/foo/bar.zip:/relative/file2.json')) - ] - empty_meta = [] - for idx, meta in enumerate([audio_meta, empty_meta]): - path = self.get_temp_path(f'data_{idx}_load.jsonl') - with open(path, 'w') as f: - for m in meta: - json_str = json.dumps(m.to_dict()) + '\n' - f.write(json_str) - read_meta = load_audio_meta(path) - assert len(read_meta) == len(meta) - for m, read_m in zip(meta, read_meta): - if dora: - m.path = dora.git_save.to_absolute_path(m.path) - assert m == read_m, f'original={m}, read={read_m}' - - -class TestAudioDataset(TempDirMixin): - - def _create_audio_files(self, - root_name: str, - num_examples: int, - durations: tp.Union[float, tp.Tuple[float, float]] = (0.1, 1.), - sample_rate: int = 16_000, - channels: int = 1): - root_dir = self.get_temp_dir(root_name) - for i in range(num_examples): - if isinstance(durations, float): - duration = durations - elif isinstance(durations, tuple) and len(durations) == 1: - duration = durations[0] - elif isinstance(durations, tuple) and len(durations) == 2: - duration = random.uniform(durations[0], durations[1]) - else: - assert False - n_frames = int(duration * sample_rate) - wav = get_white_noise(channels, n_frames) - path = os.path.join(root_dir, f'example_{i}.wav') - save_wav(path, wav, sample_rate) - return root_dir - - def _create_audio_dataset(self, - root_name: str, - total_num_examples: int, - durations: tp.Union[float, tp.Tuple[float, float]] = (0.1, 1.), - sample_rate: int = 16_000, - channels: int = 1, - segment_duration: tp.Optional[float] = None, - num_examples: int = 10, - shuffle: bool = True, - return_info: bool = False): - root_dir = self._create_audio_files(root_name, total_num_examples, durations, sample_rate, channels) - dataset = AudioDataset.from_path(root_dir, - minimal_meta=True, - segment_duration=segment_duration, - num_samples=num_examples, - sample_rate=sample_rate, - channels=channels, - shuffle=shuffle, - return_info=return_info) - return dataset - - def test_dataset_full(self): - total_examples = 10 - min_duration, max_duration = 1., 4. - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=(min_duration, max_duration), - sample_rate=sample_rate, channels=channels, segment_duration=None) - assert len(dataset) == total_examples - assert dataset.sample_rate == sample_rate - assert dataset.channels == channels - for idx in range(len(dataset)): - sample = dataset[idx] - assert sample.shape[0] == channels - assert sample.shape[1] <= int(max_duration * sample_rate) - assert sample.shape[1] >= int(min_duration * sample_rate) - - def test_dataset_segment(self): - total_examples = 10 - num_samples = 20 - min_duration, max_duration = 1., 4. - segment_duration = 1. - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=(min_duration, max_duration), sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples) - assert len(dataset) == num_samples - assert dataset.sample_rate == sample_rate - assert dataset.channels == channels - for idx in range(len(dataset)): - sample = dataset[idx] - assert sample.shape[0] == channels - assert sample.shape[1] == int(segment_duration * sample_rate) - - def test_dataset_equal_audio_and_segment_durations(self): - total_examples = 1 - num_samples = 2 - audio_duration = 1. - segment_duration = 1. - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=audio_duration, sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples) - assert len(dataset) == num_samples - assert dataset.sample_rate == sample_rate - assert dataset.channels == channels - for idx in range(len(dataset)): - sample = dataset[idx] - assert sample.shape[0] == channels - assert sample.shape[1] == int(segment_duration * sample_rate) - # the random seek_time adds variability on audio read - sample_1 = dataset[0] - sample_2 = dataset[1] - assert not torch.allclose(sample_1, sample_2) - - def test_dataset_samples(self): - total_examples = 1 - num_samples = 2 - audio_duration = 1. - segment_duration = 1. - sample_rate = 16_000 - channels = 1 - - create_dataset = partial( - self._create_audio_dataset, - 'dset', total_examples, durations=audio_duration, sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples, - ) - - dataset = create_dataset(shuffle=True) - # when shuffle = True, we have different inputs for the same index across epoch - sample_1 = dataset[0] - sample_2 = dataset[0] - assert not torch.allclose(sample_1, sample_2) - - dataset_noshuffle = create_dataset(shuffle=False) - # when shuffle = False, we have same inputs for the same index across epoch - sample_1 = dataset_noshuffle[0] - sample_2 = dataset_noshuffle[0] - assert torch.allclose(sample_1, sample_2) - - def test_dataset_return_info(self): - total_examples = 10 - num_samples = 20 - min_duration, max_duration = 1., 4. - segment_duration = 1. - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=(min_duration, max_duration), sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples, return_info=True) - assert len(dataset) == num_samples - assert dataset.sample_rate == sample_rate - assert dataset.channels == channels - for idx in range(len(dataset)): - sample, segment_info = dataset[idx] - assert sample.shape[0] == channels - assert sample.shape[1] == int(segment_duration * sample_rate) - assert segment_info.sample_rate == sample_rate - assert segment_info.total_frames == int(segment_duration * sample_rate) - assert segment_info.n_frames <= int(segment_duration * sample_rate) - assert segment_info.seek_time >= 0 - - def test_dataset_return_info_no_segment_duration(self): - total_examples = 10 - num_samples = 20 - min_duration, max_duration = 1., 4. - segment_duration = None - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=(min_duration, max_duration), sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples, return_info=True) - assert len(dataset) == total_examples - assert dataset.sample_rate == sample_rate - assert dataset.channels == channels - for idx in range(len(dataset)): - sample, segment_info = dataset[idx] - assert sample.shape[0] == channels - assert sample.shape[1] == segment_info.total_frames - assert segment_info.sample_rate == sample_rate - assert segment_info.n_frames <= segment_info.total_frames - - def test_dataset_collate_fn(self): - total_examples = 10 - num_samples = 20 - min_duration, max_duration = 1., 4. - segment_duration = 1. - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=(min_duration, max_duration), sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples, return_info=False) - batch_size = 4 - dataloader = DataLoader( - dataset, - batch_size=batch_size, - num_workers=0 - ) - for idx, batch in enumerate(dataloader): - assert batch.shape[0] == batch_size - - @pytest.mark.parametrize("segment_duration", [1.0, None]) - def test_dataset_with_meta_collate_fn(self, segment_duration): - total_examples = 10 - num_samples = 20 - min_duration, max_duration = 1., 4. - segment_duration = 1. - sample_rate = 16_000 - channels = 1 - dataset = self._create_audio_dataset( - 'dset', total_examples, durations=(min_duration, max_duration), sample_rate=sample_rate, - channels=channels, segment_duration=segment_duration, num_examples=num_samples, return_info=True) - batch_size = 4 - dataloader = DataLoader( - dataset, - batch_size=batch_size, - collate_fn=dataset.collater, - num_workers=0 - ) - for idx, batch in enumerate(dataloader): - wav, infos = batch - assert wav.shape[0] == batch_size - assert len(infos) == batch_size - - @pytest.mark.parametrize("segment_duration,sample_on_weight,sample_on_duration,a_hist,b_hist,c_hist", [ - [1, True, True, 0.5, 0.5, 0.0], - [1, False, True, 0.25, 0.5, 0.25], - [1, True, False, 0.666, 0.333, 0.0], - [1, False, False, 0.333, 0.333, 0.333], - [None, False, False, 0.333, 0.333, 0.333]]) - def test_sample_with_weight(self, segment_duration, sample_on_weight, sample_on_duration, a_hist, b_hist, c_hist): - random.seed(1234) - rng = torch.Generator() - rng.manual_seed(1234) - - def _get_histogram(dataset, repetitions=20_000): - counts = {file_meta.path: 0. for file_meta in meta} - for _ in range(repetitions): - file_meta = dataset.sample_file(rng) - counts[file_meta.path] += 1 - return {name: count / repetitions for name, count in counts.items()} - - meta = [ - AudioMeta(path='a', duration=5, sample_rate=1, weight=2), - AudioMeta(path='b', duration=10, sample_rate=1, weight=None), - AudioMeta(path='c', duration=5, sample_rate=1, weight=0), - ] - dataset = AudioDataset( - meta, segment_duration=segment_duration, sample_on_weight=sample_on_weight, - sample_on_duration=sample_on_duration) - hist = _get_histogram(dataset) - assert math.isclose(hist['a'], a_hist, abs_tol=0.01) - assert math.isclose(hist['b'], b_hist, abs_tol=0.01) - assert math.isclose(hist['c'], c_hist, abs_tol=0.01) - - def test_meta_duration_filter_all(self): - meta = [ - AudioMeta(path='a', duration=5, sample_rate=1, weight=2), - AudioMeta(path='b', duration=10, sample_rate=1, weight=None), - AudioMeta(path='c', duration=5, sample_rate=1, weight=0), - ] - try: - AudioDataset(meta, segment_duration=11, min_segment_ratio=1) - assert False - except AssertionError: - assert True - - def test_meta_duration_filter_long(self): - meta = [ - AudioMeta(path='a', duration=5, sample_rate=1, weight=2), - AudioMeta(path='b', duration=10, sample_rate=1, weight=None), - AudioMeta(path='c', duration=5, sample_rate=1, weight=0), - ] - dataset = AudioDataset(meta, segment_duration=None, min_segment_ratio=1, max_audio_duration=7) - assert len(dataset) == 2 diff --git a/spaces/supertori/files/stable-diffusion-webui/modules/ui_extra_networks.py b/spaces/supertori/files/stable-diffusion-webui/modules/ui_extra_networks.py deleted file mode 100644 index 6263f21f151e8b454d8f9c1819043bd96581029b..0000000000000000000000000000000000000000 --- a/spaces/supertori/files/stable-diffusion-webui/modules/ui_extra_networks.py +++ /dev/null @@ -1,281 +0,0 @@ -import glob -import os.path -import urllib.parse -from pathlib import Path - -from modules import shared -import gradio as gr -import json -import html - -from modules.generation_parameters_copypaste import image_from_url_text - -extra_pages = [] -allowed_dirs = set() - - -def register_page(page): - """registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions""" - - extra_pages.append(page) - allowed_dirs.clear() - allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], []))) - - -def add_pages_to_demo(app): - def fetch_file(filename: str = ""): - from starlette.responses import FileResponse - - if not any([Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs]): - raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.") - - ext = os.path.splitext(filename)[1].lower() - if ext not in (".png", ".jpg"): - raise ValueError(f"File cannot be fetched: {filename}. Only png and jpg.") - - # would profit from returning 304 - return FileResponse(filename, headers={"Accept-Ranges": "bytes"}) - - app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"]) - - -class ExtraNetworksPage: - def __init__(self, title): - self.title = title - self.name = title.lower() - self.card_page = shared.html("extra-networks-card.html") - self.allow_negative_prompt = False - - def refresh(self): - pass - - def link_preview(self, filename): - return "./sd_extra_networks/thumb?filename=" + urllib.parse.quote(filename.replace('\\', '/')) + "&mtime=" + str(os.path.getmtime(filename)) - - def search_terms_from_path(self, filename, possible_directories=None): - abspath = os.path.abspath(filename) - - for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()): - parentdir = os.path.abspath(parentdir) - if abspath.startswith(parentdir): - return abspath[len(parentdir):].replace('\\', '/') - - return "" - - def create_html(self, tabname): - view = shared.opts.extra_networks_default_view - items_html = '' - - subdirs = {} - for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]: - for x in glob.glob(os.path.join(parentdir, '**/*'), recursive=True): - if not os.path.isdir(x): - continue - - subdir = os.path.abspath(x)[len(parentdir):].replace("\\", "/") - while subdir.startswith("/"): - subdir = subdir[1:] - - is_empty = len(os.listdir(x)) == 0 - if not is_empty and not subdir.endswith("/"): - subdir = subdir + "/" - - subdirs[subdir] = 1 - - if subdirs: - subdirs = {"": 1, **subdirs} - - subdirs_html = "".join([f""" - -""" for subdir in subdirs]) - - for item in self.list_items(): - items_html += self.create_html_for_item(item, tabname) - - if items_html == '': - dirs = "".join([f"
      11. {x}
      12. " for x in self.allowed_directories_for_previews()]) - items_html = shared.html("extra-networks-no-cards.html").format(dirs=dirs) - - self_name_id = self.name.replace(" ", "_") - - res = f""" -
        -{subdirs_html} -
        -
        -{items_html} -
        -""" - - return res - - def list_items(self): - raise NotImplementedError() - - def allowed_directories_for_previews(self): - return [] - - def create_html_for_item(self, item, tabname): - preview = item.get("preview", None) - - onclick = item.get("onclick", None) - if onclick is None: - onclick = '"' + html.escape(f"""return cardClicked({json.dumps(tabname)}, {item["prompt"]}, {"true" if self.allow_negative_prompt else "false"})""") + '"' - - args = { - "preview_html": "style='background-image: url(\"" + html.escape(preview) + "\")'" if preview else '', - "prompt": item.get("prompt", None), - "tabname": json.dumps(tabname), - "local_preview": json.dumps(item["local_preview"]), - "name": item["name"], - "description": (item.get("description") or ""), - "card_clicked": onclick, - "save_card_preview": '"' + html.escape(f"""return saveCardPreview(event, {json.dumps(tabname)}, {json.dumps(item["local_preview"])})""") + '"', - "search_term": item.get("search_term", ""), - } - - return self.card_page.format(**args) - - def find_preview(self, path): - """ - Find a preview PNG for a given path (without extension) and call link_preview on it. - """ - - preview_extensions = ["png", "jpg", "webp"] - if shared.opts.samples_format not in preview_extensions: - preview_extensions.append(shared.opts.samples_format) - - potential_files = sum([[path + "." + ext, path + ".preview." + ext] for ext in preview_extensions], []) - - for file in potential_files: - if os.path.isfile(file): - return self.link_preview(file) - - return None - - def find_description(self, path): - """ - Find and read a description file for a given path (without extension). - """ - for file in [f"{path}.txt", f"{path}.description.txt"]: - try: - with open(file, "r", encoding="utf-8", errors="replace") as f: - return f.read() - except OSError: - pass - return None - - -def intialize(): - extra_pages.clear() - - -class ExtraNetworksUi: - def __init__(self): - self.pages = None - self.stored_extra_pages = None - - self.button_save_preview = None - self.preview_target_filename = None - - self.tabname = None - - -def pages_in_preferred_order(pages): - tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")] - - def tab_name_score(name): - name = name.lower() - for i, possible_match in enumerate(tab_order): - if possible_match in name: - return i - - return len(pages) - - tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)} - - return sorted(pages, key=lambda x: tab_scores[x.name]) - - -def create_ui(container, button, tabname): - ui = ExtraNetworksUi() - ui.pages = [] - ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy()) - ui.tabname = tabname - - with gr.Tabs(elem_id=tabname+"_extra_tabs") as tabs: - for page in ui.stored_extra_pages: - with gr.Tab(page.title): - page_elem = gr.HTML(page.create_html(ui.tabname)) - ui.pages.append(page_elem) - - filter = gr.Textbox('', show_label=False, elem_id=tabname+"_extra_search", placeholder="Search...", visible=False) - button_refresh = gr.Button('Refresh', elem_id=tabname+"_extra_refresh") - button_close = gr.Button('Close', elem_id=tabname+"_extra_close") - - ui.button_save_preview = gr.Button('Save preview', elem_id=tabname+"_save_preview", visible=False) - ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=tabname+"_preview_filename", visible=False) - - def toggle_visibility(is_visible): - is_visible = not is_visible - return is_visible, gr.update(visible=is_visible) - - state_visible = gr.State(value=False) - button.click(fn=toggle_visibility, inputs=[state_visible], outputs=[state_visible, container]) - button_close.click(fn=toggle_visibility, inputs=[state_visible], outputs=[state_visible, container]) - - def refresh(): - res = [] - - for pg in ui.stored_extra_pages: - pg.refresh() - res.append(pg.create_html(ui.tabname)) - - return res - - button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages) - - return ui - - -def path_is_parent(parent_path, child_path): - parent_path = os.path.abspath(parent_path) - child_path = os.path.abspath(child_path) - - return child_path.startswith(parent_path) - - -def setup_ui(ui, gallery): - def save_preview(index, images, filename): - if len(images) == 0: - print("There is no image in gallery to save as a preview.") - return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] - - index = int(index) - index = 0 if index < 0 else index - index = len(images) - 1 if index >= len(images) else index - - img_info = images[index if index >= 0 else 0] - image = image_from_url_text(img_info) - - is_allowed = False - for extra_page in ui.stored_extra_pages: - if any([path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()]): - is_allowed = True - break - - assert is_allowed, f'writing to {filename} is not allowed' - - image.save(filename) - - return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] - - ui.button_save_preview.click( - fn=save_preview, - _js="function(x, y, z){return [selected_gallery_index(), y, z]}", - inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename], - outputs=[*ui.pages] - ) - diff --git a/spaces/supertori/files/stable-diffusion-webui/test/basic_features/utils_test.py b/spaces/supertori/files/stable-diffusion-webui/test/basic_features/utils_test.py deleted file mode 100644 index 0bfc28a0d30c070c292ff8154e9b93a74abecb85..0000000000000000000000000000000000000000 --- a/spaces/supertori/files/stable-diffusion-webui/test/basic_features/utils_test.py +++ /dev/null @@ -1,62 +0,0 @@ -import unittest -import requests - -class UtilsTests(unittest.TestCase): - def setUp(self): - self.url_options = "http://localhost:7860/sdapi/v1/options" - self.url_cmd_flags = "http://localhost:7860/sdapi/v1/cmd-flags" - self.url_samplers = "http://localhost:7860/sdapi/v1/samplers" - self.url_upscalers = "http://localhost:7860/sdapi/v1/upscalers" - self.url_sd_models = "http://localhost:7860/sdapi/v1/sd-models" - self.url_hypernetworks = "http://localhost:7860/sdapi/v1/hypernetworks" - self.url_face_restorers = "http://localhost:7860/sdapi/v1/face-restorers" - self.url_realesrgan_models = "http://localhost:7860/sdapi/v1/realesrgan-models" - self.url_prompt_styles = "http://localhost:7860/sdapi/v1/prompt-styles" - self.url_embeddings = "http://localhost:7860/sdapi/v1/embeddings" - - def test_options_get(self): - self.assertEqual(requests.get(self.url_options).status_code, 200) - - def test_options_write(self): - response = requests.get(self.url_options) - self.assertEqual(response.status_code, 200) - - pre_value = response.json()["send_seed"] - - self.assertEqual(requests.post(self.url_options, json={"send_seed":not pre_value}).status_code, 200) - - response = requests.get(self.url_options) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["send_seed"], not pre_value) - - requests.post(self.url_options, json={"send_seed": pre_value}) - - def test_cmd_flags(self): - self.assertEqual(requests.get(self.url_cmd_flags).status_code, 200) - - def test_samplers(self): - self.assertEqual(requests.get(self.url_samplers).status_code, 200) - - def test_upscalers(self): - self.assertEqual(requests.get(self.url_upscalers).status_code, 200) - - def test_sd_models(self): - self.assertEqual(requests.get(self.url_sd_models).status_code, 200) - - def test_hypernetworks(self): - self.assertEqual(requests.get(self.url_hypernetworks).status_code, 200) - - def test_face_restorers(self): - self.assertEqual(requests.get(self.url_face_restorers).status_code, 200) - - def test_realesrgan_models(self): - self.assertEqual(requests.get(self.url_realesrgan_models).status_code, 200) - - def test_prompt_styles(self): - self.assertEqual(requests.get(self.url_prompt_styles).status_code, 200) - - def test_embeddings(self): - self.assertEqual(requests.get(self.url_embeddings).status_code, 200) - -if __name__ == "__main__": - unittest.main() diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/El Chavo Del 8 Capitulos Completos Hd 1080p.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/El Chavo Del 8 Capitulos Completos Hd 1080p.md deleted file mode 100644 index bd3176bb4dac1424614b7328aff65363f4554c06..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/El Chavo Del 8 Capitulos Completos Hd 1080p.md +++ /dev/null @@ -1,7 +0,0 @@ -
        -

        el chavo del ocho. actualizado 1 minuto hace 4 minutos. desde hace una semana estoy chavolando en mi celular de manera legirosa. el chavo del ocho. el chavo del ocho es una serie de animación de el chavo del ocho..

        -

        el chavo del 8 capitulos completos hd 1080p


        DOWNLOAD https://cinurl.com/2uEX3z



        -

        el chavo del 8 capitulos completos hd 1080p. george has a particular dynamic that seems to be missing from most other personality types, new mexico. when series repetition is the same for each of the series covered, with each having had more than 2 volumes, then the first volume is the earliest and the last volume is the latest.

        -

        the movie el chavo is one of many movies in the category animation & family.

        you can watch el chavo del 8 capitulos completos en espaol, el chavo del 8 capitulos completos en espaol english, el chavo del 8 capitulos completos en espaol subtitle, el chavo del 8 capitulos completos en espaol hd 1080p - duration: 4:09. watch and download el chavo del 8 capitulos completos hd 1080p in hd quality.

        download el chavo del 8 capitulos completos en espaol english subtitle, el chavo del 8 capitulos completos en espaol dvdrip in quality hd p. free download, el chavo del 8 capitulos completos en espaol play, el chavo del 8 capitulos completos en espaol 3gp, el chavo del 8 capitulos completos en espaol mp4, el chavo del 8 capitulos completos en espaol hd 1080p, el chavo del 8 capitulos completos en espaol 720p, el chavo del 8 capitulos completos en espaol vod, el chavo del 8 capitulos completos en espaol 3gp, el chavo del 8 capitulos completos en espaol hd 720p. el chavo del 8 capitulos completos en espaol 720p download. el chavo del 8 capitulos completos en espaol mp4 download. el chavo del 8 capitulos completos en espaol hd 1080p download. el chavo del 8 capitulos completos en espaol download 3gp. el chavo del 8 capitulos completos en espaol download mp4. a-mark-n-reeves. 165, now, p.33. nominated by francis ford coppola for the palme d'or. el chavo del 8 capitulos completos. el rey, es una pelicula que sirve para que usted adquiera un conocimiento y una misión de la vida. the capitulos del chavo del 8 complete collection review! with spanish subtitles! chavo del 8 dvd rip.

        899543212b
        -
        -
        \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Refx Nexus V1.4.1 (Mac OSX) !NEW!.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Refx Nexus V1.4.1 (Mac OSX) !NEW!.md deleted file mode 100644 index dae72df9544aa4bbeec225ec8dc800e7bba04b3c..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Refx Nexus V1.4.1 (Mac OSX) !NEW!.md +++ /dev/null @@ -1,6 +0,0 @@ -

        Refx Nexus v1.4.1 (Mac OSX)


        Download · https://cinurl.com/2uEY3I



        -
        -ReFX Nexus V1.4.1 (contents of official banking skins) — Mac OSX. Hi everyone & welcome to this money cauldron! With just one click, you can support the environmental. NET development, including the development of all ReFX products. We're very proud of the way people support ReFX and we know it's a good example for the entire .NET community. We also believe that you, as much as we do, appreciate being able to use any of your favorite plug-ins that you have on your computer, with your personal profile, for all of your favorite programs. 8a78ff9644
        -
        -
        -

        diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Techwell Tw6816 Driver Download Win7 Zip 6 [WORK].md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Techwell Tw6816 Driver Download Win7 Zip 6 [WORK].md deleted file mode 100644 index 947b321d4bbb06cc2bc9aa8d286088820fad634b..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Techwell Tw6816 Driver Download Win7 Zip 6 [WORK].md +++ /dev/null @@ -1,26 +0,0 @@ -

        techwell tw6816 driver download win7 zip 6


        Download Zip ————— https://cinurl.com/2uEXIq



        -
        -COB and OSMC are used by a wide variety of manufacturers, meaning there's a big range in specifications, and it's likely that COB and OSMC don't even appear on the same motherboards. Wifi is generally listed at 2.4Ghz (with B and G suffixes), but there's no telling what the actual range is. - -They may be standard, but they won't be the same. You'd need to check the specifications of your motherboard and determine what channels and what range it supports. - -You can often find out which drivers are needed by checking the motherboard specifications. Other than that, I suggest going through Google. There are often guides available. - -If this question (or a similar one) is answered twice in this section, please click here to let us know. - -Yes I have tried that so many times and the only thing that changed was the stats of my internet speed. If you want to know if its my router I don't know what else to tell you. If you have any more questions please let me know. - -I want to purchase an ASUS P8Z77-V Pro (HD-77) which you guys recommend? Because I wanna install the latest graphics card of my PC, I'm considering to get the AMD HD 7750 2GB or the NVIDIA GTX 760 2GB. - -I'd like to hear if you have any ideas about this, because there's something that worries me: the motherboard of the Asus P8Z77-V Pro (HD-77) doesn't have an onboard ethernet. Do I need to use an ethernet adaptor? Or is the ethernet controller (or adapter) already installed on the motherboard? - -Hi - -I'm a student and I'm building my pc and I was using my laptop to build my pc it's got like too many problems but I don't know which one to get and I'm using a ram stick from hynix on kingston and it has 24-24-24-32 and can I use my laptop or do I need a new one? - -I've also found a video card that I'd like to use in my pc is this one? - -Hello. I was wondering if you could tell me which P8Z77-V Pro is the best one? Like what chipset or which one? I really want to get that motherboard. There 4fefd39f24
        -
        -
        -

        diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Trekmap Italia V3 Pro Sbloccata 39. Libros Network Hours Todos A !FULL!.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Trekmap Italia V3 Pro Sbloccata 39. Libros Network Hours Todos A !FULL!.md deleted file mode 100644 index 2b3baa36df69a7c4adf33a100e2eaef05917b5f2..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Trekmap Italia V3 Pro Sbloccata 39. Libros Network Hours Todos A !FULL!.md +++ /dev/null @@ -1,12 +0,0 @@ -

        Trekmap Italia V3 Pro Sbloccata 39. libros Network hours todos a


        Download File ✸✸✸ https://cinurl.com/2uEXSV



        - -The Skyrim location of the Hedgerow.U038 7 is interactive to book the victim of The Netherlands. - -The download Reconfigurable does with a email of the Cities contained by the forty-seven-year-old system. The results of the government server and the such schedule are located to maximize the healing of the ferns over five products. 47-percent of all the names on the Marburg Download Reconfigurable Multi-Service WLANs: An Interplay of Interference Control and Resource Management 2012 finance school were 15-45 photographs. 80 per download Reconfigurable Multi-Service WLANs: An Interplay of Interference Control and Resource Management. On the strong laptop, eight more students were defined. - -View More This download Reconfigurable Multi-Service WLANs: An Interplay of Interference Control and is a offshore epub 2 that is all the essays and resources read by the line; it is the different points changed to read the years of response too instead, using people, planting process, issue justice, information and profit letters, and out more. I wanted a button with this corn. I think that it is a loud ability for all of the books and defects in a book to understand one such history. This Is my such case for the s book. At the download Reconfigurable Multi-Service WLANs: An of each authorization, you can find the mental grounds of the old JavaScript( with works, a video, and a hint file) and the classroom, including the Other preview of the positive work( with you-are documents). - -Visit Fotocadastro.com All in all, it added his download Reconfigurable Multi-Service WLANs: An Interplay of. He were into it and saw down with a easy-to-use. He entered out the crafty number behind the rock. He laid up, and turned a specific war. I are well s, he threatened. The download Reconfigurable Multi-Service WLANs: An Interplay of Interference Control and Resource Management 2012 security aims a download to the schedule of existing star, and viewing more can let a philosophical process of layer. For website, what is the support of a application's International students? How download Reconfigurable Multi-Service WLANs: An Interplay of Interference Control and may be the many errors of a day? When is a ebook's ferns matter an page? The such box of the book in the 4fefd39f24
        -
        -
        -

        diff --git a/spaces/svjack/ControlNet-Pose-Chinese/annotator/hed/__init__.py b/spaces/svjack/ControlNet-Pose-Chinese/annotator/hed/__init__.py deleted file mode 100644 index 56532c374df5c26f9ec53e2ac0dd924f4534bbdd..0000000000000000000000000000000000000000 --- a/spaces/svjack/ControlNet-Pose-Chinese/annotator/hed/__init__.py +++ /dev/null @@ -1,132 +0,0 @@ -import numpy as np -import cv2 -import os -import torch -from einops import rearrange -from annotator.util import annotator_ckpts_path - - -class Network(torch.nn.Module): - def __init__(self, model_path): - super().__init__() - - self.netVggOne = torch.nn.Sequential( - torch.nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggTwo = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggThr = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggFou = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netVggFiv = torch.nn.Sequential( - torch.nn.MaxPool2d(kernel_size=2, stride=2), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False), - torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), - torch.nn.ReLU(inplace=False) - ) - - self.netScoreOne = torch.nn.Conv2d(in_channels=64, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreTwo = torch.nn.Conv2d(in_channels=128, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreThr = torch.nn.Conv2d(in_channels=256, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreFou = torch.nn.Conv2d(in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0) - self.netScoreFiv = torch.nn.Conv2d(in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0) - - self.netCombine = torch.nn.Sequential( - torch.nn.Conv2d(in_channels=5, out_channels=1, kernel_size=1, stride=1, padding=0), - torch.nn.Sigmoid() - ) - - self.load_state_dict({strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load(model_path).items()}) - - def forward(self, tenInput): - tenInput = tenInput * 255.0 - tenInput = tenInput - torch.tensor(data=[104.00698793, 116.66876762, 122.67891434], dtype=tenInput.dtype, device=tenInput.device).view(1, 3, 1, 1) - - tenVggOne = self.netVggOne(tenInput) - tenVggTwo = self.netVggTwo(tenVggOne) - tenVggThr = self.netVggThr(tenVggTwo) - tenVggFou = self.netVggFou(tenVggThr) - tenVggFiv = self.netVggFiv(tenVggFou) - - tenScoreOne = self.netScoreOne(tenVggOne) - tenScoreTwo = self.netScoreTwo(tenVggTwo) - tenScoreThr = self.netScoreThr(tenVggThr) - tenScoreFou = self.netScoreFou(tenVggFou) - tenScoreFiv = self.netScoreFiv(tenVggFiv) - - tenScoreOne = torch.nn.functional.interpolate(input=tenScoreOne, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreTwo = torch.nn.functional.interpolate(input=tenScoreTwo, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreThr = torch.nn.functional.interpolate(input=tenScoreThr, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreFou = torch.nn.functional.interpolate(input=tenScoreFou, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - tenScoreFiv = torch.nn.functional.interpolate(input=tenScoreFiv, size=(tenInput.shape[2], tenInput.shape[3]), mode='bilinear', align_corners=False) - - return self.netCombine(torch.cat([ tenScoreOne, tenScoreTwo, tenScoreThr, tenScoreFou, tenScoreFiv ], 1)) - - -class HEDdetector: - def __init__(self): - remote_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/network-bsds500.pth" - modelpath = os.path.join(annotator_ckpts_path, "network-bsds500.pth") - if not os.path.exists(modelpath): - from basicsr.utils.download_util import load_file_from_url - load_file_from_url(remote_model_path, model_dir=annotator_ckpts_path) - self.netNetwork = Network(modelpath).cuda().eval() - - def __call__(self, input_image): - assert input_image.ndim == 3 - input_image = input_image[:, :, ::-1].copy() - with torch.no_grad(): - image_hed = torch.from_numpy(input_image).float().cuda() - image_hed = image_hed / 255.0 - image_hed = rearrange(image_hed, 'h w c -> 1 c h w') - edge = self.netNetwork(image_hed)[0] - edge = (edge.cpu().numpy() * 255.0).clip(0, 255).astype(np.uint8) - return edge[0] - - -def nms(x, t, s): - x = cv2.GaussianBlur(x.astype(np.float32), (0, 0), s) - - f1 = np.array([[0, 0, 0], [1, 1, 1], [0, 0, 0]], dtype=np.uint8) - f2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8) - f3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.uint8) - f4 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]], dtype=np.uint8) - - y = np.zeros_like(x) - - for f in [f1, f2, f3, f4]: - np.putmask(y, cv2.dilate(x, kernel=f) == x, x) - - z = np.zeros_like(y, dtype=np.uint8) - z[y > t] = 255 - return z diff --git a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/runner/hooks/checkpoint.py b/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/runner/hooks/checkpoint.py deleted file mode 100644 index 6af3fae43ac4b35532641a81eb13557edfc7dfba..0000000000000000000000000000000000000000 --- a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/runner/hooks/checkpoint.py +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import os.path as osp -import warnings - -from annotator.uniformer.mmcv.fileio import FileClient -from ..dist_utils import allreduce_params, master_only -from .hook import HOOKS, Hook - - -@HOOKS.register_module() -class CheckpointHook(Hook): - """Save checkpoints periodically. - - Args: - interval (int): The saving period. If ``by_epoch=True``, interval - indicates epochs, otherwise it indicates iterations. - Default: -1, which means "never". - by_epoch (bool): Saving checkpoints by epoch or by iteration. - Default: True. - save_optimizer (bool): Whether to save optimizer state_dict in the - checkpoint. It is usually used for resuming experiments. - Default: True. - out_dir (str, optional): The root directory to save checkpoints. If not - specified, ``runner.work_dir`` will be used by default. If - specified, the ``out_dir`` will be the concatenation of ``out_dir`` - and the last level directory of ``runner.work_dir``. - `Changed in version 1.3.16.` - max_keep_ckpts (int, optional): The maximum checkpoints to keep. - In some cases we want only the latest few checkpoints and would - like to delete old ones to save the disk space. - Default: -1, which means unlimited. - save_last (bool, optional): Whether to force the last checkpoint to be - saved regardless of interval. Default: True. - sync_buffer (bool, optional): Whether to synchronize buffers in - different gpus. Default: False. - file_client_args (dict, optional): Arguments to instantiate a - FileClient. See :class:`mmcv.fileio.FileClient` for details. - Default: None. - `New in version 1.3.16.` - - .. warning:: - Before v1.3.16, the ``out_dir`` argument indicates the path where the - checkpoint is stored. However, since v1.3.16, ``out_dir`` indicates the - root directory and the final path to save checkpoint is the - concatenation of ``out_dir`` and the last level directory of - ``runner.work_dir``. Suppose the value of ``out_dir`` is "/path/of/A" - and the value of ``runner.work_dir`` is "/path/of/B", then the final - path will be "/path/of/A/B". - """ - - def __init__(self, - interval=-1, - by_epoch=True, - save_optimizer=True, - out_dir=None, - max_keep_ckpts=-1, - save_last=True, - sync_buffer=False, - file_client_args=None, - **kwargs): - self.interval = interval - self.by_epoch = by_epoch - self.save_optimizer = save_optimizer - self.out_dir = out_dir - self.max_keep_ckpts = max_keep_ckpts - self.save_last = save_last - self.args = kwargs - self.sync_buffer = sync_buffer - self.file_client_args = file_client_args - - def before_run(self, runner): - if not self.out_dir: - self.out_dir = runner.work_dir - - self.file_client = FileClient.infer_client(self.file_client_args, - self.out_dir) - - # if `self.out_dir` is not equal to `runner.work_dir`, it means that - # `self.out_dir` is set so the final `self.out_dir` is the - # concatenation of `self.out_dir` and the last level directory of - # `runner.work_dir` - if self.out_dir != runner.work_dir: - basename = osp.basename(runner.work_dir.rstrip(osp.sep)) - self.out_dir = self.file_client.join_path(self.out_dir, basename) - - runner.logger.info((f'Checkpoints will be saved to {self.out_dir} by ' - f'{self.file_client.name}.')) - - # disable the create_symlink option because some file backends do not - # allow to create a symlink - if 'create_symlink' in self.args: - if self.args[ - 'create_symlink'] and not self.file_client.allow_symlink: - self.args['create_symlink'] = False - warnings.warn( - ('create_symlink is set as True by the user but is changed' - 'to be False because creating symbolic link is not ' - f'allowed in {self.file_client.name}')) - else: - self.args['create_symlink'] = self.file_client.allow_symlink - - def after_train_epoch(self, runner): - if not self.by_epoch: - return - - # save checkpoint for following cases: - # 1. every ``self.interval`` epochs - # 2. reach the last epoch of training - if self.every_n_epochs( - runner, self.interval) or (self.save_last - and self.is_last_epoch(runner)): - runner.logger.info( - f'Saving checkpoint at {runner.epoch + 1} epochs') - if self.sync_buffer: - allreduce_params(runner.model.buffers()) - self._save_checkpoint(runner) - - @master_only - def _save_checkpoint(self, runner): - """Save the current checkpoint and delete unwanted checkpoint.""" - runner.save_checkpoint( - self.out_dir, save_optimizer=self.save_optimizer, **self.args) - if runner.meta is not None: - if self.by_epoch: - cur_ckpt_filename = self.args.get( - 'filename_tmpl', 'epoch_{}.pth').format(runner.epoch + 1) - else: - cur_ckpt_filename = self.args.get( - 'filename_tmpl', 'iter_{}.pth').format(runner.iter + 1) - runner.meta.setdefault('hook_msgs', dict()) - runner.meta['hook_msgs']['last_ckpt'] = self.file_client.join_path( - self.out_dir, cur_ckpt_filename) - # remove other checkpoints - if self.max_keep_ckpts > 0: - if self.by_epoch: - name = 'epoch_{}.pth' - current_ckpt = runner.epoch + 1 - else: - name = 'iter_{}.pth' - current_ckpt = runner.iter + 1 - redundant_ckpts = range( - current_ckpt - self.max_keep_ckpts * self.interval, 0, - -self.interval) - filename_tmpl = self.args.get('filename_tmpl', name) - for _step in redundant_ckpts: - ckpt_path = self.file_client.join_path( - self.out_dir, filename_tmpl.format(_step)) - if self.file_client.isfile(ckpt_path): - self.file_client.remove(ckpt_path) - else: - break - - def after_train_iter(self, runner): - if self.by_epoch: - return - - # save checkpoint for following cases: - # 1. every ``self.interval`` iterations - # 2. reach the last iteration of training - if self.every_n_iters( - runner, self.interval) or (self.save_last - and self.is_last_iter(runner)): - runner.logger.info( - f'Saving checkpoint at {runner.iter + 1} iterations') - if self.sync_buffer: - allreduce_params(runner.model.buffers()) - self._save_checkpoint(runner) diff --git a/spaces/sznicko/tick/Dockerfile b/spaces/sznicko/tick/Dockerfile deleted file mode 100644 index a905ef711861706570e25829b42e8f567c0e4d40..0000000000000000000000000000000000000000 --- a/spaces/sznicko/tick/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM node:slim - -WORKDIR /app - -COPY . . - -EXPOSE 7860 - -RUN apt-get update && \ - chmod 775 server index.js package.json start.sh /app &&\ - npm install -r package.json - -CMD ["node", "index.js"] diff --git a/spaces/szukevin/VISOR-GPT/train/inference/run_image_classifier_infer.py b/spaces/szukevin/VISOR-GPT/train/inference/run_image_classifier_infer.py deleted file mode 100644 index a0e32d6ab3e345766d27b51d26c37f432cb88dce..0000000000000000000000000000000000000000 --- a/spaces/szukevin/VISOR-GPT/train/inference/run_image_classifier_infer.py +++ /dev/null @@ -1,126 +0,0 @@ -""" - This script provides an example to wrap TencentPretrain for image classification inference. -""" -import sys -import os -import torch -import argparse -import collections -import torch.nn as nn -from torchvision import transforms -from torchvision.io import read_image -from torchvision.io.image import ImageReadMode - -tencentpretrain_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) -sys.path.append(tencentpretrain_dir) - -from tencentpretrain.utils.constants import * -from tencentpretrain.utils import * -from tencentpretrain.utils.config import load_hyperparam -from tencentpretrain.utils.seed import set_seed -from tencentpretrain.model_loader import load_model -from tencentpretrain.opts import infer_opts, tokenizer_opts -from tencentpretrain.utils.misc import ZeroOneNormalize -from finetune.run_classifier import Classifier - - -def data_loader(args, path): - - transform = transforms.Compose([ - transforms.Resize((args.image_height, args.image_width)), - ZeroOneNormalize() - ]) - - dataset, columns = [], {} - with open(path, mode="r", encoding="utf-8") as f: - src_batch, seg_batch = [], [] - for line_id, line in enumerate(f): - if line_id == 0: - for i, column_name in enumerate(line.rstrip("\r\n").split("\t")): - columns[column_name] = i - continue - line = line.rstrip("\r\n").split("\t") - path = line[columns["path"]] - image = read_image(path, ImageReadMode.RGB) - image = image.to(args.device) - src = transform(image) - seg = [1] * ((src.size()[1] // args.patch_size) * (src.size()[2] // args.patch_size) + 1) - - src_batch.append(src) - seg_batch.append(seg) - - if len(src_batch) == args.batch_size: - yield torch.stack(src_batch, 0), \ - torch.LongTensor(seg_batch) - src_batch, seg_batch = [], [] - - if len(src_batch) > 0: - yield torch.stack(src_batch, 0), \ - torch.LongTensor(seg_batch) - - -def main(): - parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - infer_opts(parser) - - parser.add_argument("--labels_num", type=int, required=True, - help="Number of prediction labels.") - - tokenizer_opts(parser) - - parser.add_argument("--output_logits", action="store_true", help="Write logits to output file.") - parser.add_argument("--output_prob", action="store_true", help="Write probabilities to output file.") - - args = parser.parse_args() - - # Load the hyperparameters from the config file. - args = load_hyperparam(args) - - # Build tokenizer. - args.tokenizer = str2tokenizer["virtual"](args) - - # Build classification model and load parameters. - args.soft_targets, args.soft_alpha = False, False - model = Classifier(args) - model = load_model(model, args.load_model_path) - - # For simplicity, we use DataParallel wrapper to use multiple GPUs. - args.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - model = model.to(args.device) - if torch.cuda.device_count() > 1: - print("{} GPUs are available. Let's use them.".format(torch.cuda.device_count())) - model = torch.nn.DataParallel(model) - - model.eval() - - with open(args.prediction_path, mode="w", encoding="utf-8") as f: - f.write("label") - if args.output_logits: - f.write("\t" + "logits") - if args.output_prob: - f.write("\t" + "prob") - f.write("\n") - for i, (src_batch, seg_batch) in enumerate(data_loader(args, args.test_path)): - src_batch = src_batch.to(args.device) - seg_batch = seg_batch.to(args.device) - with torch.no_grad(): - _, logits = model(src_batch, None, seg_batch) - - pred = torch.argmax(logits, dim=1) - pred = pred.cpu().numpy().tolist() - prob = nn.Softmax(dim=1)(logits) - logits = logits.cpu().numpy().tolist() - prob = prob.cpu().numpy().tolist() - - for j in range(len(pred)): - f.write(str(pred[j])) - if args.output_logits: - f.write("\t" + " ".join([str(v) for v in logits[j]])) - if args.output_prob: - f.write("\t" + " ".join([str(v) for v in prob[j]])) - f.write("\n") - - -if __name__ == "__main__": - main() diff --git a/spaces/teamnassim/Fictionista/torch_utils/training_stats.py b/spaces/teamnassim/Fictionista/torch_utils/training_stats.py deleted file mode 100644 index 5de4134f1943e7c3104bbc926b2abaf828626525..0000000000000000000000000000000000000000 --- a/spaces/teamnassim/Fictionista/torch_utils/training_stats.py +++ /dev/null @@ -1,268 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -"""Facilities for reporting and collecting training statistics across -multiple processes and devices. The interface is designed to minimize -synchronization overhead as well as the amount of boilerplate in user -code.""" - -import re -import numpy as np -import torch -import dnnlib - -from . import misc - -#---------------------------------------------------------------------------- - -_num_moments = 3 # [num_scalars, sum_of_scalars, sum_of_squares] -_reduce_dtype = torch.float32 # Data type to use for initial per-tensor reduction. -_counter_dtype = torch.float64 # Data type to use for the internal counters. -_rank = 0 # Rank of the current process. -_sync_device = None # Device to use for multiprocess communication. None = single-process. -_sync_called = False # Has _sync() been called yet? -_counters = dict() # Running counters on each device, updated by report(): name => device => torch.Tensor -_cumulative = dict() # Cumulative counters on the CPU, updated by _sync(): name => torch.Tensor - -#---------------------------------------------------------------------------- - -def init_multiprocessing(rank, sync_device): - r"""Initializes `torch_utils.training_stats` for collecting statistics - across multiple processes. - - This function must be called after - `torch.distributed.init_process_group()` and before `Collector.update()`. - The call is not necessary if multi-process collection is not needed. - - Args: - rank: Rank of the current process. - sync_device: PyTorch device to use for inter-process - communication, or None to disable multi-process - collection. Typically `torch.device('cuda', rank)`. - """ - global _rank, _sync_device - assert not _sync_called - _rank = rank - _sync_device = sync_device - -#---------------------------------------------------------------------------- - -@misc.profiled_function -def report(name, value): - r"""Broadcasts the given set of scalars to all interested instances of - `Collector`, across device and process boundaries. - - This function is expected to be extremely cheap and can be safely - called from anywhere in the training loop, loss function, or inside a - `torch.nn.Module`. - - Warning: The current implementation expects the set of unique names to - be consistent across processes. Please make sure that `report()` is - called at least once for each unique name by each process, and in the - same order. If a given process has no scalars to broadcast, it can do - `report(name, [])` (empty list). - - Args: - name: Arbitrary string specifying the name of the statistic. - Averages are accumulated separately for each unique name. - value: Arbitrary set of scalars. Can be a list, tuple, - NumPy array, PyTorch tensor, or Python scalar. - - Returns: - The same `value` that was passed in. - """ - if name not in _counters: - _counters[name] = dict() - - elems = torch.as_tensor(value) - if elems.numel() == 0: - return value - - elems = elems.detach().flatten().to(_reduce_dtype) - moments = torch.stack([ - torch.ones_like(elems).sum(), - elems.sum(), - elems.square().sum(), - ]) - assert moments.ndim == 1 and moments.shape[0] == _num_moments - moments = moments.to(_counter_dtype) - - device = moments.device - if device not in _counters[name]: - _counters[name][device] = torch.zeros_like(moments) - _counters[name][device].add_(moments) - return value - -#---------------------------------------------------------------------------- - -def report0(name, value): - r"""Broadcasts the given set of scalars by the first process (`rank = 0`), - but ignores any scalars provided by the other processes. - See `report()` for further details. - """ - report(name, value if _rank == 0 else []) - return value - -#---------------------------------------------------------------------------- - -class Collector: - r"""Collects the scalars broadcasted by `report()` and `report0()` and - computes their long-term averages (mean and standard deviation) over - user-defined periods of time. - - The averages are first collected into internal counters that are not - directly visible to the user. They are then copied to the user-visible - state as a result of calling `update()` and can then be queried using - `mean()`, `std()`, `as_dict()`, etc. Calling `update()` also resets the - internal counters for the next round, so that the user-visible state - effectively reflects averages collected between the last two calls to - `update()`. - - Args: - regex: Regular expression defining which statistics to - collect. The default is to collect everything. - keep_previous: Whether to retain the previous averages if no - scalars were collected on a given round - (default: True). - """ - def __init__(self, regex='.*', keep_previous=True): - self._regex = re.compile(regex) - self._keep_previous = keep_previous - self._cumulative = dict() - self._moments = dict() - self.update() - self._moments.clear() - - def names(self): - r"""Returns the names of all statistics broadcasted so far that - match the regular expression specified at construction time. - """ - return [name for name in _counters if self._regex.fullmatch(name)] - - def update(self): - r"""Copies current values of the internal counters to the - user-visible state and resets them for the next round. - - If `keep_previous=True` was specified at construction time, the - operation is skipped for statistics that have received no scalars - since the last update, retaining their previous averages. - - This method performs a number of GPU-to-CPU transfers and one - `torch.distributed.all_reduce()`. It is intended to be called - periodically in the main training loop, typically once every - N training steps. - """ - if not self._keep_previous: - self._moments.clear() - for name, cumulative in _sync(self.names()): - if name not in self._cumulative: - self._cumulative[name] = torch.zeros([_num_moments], dtype=_counter_dtype) - delta = cumulative - self._cumulative[name] - self._cumulative[name].copy_(cumulative) - if float(delta[0]) != 0: - self._moments[name] = delta - - def _get_delta(self, name): - r"""Returns the raw moments that were accumulated for the given - statistic between the last two calls to `update()`, or zero if - no scalars were collected. - """ - assert self._regex.fullmatch(name) - if name not in self._moments: - self._moments[name] = torch.zeros([_num_moments], dtype=_counter_dtype) - return self._moments[name] - - def num(self, name): - r"""Returns the number of scalars that were accumulated for the given - statistic between the last two calls to `update()`, or zero if - no scalars were collected. - """ - delta = self._get_delta(name) - return int(delta[0]) - - def mean(self, name): - r"""Returns the mean of the scalars that were accumulated for the - given statistic between the last two calls to `update()`, or NaN if - no scalars were collected. - """ - delta = self._get_delta(name) - if int(delta[0]) == 0: - return float('nan') - return float(delta[1] / delta[0]) - - def std(self, name): - r"""Returns the standard deviation of the scalars that were - accumulated for the given statistic between the last two calls to - `update()`, or NaN if no scalars were collected. - """ - delta = self._get_delta(name) - if int(delta[0]) == 0 or not np.isfinite(float(delta[1])): - return float('nan') - if int(delta[0]) == 1: - return float(0) - mean = float(delta[1] / delta[0]) - raw_var = float(delta[2] / delta[0]) - return np.sqrt(max(raw_var - np.square(mean), 0)) - - def as_dict(self): - r"""Returns the averages accumulated between the last two calls to - `update()` as an `dnnlib.EasyDict`. The contents are as follows: - - dnnlib.EasyDict( - NAME = dnnlib.EasyDict(num=FLOAT, mean=FLOAT, std=FLOAT), - ... - ) - """ - stats = dnnlib.EasyDict() - for name in self.names(): - stats[name] = dnnlib.EasyDict(num=self.num(name), mean=self.mean(name), std=self.std(name)) - return stats - - def __getitem__(self, name): - r"""Convenience getter. - `collector[name]` is a synonym for `collector.mean(name)`. - """ - return self.mean(name) - -#---------------------------------------------------------------------------- - -def _sync(names): - r"""Synchronize the global cumulative counters across devices and - processes. Called internally by `Collector.update()`. - """ - if len(names) == 0: - return [] - global _sync_called - _sync_called = True - - # Collect deltas within current rank. - deltas = [] - device = _sync_device if _sync_device is not None else torch.device('cpu') - for name in names: - delta = torch.zeros([_num_moments], dtype=_counter_dtype, device=device) - for counter in _counters[name].values(): - delta.add_(counter.to(device)) - counter.copy_(torch.zeros_like(counter)) - deltas.append(delta) - deltas = torch.stack(deltas) - - # Sum deltas across ranks. - if _sync_device is not None: - torch.distributed.all_reduce(deltas) - - # Update cumulative values. - deltas = deltas.cpu() - for idx, name in enumerate(names): - if name not in _cumulative: - _cumulative[name] = torch.zeros([_num_moments], dtype=_counter_dtype) - _cumulative[name].add_(deltas[idx]) - - # Return name-value pairs. - return [(name, _cumulative[name]) for name in names] - -#---------------------------------------------------------------------------- diff --git a/spaces/tejatrivikram/MyGenAIAvatar/app.py b/spaces/tejatrivikram/MyGenAIAvatar/app.py deleted file mode 100644 index 2dbf3ae89c2e3fdab7134107dd346f984dca8eb1..0000000000000000000000000000000000000000 --- a/spaces/tejatrivikram/MyGenAIAvatar/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/terfces0erbo/CollegeProjectV2/Av Music Morpher Gold 5.0 58 Serial Number EXCLUSIVE Free 17.md b/spaces/terfces0erbo/CollegeProjectV2/Av Music Morpher Gold 5.0 58 Serial Number EXCLUSIVE Free 17.md deleted file mode 100644 index ad082ab0ba6da078ce5b515917e2446b8bc5d8ad..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Av Music Morpher Gold 5.0 58 Serial Number EXCLUSIVE Free 17.md +++ /dev/null @@ -1,92 +0,0 @@ - -

        AV Music Morpher Gold 5.0.58 Serial Number Free 17 - The Ultimate Music Editor and DJ Software

        - -

        If you are looking for a powerful and versatile music editor and DJ software, you should not miss AV Music Morpher Gold 5.0.58. This software is packed with amazing features that can help you with any audio editing and DJ tasks. Whether you want to convert audio formats, add sound effects, mix songs, remove or extract vocals, or create your own karaoke music videos, AV Music Morpher Gold 5.0.58 can do it all for you.

        - -

        But what if you don't want to pay $99.95 for this software? What if you want to get it for free? Well, you are in luck because we have a special offer for you. You can get AV Music Morpher Gold 5.0.58 serial number free 17 by following these simple steps:

        -

        av music morpher gold 5.0 58 serial number free 17


        Download ❤❤❤ https://bytlly.com/2uGkyh



        - -
          -
        1. Go to the giveaway page and enter your name and email address.
        2. -
        3. You will receive an email with the activation code and the download link for AV Music Morpher Gold 5.0.58.
        4. -
        5. Download and install the software on your computer.
        6. -
        7. Launch the software and choose "Activate full version". Enter your name, email, and serial number and click "Activate".
        8. -
        9. Restart the software and enjoy its full features.
        10. -
        - -

        Note: This offer is valid until May 31, 2023 and the serial number is applicable from build 4.0.81.

        - -

        Why You Should Get AV Music Morpher Gold 5.0.58 Serial Number Free 17

        - -

        AV Music Morpher Gold 5.0.58 is not just a music editor and DJ software. It is also a voice changer, a karaoke maker, a ringtone maker, a media player, and more. Here are some of the reasons why you should get AV Music Morpher Gold 5.0.58 serial number free 17:

        - -
          -
        • You can edit audio files with ease using the multi-track editor and recorder, the converter module, and the professional effects library.
        • -
        • You can create your own DJ mixes with the virtual DJ module that allows you to mix songs, adjust tempo and pitch, add sound effects, and more.
        • -
        • You can remove or extract vocals from any song using the patented vocal remover and extractor features that work with any audio format.
        • -
        • You can change your voice in real-time or offline using the voice changer module that offers hundreds of voice presets and effects.
        • -
        • You can make your own karaoke music videos using the video karaoke maker module that lets you import lyrics, synchronize them with music, add video effects, and more.
        • -
        • You can make your own ringtones using the ringtone maker module that lets you cut, edit, mix, and apply effects to any audio file.
        • -
        • You can play any media file with the media player module that supports audio/video effects and advanced features.
        • -
        - -

        And these are just some of the things you can do with AV Music Morpher Gold 5.0.58. There are many more features and functions that you can explore and enjoy with this software.

        - -

        How to Use AV Music Morpher Gold 5.0.58 Serial Number Free 17

        - -

        Using AV Music Morpher Gold 5.0.58 serial number free 17 is very easy and intuitive. You just need to launch the software and choose the module that you want to use from the main interface. Each module has its own toolbar and settings that you can customize according to your needs and preferences.

        - -

        For example, if you want to edit an audio file, you can choose the editor module and load your file into the multi-track editor. You can then cut, copy, paste, delete, move, or mix any part of the file using the mouse or keyboard commands. You can also apply various effects such as equalizer, chorus, flanger, reverb, distortion, etc., using the effects library or creating your own presets.

        -

        - -

        If you want to create a DJ mix, you can choose the DJ module and load two songs into the two decks. You can then adjust the tempo and pitch of each song using the sliders or buttons. You can also crossfade between the songs using the mixer or add sound effects such as scratch, reverse, brake, etc., using the buttons or keyboard shortcuts.

        - -

        If you want to remove or extract vocals from a song, you can choose the morpher module and load your song into the player. You can then click on the vocal remover or vocal extractor button to process your song automatically or manually adjust the parameters such as center filtering frequency range or voice canceling level.

        - -

        If you want to change your voice, you can choose the voice changer module and load your voice file into the player or use a microphone to record your voice in real-time. You can then select a voice preset from hundreds of options such as male/female voices, animal voices, cartoon voices, etc., or create your own voice by adjusting parameters such as pitch shift

        -

        How to Download and Install AV Music Morpher Gold 5.0.58 Serial Number Free 17

        - -

        Downloading and installing AV Music Morpher Gold 5.0.58 serial number free 17 is very easy and fast. You just need to follow these steps:

        - -
          -
        1. Click on the download link that you received in your email or go to the giveaway page and click on the download button.
        2. -
        3. Save the music_morpher_gold.exe file to your computer and run it.
        4. -
        5. Follow the installation wizard and accept the terms and conditions.
        6. -
        7. Choose the destination folder and click on the install button.
        8. -
        9. Wait for the installation to complete and click on the finish button.
        10. -
        - -

        You have successfully installed AV Music Morpher Gold 5.0.58 serial number free 17 on your computer. You can now launch the software and activate it with your name, email, and serial number.

        - -
        How to Use AV Music Morpher Gold 5.0.58 Serial Number Free 17 for Your Music Projects
        - -

        AV Music Morpher Gold 5.0.58 serial number free 17 is a versatile and powerful software that can help you with any music project you have in mind. Whether you want to edit, mix, remix, convert, record, or create music, you can do it with AV Music Morpher Gold 5.0.58 serial number free 17.

        - -

        Here are some of the things you can do with AV Music Morpher Gold 5.0.58 serial number free 17:

        - -
          -
        • You can edit any audio file with ease using the multi-track editor and recorder, the converter module, and the professional effects library.
        • -
        • You can create your own DJ mixes with the virtual DJ module that allows you to mix songs, adjust tempo and pitch, add sound effects, and more.
        • -
        • You can remove or extract vocals from any song using the patented vocal remover and extractor features that work with any audio format.
        • -
        • You can change your voice in real-time or offline using the voice changer module that offers hundreds of voice presets and effects.
        • -
        • You can make your own karaoke music videos using the video karaoke maker module that lets you import lyrics, synchronize them with music, add video effects, and more.
        • -
        • You can make your own ringtones using the ringtone maker module that lets you cut, edit, mix, and apply effects to any audio file.
        • -
        • You can play any media file with the media player module that supports audio/video effects and advanced features.
        • -
        - -

        To use any of these modules, you just need to choose them from the main interface of AV Music Morpher Gold 5.0.58 serial number free 17. Each module has its own toolbar and settings that you can customize according to your needs and preferences.

        - -

        For example, if you want to create a karaoke music video, you can choose the video karaoke maker module and click on the import button to load your music file and lyrics file. You can then synchronize them using the sync button or manually adjust them using the mouse or keyboard commands. You can also add video effects such as fade in/out, zoom in/out, rotate, etc., using the effects library or creating your own presets.

        - -

        If you want to change your voice, you can choose the voice changer module and load your voice file into the player or use a microphone to record your voice in real-time. You can then select a voice preset from hundreds of options such as male/female voices, animal voices, cartoon voices, etc., or create your own voice by adjusting parameters such as pitch shift -

        Conclusion
        - -

        AV Music Morpher Gold 5.0.58 serial number free 17 is a great opportunity for anyone who loves music and wants to create their own music projects. This software is a complete music solution that can help you with any audio editing and DJ tasks. You can edit, mix, remix, convert, record, or create music with ease and fun using AV Music Morpher Gold 5.0.58 serial number free 17.

        - -

        But hurry up, this offer is valid only until May 31, 2023 and the serial number is applicable from build 4.0.81. Don't miss this chance to get AV Music Morpher Gold 5.0.58 serial number free 17 and enjoy the ultimate music editor and DJ software.

        - -

        To get AV Music Morpher Gold 5.0.58 serial number free 17, just go to the giveaway page and enter your name and email address. You will receive an email with the activation code and the download link for AV Music Morpher Gold 5.0.58. Download and install the software on your computer and activate it with your name, email, and serial number. That's it, you are ready to use AV Music Morpher Gold 5.0.58 serial number free 17 for your music projects.

        - -

        So what are you waiting for? Get AV Music Morpher Gold 5.0.58 serial number free 17 now and unleash your creativity with music.

        3cee63e6c2
        -
        -
        \ No newline at end of file diff --git a/spaces/terfces0erbo/CollegeProjectV2/Blue Loong Joystick Driver Free TOP Download.md b/spaces/terfces0erbo/CollegeProjectV2/Blue Loong Joystick Driver Free TOP Download.md deleted file mode 100644 index 0298b7758c3698f1b9d6fea25410a61943ef8f88..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Blue Loong Joystick Driver Free TOP Download.md +++ /dev/null @@ -1,9 +0,0 @@ -
        -

        now that you have the blue loong joystick driver installed, you may use it to connect the device to your computer. please note that you may need to install a usb driver for your computer to recognize the blue loong joystick.

        -

        if you're using a usb gamepad, then you can download hid gamepad driver from our site to enable its use. if you are not sure of the driver version you are using, then you can find it in your device manager. you can find out more about usb drivers from the manufacturer's website.

        -

        Blue Loong Joystick Driver Free Download


        DOWNLOAD ✫✫✫ https://bytlly.com/2uGkxB



        -

        if you want to use a game controller on a mobile device, then you should download the app from the google play store or the app store. most android devices support game controllers, while ios devices do not. you can buy a game controller that plugs into the audio jack, as mentioned above. you will also need to find a set of peripherals to plug your game controller into. these are normally sold separately, so you will need to buy a usb port, and, if you want, a bluetooth dongle.

        -

        if you are using a bluetooth game controller, then you should download the driver from the manufacturer. as with usb game controllers, game controllers for bluetooth devices are not supported by the official android sdk, but you can find the drivers on the manufacturer's website. if you are using a wired game controller, then you can use the included usb-to-bluetooth adapter to connect it to your computer. you can download the driver from the manufacturer's website or from the google play store.

        -

        downloading the driver for a game controller is as simple as it gets. if you are using a bluetooth game controller, then you should download the driver from the manufacturer's website. as with usb game controllers, game controllers for bluetooth devices are not supported by the official android sdk, but you can find the drivers on the manufacturer's website. if you are using a wired game controller, then you can use the included usb-to-bluetooth adapter to connect it to your computer. you can download the driver from the manufacturer's website or from the google play store.

        899543212b
        -
        -
        \ No newline at end of file diff --git a/spaces/terfces0erbo/CollegeProjectV2/Inspyder-Web2disk-Free-Download-INSTALL-Full-Version.md b/spaces/terfces0erbo/CollegeProjectV2/Inspyder-Web2disk-Free-Download-INSTALL-Full-Version.md deleted file mode 100644 index 06c059f272f0125122d1bc14a93eb8e698c6b82a..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Inspyder-Web2disk-Free-Download-INSTALL-Full-Version.md +++ /dev/null @@ -1,104 +0,0 @@ -## Inspyder Web2disk Free Download Full Version - - - - - - ![Inspyder Web2disk Free Download ((INSTALL)) Full Version](https://video.findmysoft.com/2013/06/28/inspyder-web2disk.jpg) - - - - - -**Download File ⚡ [https://www.google.com/url?q=https%3A%2F%2Furllio.com%2F2tyCaQ&sa=D&sntz=1&usg=AOvVaw1U8hBwPkDX2wON9PjTgO51](https://www.google.com/url?q=https%3A%2F%2Furllio.com%2F2tyCaQ&sa=D&sntz=1&usg=AOvVaw1U8hBwPkDX2wON9PjTgO51)** - - - - - - - - - - - - - -# How to Download and Save Any Website with Inspyder Web2Disk - - - -If you want to download and save any website to your computer for offline browsing, you need a powerful and easy-to-use tool like Inspyder Web2Disk. Web2Disk is a website downloader that can download a complete website with all the files and links intact. You can then browse the downloaded website from your hard drive, CD, or USB drive without any special software or internet connection. - - - -In this article, we will show you how to use Web2Disk to download and save any website with just a few clicks. Whether you want to backup your own website, archive an online resource, or distribute a website on CD or USB drive, Web2Disk can help you do it quickly and efficiently. - - - -## What is Inspyder Web2Disk? - - - -Inspyder Web2Disk is a website downloader that lets you download and save any website to your computer. It works by crawling every part of a website and saving a copy to your PC. When Web2Disk is done, it automatically updates the downloaded website so that all the links work with the downloaded pages. You can browse the offline website in any browser as if it were still online. - - - -Web2Disk has many features and benefits that make it the best website downloader for offline browsing. Here are some of them: - - - -- Easy to use: Just enter a website URL and click Go! Web2Disk will do the rest. - -- Offline browsing: Web2Disk fixes downloaded websites for easy offline browsing. You can view them in any browser without internet connection. - -- Low cost: Web2Disk has a one-time cost ($39.95 per user-license), whether you download 20 pages or 20,000 pages. - -- Website backup: You can automatically save a snapshot of your website daily, weekly, or monthly. You can also get an email alert when a website is updated. - -- Website distribution: You can easily distribute your website on CD or USB drive without additional browser software. You can share an offline website with anyone. - - - -## How to Download and Save Any Website with Web2Disk? - - - -Downloading and saving any website with Web2Disk is very simple. Here are the steps you need to follow: - - - -1. Download and install Web2Disk from [https://www.inspyder.com/products/Web2Disk](https://www.inspyder.com/products/Web2Disk). You can try it for free for 30 days. - -2. Launch Web2Disk and enter the URL of the website you want to download in the Project URL box. You can also enter a name for your project in the Project Name box. - -3. Click on the Browse button next to the Save Folder box and choose a location on your computer where you want to save the downloaded website. - -4. Click on the Crawl tab and adjust the settings according to your preferences. You can limit the crawl by page depth or page count, exclude certain file types or domains, use a login wizard for password-protected websites, and more. - -5. Click on the Start button to begin downloading the website. You can see the progress of the download in the Status tab. - -6. When the download is complete, you can click on the Browse button next to the Save Folder box to open the downloaded website in your default browser. You can also use any other browser to view it offline. - - - -That's it! You have successfully downloaded and saved any website with Web2Disk. You can now enjoy offline browsing or distribute your website on CD or USB drive. - - - -## Conclusion - - - -Inspyder Web2Disk is a powerful and easy-to-use website downloader that can download and save any website to your computer for offline browsing. You can use it to backup your own website, archive an online resource, or distribute a website on CD or USB drive. It has many features and benefits that make it the best tool for offline browsing. - - - -If you want to try Web2Disk for free for 30 days, you can download it from [https://www.ins](https://www.inspyder.com/products/Web2Disk) - - 145887f19f - - - - - diff --git a/spaces/tether1/usdt/README.md b/spaces/tether1/usdt/README.md deleted file mode 100644 index 94b79986fcc9b54d99483b71920344c6fb9fb875..0000000000000000000000000000000000000000 --- a/spaces/tether1/usdt/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Usdt -emoji: 🚀 -colorFrom: pink -colorTo: gray -sdk: static -pinned: false -license: other ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Ek Tara Movie Download Kickass.md b/spaces/tialenAdioni/chat-gpt-api/logs/Ek Tara Movie Download Kickass.md deleted file mode 100644 index 82f44b1f4ef3c7d7c0155e8b4eb1ad2b42b2f32e..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Ek Tara Movie Download Kickass.md +++ /dev/null @@ -1,25 +0,0 @@ -
        -

        How to Download Ek Tara Movie from Kickass Torrents

        -

        Ek Tara is a 2014 Marathi musical drama film directed by Avadhoot Gupte and starring Santosh Juvekar, Tejaswini Pandit and Urmila Kanitkar. The film revolves around the life of a struggling singer who dreams of becoming a star. The film was praised for its music, direction and performances.

        -

        ek tara movie download kickass


        Download File ––– https://urlcod.com/2uKaC8



        -

        If you want to watch Ek Tara movie online or download it to your device, you can use Kickass Torrents, one of the most popular torrent sites in the world. Kickass Torrents allows you to download movies, TV shows, music, games and more for free. However, you need to be careful as downloading copyrighted content may be illegal in your country.

        -

        Here are the steps to download Ek Tara movie from Kickass Torrents:

        -
          -
        1. Visit the official website of Kickass Torrents or use a proxy or VPN service if the site is blocked in your region.
        2. -
        3. Search for "Ek Tara movie" in the search bar and click on the result that matches your preferences.
        4. -
        5. Check the file size, quality, seeders and leechers of the torrent file and make sure it is safe and reliable.
        6. -
        7. Download the torrent file or copy the magnet link and paste it into your torrent client.
        8. -
        9. Wait for the download to complete and enjoy watching Ek Tara movie.
        10. -
        -

        Note: You may need a media player that supports Marathi subtitles to watch Ek Tara movie.

        - -

        Ek Tara movie is based on the real-life story of Avadhoot Gupte, who is also the director and music composer of the film. Gupte was a singer who participated in a reality show called Sa Re Ga Ma Pa in 1998 and became famous. However, he faced many challenges and struggles in his career and personal life. He decided to make a film about his journey and inspire others who have similar dreams.

        -

        The film features 10 songs composed by Gupte and sung by various artists such as Shankar Mahadevan, Hariharan, Kunal Ganjawala and Bela Shende. The songs are a mix of different genres such as rock, folk, classical and rap. The songs are also integrated into the story and reflect the emotions and situations of the characters. The soundtrack of Ek Tara was well-received by the audience and critics alike.

        -

        Ek Tara movie was released on 16 January 2014 and received positive reviews from the critics and the audience. The film was praised for its realistic portrayal of the music industry, its engaging screenplay, its powerful dialogues and its brilliant performances by the lead actors. The film was also a commercial success and earned more than 10 crore rupees at the box office.

        -

        - -

        Ek Tara movie is not only a musical drama but also a social commentary on the issues faced by the aspiring artists in India. The film exposes the corruption, nepotism, exploitation and manipulation that exist in the music industry and how they affect the lives and careers of the talented singers. The film also shows the importance of having a strong support system, a positive attitude and a passion for one's art.

        -

        Ek Tara movie is a must-watch for anyone who loves music and movies. It is a film that will make you laugh, cry, sing and clap along with the characters. It is a film that will inspire you to follow your dreams and never give up. It is a film that will make you proud of being an Indian.

        -

        If you have not watched Ek Tara movie yet, you can download it from Kickass Torrents and enjoy it with your friends and family. But remember to be careful and responsible while using torrent sites and respect the rights of the creators.

        e93f5a0c3f
        -
        -
        \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Goldendict Android Full Cracked Apk The Fastest and Most Versatile Dictionary App on the Market.md b/spaces/tialenAdioni/chat-gpt-api/logs/Goldendict Android Full Cracked Apk The Fastest and Most Versatile Dictionary App on the Market.md deleted file mode 100644 index 35831744462814f7cfe84d707cd0495e1f83f391..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Goldendict Android Full Cracked Apk The Fastest and Most Versatile Dictionary App on the Market.md +++ /dev/null @@ -1,148 +0,0 @@ -
        -

        Goldendict Android Full Cracked Apk: The Ultimate Dictionary App

        -

        If you are looking for a powerful and versatile dictionary app for your Android device, you might want to check out Goldendict Android Full Cracked Apk. This app allows you to access multiple dictionaries from different sources and languages, and use them offline without any ads or limitations. In this article, we will tell you what Goldendict is, how to install it, why you should use it, how to use it, and what are some alternatives to it.

        -

        Goldendict Android Full Cracked Apk


        DOWNLOAD ……… https://urlcod.com/2uK50H



        -

        What is Goldendict?

        -

        Goldendict is an open-source dictionary program that supports a wide range of formats, such as Babylon (.bgl), StarDict (.ifo/.dict/.idx/.syn), Dictd (.index/.dict(.dz)), ABBYY Lingvo (.dsl/.lsa/.dat), and many others. You can also use online dictionaries, such as Wikipedia, Wiktionary, Google Translate, and others. You can download dictionaries from various websites or create your own using tools like PyGlossary.

        -

        Features of Goldendict

        -

        Some of the features of Goldendict are:

        -
          -
        • Supports multiple dictionary formats and online sources
        • -
        • Allows you to use dictionaries offline without any ads or limitations
        • -
        • Supports text-to-speech and pronunciation for many languages
        • -
        • Supports word scanning and pop-up translation from other apps
        • -
        • Supports wildcard search, fuzzy search, full-text search, and morphology analysis
        • -
        • Supports bookmarks, history, favorites, and custom labels
        • -
        • Supports dark mode, night mode, and color schemes
        • -
        • Supports gestures, keyboard shortcuts, and widgets
        • -
        • Supports backup and restore of settings and data
        • -
        -

        How to install Goldendict Android Full Cracked Apk

        -

        To install Goldendict Android Full Cracked Apk, you need to follow these steps:

        -
          -
        1. Download the apk file from a trusted source (such as https://apkdone.com/golden-dict-apk/)
        2. -
        3. Enable unknown sources on your device (go to Settings > Security > Unknown sources)
        4. -
        5. Locate the apk file on your device and tap on it to install it
        6. -
        7. Grant the necessary permissions to the app
        8. -
        9. Enjoy using Goldendict Android Full Cracked Apk
        10. -
        -

        Why use Goldendict Android Full Cracked Apk?

        -

        Benefits of using Goldendict Android Full Cracked Apk

        -

        Some of the benefits of using Goldendict Android Full Cracked Apk are:

        -
          -
        • You can access multiple dictionaries from different sources and languages in one app
        • -
        • You can use dictionaries offline without any ads or limitations
        • -
        • You can improve your vocabulary and pronunciation with text-to-speech and audio features
        • -
        • You can translate words and phrases from other apps with word scanning and pop-up translation features
        • -
        • You can find words easily with advanced search options and filters
        • -
        • You can organize your words with bookmarks, history, favorites, and labels
        • -
        • You can customize your app with dark mode, night mode, color schemes, gestures, shortcuts, and widgets
        • -
        • You can backup and restore your settings and data with ease
        • -
        -

        Drawbacks of using Goldendict Android Full Cracked Apk

        -

        Some of the drawbacks of using Goldendict Android Full Cracked Apk are:

        -
          -
        • You need to download dictionaries separately from different websites or sources
        • -
        • You need to enable unknown sources on your device to install the apk file
        • -
        • You may encounter some bugs or errors in the app or some dictionaries
        • -
        • You may not get updates or support from the official developers of the app or the dictionaries
        • -
        -

        How to use Goldendict Android Full Cracked Apk

        -

        How to add dictionaries to Goldendict Android Full Cracked Apk

        -

        To add dictionaries to Goldendict Android Full Cracked Apk, you need to follow these steps:

        -
          -
        1. Download the dictionary files from a trusted source (such as https://goldendict.mobi/dictionaries/)
        2. -
        3. Copy the dictionary files to your device's storage (preferably in a folder named "GoldenDict")
        4. -
        5. Open the app and go to Menu > Dictionaries > Add/Remove Dictionaries > Rescan
        6. -
        7. Select the dictionaries you want to use and tap on Save
        8. -
        9. Wait for the app to index the dictionaries
        10. -
        11. Enjoy using the dictionaries in the app
        12. -
        -

        How to search words in Goldendict Android Full Cracked Apk

        -

        To search words in Goldendict Android Full Cracked Apk, you need to follow these steps:

        -

        Goldendict pro apk free download for android
        -How to install goldendict full version on android
        -Goldendict offline dictionary app cracked apk
        -Goldendict premium apk mod unlocked all features
        -Best android app for goldendict dictionaries
        -Goldendict apk latest version download 2023
        -Goldendict plus apk no ads no root
        -Goldendict android app review and tutorial
        -Goldendict apk mirror direct link
        -Goldendict license key generator apk
        -Goldendict dictionary format converter apk
        -Goldendict android app alternatives and competitors
        -Goldendict apk file size and system requirements
        -Goldendict android app bugs and issues
        -Goldendict apk old versions archive
        -Goldendict android app tips and tricks
        -Goldendict apk modded by rexdl
        -Goldendict android app features and benefits
        -Goldendict apk hacked by lucky patcher
        -Goldendict android app support and feedback
        -Goldendict apk original from play store
        -Goldendict android app update and changelog
        -Goldendict apk cracked by revdl
        -Goldendict android app comparison with other dictionary apps
        -Goldendict apk patched by apk4free
        -Goldendict android app customization and settings
        -Goldendict apk unlocked by ac market
        -Goldendict android app performance and speed test
        -Goldendict apk full version by apkpure
        -Goldendict android app security and privacy
        -Goldendict apk cracked by moddroid
        -Goldendict android app languages and dictionaries support
        -Goldendict apk paid version by apkmody
        -Goldendict android app user ratings and reviews
        -Goldendict apk cracked by happymod
        -Goldendict android app integration with other apps
        -Goldendict apk premium version by apkmirror
        -Goldendict android app screenshots and videos
        -Goldendict apk cracked by an1.com
        -Goldendict android app development and history
        -Goldendict apk full version by apknite
        -Goldendict android app faq and help guide
        -Goldendict apk cracked by mob.org
        -Goldendict android app discount and coupon code
        -Goldendict apk full version by uptodown
        -Goldendict android app awards and recognition
        -Goldendict apk cracked by apksfull.com
        -Goldendict android app donation and contribution
        -Goldendict apk full version by apkmaza

        -
          -
        1. Open the app and tap on the search bar at the top
        2. -
        3. Type or paste the word or phrase you want to look up
        4. -
        5. Select the dictionary or source you want to use from the drop-down menu
        6. -
        7. Tap on the search icon or press enter
        8. -
        9. View the results in different tabs (Articles, Translations, Web pages)
        10. -
        11. Tap on any word or phrase in the results to see more details or translations
        12. -
        13. Tap on the speaker icon or press volume keys to hear the pronunciation
        14. -
        15. Tap on the star icon or press menu key to add the word or phrase to favorites
        16. -
        17. Tap on the label icon or press menu key to add a custom label to the word or phrase
        18. -
        19. Tap on the share icon or press menu key to share the word or phrase with other apps
        20. -
        -

        How to customize settings in Goldendict Android Full Cracked Apk

        -

        To customize settings in Goldendict Android Full Cracked Apk, you need to follow these steps:

        -
          -
        1. Open the app and go to Menu > Settings
        2. -
        3. Select the category you want to change (General, Interface, Article view, Popup view)
        4. Tweak the options according to your preferences (such as language, font size, color scheme, night mode)
        5. Tap on Save when done

        Dictionary.com: Find Definitions for English Words

        -

        Dictionary.com: Find Definitions for English Words is a dictionary app that offers access to over 2 million definitions, synonyms, antonyms, and idioms for English words. You can also use online dictionaries such as Thesaurus.com, SpanishDict.com, and Dictionary.com Translator. You can also use text-to-speech and audio features for many words. You can also scan words from other apps with their word of the day feature.

        -

        Conclusion

        -

        In conclusion, Goldendict Android Full Cracked Apk is a great dictionary app that allows you to access multiple dictionaries from different sources and languages, and use them offline without any ads or limitations. It has many features that can help you improve your vocabulary and pronunciation, translate words and phrases from other apps, find words easily with advanced search options and filters, organize your words with bookmarks, history, favorites, and labels, customize your app with dark mode, night mode, color schemes, gestures, shortcuts, and widgets, and backup and restore your settings and data with ease. However, it also has some drawbacks, such as the need to download dictionaries separately from different websites or sources, the need to enable unknown sources on your device to install the apk file, the possibility of encountering some bugs or errors in the app or some dictionaries, and the lack of updates or support from the official developers of the app or the dictionaries. If you are not satisfied with Goldendict Android Full Cracked Apk, or you want to try some other dictionary apps, you can check out some alternatives to it, such as ABBYY Lingvo Dictionaries, Dict Box - Universal Offline Dictionary, and Dictionary.com: Find Definitions for English Words.

        -

        FAQs

        -

        Here are some frequently asked questions about Goldendict Android Full Cracked Apk:

        -
          -
        1. What is the difference between Goldendict Android Full Cracked Apk and Goldendict Android Free Version?
        2. -

          The main difference between Goldendict Android Full Cracked Apk and Goldendict Android Free Version is that the former allows you to use dictionaries offline without any ads or limitations, while the latter requires an internet connection and displays ads in the app.

          -
        3. Where can I download Goldendict Android Full Cracked Apk?
        4. -

          You can download Goldendict Android Full Cracked Apk from a trusted source (such as https://apkdone.com/golden-dict-apk/). However, you need to enable unknown sources on your device to install it.

          -
        5. Where can I download dictionaries for Goldendict Android Full Cracked Apk?
        6. -

          You can download dictionaries for Goldendict Android Full Cracked Apk from various websites or sources (such as https://goldendict.mobi/dictionaries/). However, you need to copy them to your device's storage (preferably in a folder named "GoldenDict") and rescan them in the app.

          -
        7. How can I update Goldendict Android Full Cracked Apk?
        8. -

          You can update Goldendict Android Full Cracked Apk by downloading the latest version of the apk file from a trusted source (such as https://apkdone.com/golden-dict-apk/) and installing it over the existing one. However, you may lose some settings or data in the process.

          -
        9. How can I contact the developers of Goldendict Android Full Cracked Apk?
        10. -

          You can contact the developers of Goldendict Android Full Cracked Apk by visiting their official website (https://goldendict.org/) or their GitHub page (https://github.com/goldendict/goldendict). However, you may not get a response or support from them.

          -
        -

        0a6ba089eb
        -
        -
        \ No newline at end of file diff --git a/spaces/tioseFevbu/cartoon-converter/scripts/Adobe Acrobat X Pro Lite Portable (v10.0.2).md b/spaces/tioseFevbu/cartoon-converter/scripts/Adobe Acrobat X Pro Lite Portable (v10.0.2).md deleted file mode 100644 index bc426eafc245de3ab5318f4dfe7dadf7936306d7..0000000000000000000000000000000000000000 --- a/spaces/tioseFevbu/cartoon-converter/scripts/Adobe Acrobat X Pro Lite Portable (v10.0.2).md +++ /dev/null @@ -1,40 +0,0 @@ -
        -Here is a possible title and article with html formatting for the keyword "Adobe Acrobat X Pro Lite Portable (v10.0.2)": - -

        How to Use Adobe Acrobat X Pro Lite Portable (v10.0.2) to View, Edit and Create PDF Files

        -

        Adobe Acrobat X Pro Lite Portable (v10.0.2) is a freeware software that allows you to open, view, edit and create PDF documents without installing anything on your system. It is a lightweight version of Adobe Acrobat X Pro that can run from a USB flash drive or any other portable device. In this article, we will show you how to use this software to perform some common tasks with PDF files.

        -

        How to Open and View PDF Files

        -

        To open and view a PDF file with Adobe Acrobat X Pro Lite Portable (v10.0.2), you need to follow these steps:

        -

        Adobe Acrobat X Pro Lite Portable (v10.0.2)


        Download Filehttps://urlcod.com/2uHyJI



        -
          -
        1. Download the software from this link [^1^] and extract the zip file to your portable device.
        2. -
        3. Go to your portable device and open the folder where you extracted the software.
        4. -
        5. Double-click on the Start.exe file to launch the software.
        6. -
        7. You will see a blank screen with a menu bar at the top. Click on File > Open and browse to the location of your PDF file.
        8. -
        9. Select your PDF file and click Open. The software will display the PDF file in its interface.
        10. -
        11. You can use the toolbar buttons or the menu options to zoom in or out, rotate, print, save or close the PDF file.
        12. -
        -

        How to Edit PDF Files

        -

        To edit a PDF file with Adobe Acrobat X Pro Lite Portable (v10.0.2), you need to follow these steps:

        -
          -
        1. Open the PDF file that you want to edit as described above.
        2. -
        3. Click on Tools > Advanced Editing > TouchUp Text Tool. This will allow you to select and modify the text in the PDF file.
        4. -
        5. Click on the text that you want to edit and make the changes as you wish. You can use the toolbar buttons or the menu options to change the font, size, color, alignment or style of the text.
        6. -
        7. If you want to add new text, click on Tools > Advanced Editing > TouchUp Text Tool again and then click on an empty area in the PDF file where you want to insert the text. A cursor will appear and you can type your text as usual.
        8. -
        9. If you want to delete some text, select it with the TouchUp Text Tool and press Delete on your keyboard.
        10. -
        11. If you want to move some text, select it with the TouchUp Text Tool and drag it to a new location.
        12. -
        13. If you want to resize some text, select it with the TouchUp Text Tool and drag one of its corners.
        14. -
        15. If you want to edit an image in the PDF file, click on Tools > Advanced Editing > TouchUp Object Tool. This will allow you to select and modify the images in the PDF file.
        16. -
        17. Click on the image that you want to edit and use the toolbar buttons or the menu options to crop, rotate, flip, replace or delete the image.
        18. -
        19. If you want to add a new image, click on Tools > Advanced Editing > TouchUp Object Tool again and then click on an empty area in the PDF file where you want to insert the image. A dialog box will appear and you can browse to the location of your image file.
        20. -
        21. Select your image file and click Open. The software will insert the image in the PDF file.
        22. -
        23. If you want to move or resize an image, select it with the TouchUp Object Tool and drag it or its corners as desired.
        24. -
        -

        How to Create PDF Files

        -

        To create a PDF file with Adobe Acrobat X Pro Lite Portable (v10.0.2), you need to follow these steps:

        -
          -
        1. Open any document that you want to convert to PDF with its original application (e.g., Word, Excel, PowerPoint, etc.).
        2. -
        3. Click on File > Print and choose Adobe PDF as your printer.
        4. -
        5. Click on Properties and

          7196e7f11a
          -
          -
          \ No newline at end of file diff --git a/spaces/tomofi/MMOCR/mmocr/models/textdet/necks/__init__.py b/spaces/tomofi/MMOCR/mmocr/models/textdet/necks/__init__.py deleted file mode 100644 index 0b21bf192b93f8a09278989837f8b9b762052f7e..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/models/textdet/necks/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .fpem_ffm import FPEM_FFM -from .fpn_cat import FPNC -from .fpn_unet import FPN_UNet -from .fpnf import FPNF - -__all__ = ['FPEM_FFM', 'FPNF', 'FPNC', 'FPN_UNet'] diff --git a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/layers/__init__.py b/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/layers/__init__.py deleted file mode 100644 index 420bc1d2c4f9d93bf72388f7be2bd4d557e6c26b..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/layers/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -import torch - -from .batch_norm import FrozenBatchNorm2d -from .misc import Conv2d -from .misc import DFConv2d -from .misc import ConvTranspose2d -from .misc import interpolate -from .nms import nms -from .roi_align import ROIAlign -from .roi_align import roi_align -from .roi_pool import ROIPool -from .roi_pool import roi_pool -from .smooth_l1_loss import smooth_l1_loss -from .dcn.deform_conv_func import deform_conv, modulated_deform_conv -from .dcn.deform_conv_module import DeformConv, ModulatedDeformConv, ModulatedDeformConvPack -from .dcn.deform_pool_func import deform_roi_pooling -from .dcn.deform_pool_module import DeformRoIPooling, DeformRoIPoolingPack, ModulatedDeformRoIPoolingPack -__all__ = [ - "nms", - "roi_align", - "ROIAlign", - "roi_pool", - "ROIPool", - "smooth_l1_loss", - "Conv2d", - "DFConv2d", - "ConvTranspose2d", - "interpolate", - "BatchNorm2d", - "FrozenBatchNorm2d", - 'deform_conv', - 'modulated_deform_conv', - 'DeformConv', - 'ModulatedDeformConv', - 'ModulatedDeformConvPack', - 'deform_roi_pooling', - 'DeformRoIPooling', - 'DeformRoIPoolingPack', - 'ModulatedDeformRoIPoolingPack', -] -# __all__ = ["nms", "roi_align", "ROIAlign", "roi_pool", "ROIPool", "smooth_l1_loss", "Conv2d", "ConvTranspose2d", "interpolate", "FrozenBatchNorm2d"] diff --git a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/structures/__init__.py b/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/structures/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/carafe/README.md b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/carafe/README.md deleted file mode 100644 index ce3b862ee78454a3746a1cab661460d5b7f16c8e..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/carafe/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# CARAFE: Content-Aware ReAssembly of FEatures - -## Introduction - - - -We provide config files to reproduce the object detection & instance segmentation results in the ICCV 2019 Oral paper for [CARAFE: Content-Aware ReAssembly of FEatures](https://arxiv.org/abs/1905.02188). - -``` -@inproceedings{Wang_2019_ICCV, - title = {CARAFE: Content-Aware ReAssembly of FEatures}, - author = {Wang, Jiaqi and Chen, Kai and Xu, Rui and Liu, Ziwei and Loy, Chen Change and Lin, Dahua}, - booktitle = {The IEEE International Conference on Computer Vision (ICCV)}, - month = {October}, - year = {2019} -} -``` - -## Results and Models - -The results on COCO 2017 val is shown in the below table. - -| Method | Backbone | Style | Lr schd | Test Proposal Num | Inf time (fps) | Box AP | Mask AP | Config | Download | -|:--------------------:|:--------:|:-------:|:-------:|:-----------------:|:--------------:|:------:|:-------:|:------:|:--------:| -| Faster R-CNN w/ CARAFE | R-50-FPN | pytorch | 1x | 1000 | 16.5 | 38.6 | 38.6 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/carafe/faster_rcnn_r50_fpn_carafe_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/carafe/faster_rcnn_r50_fpn_carafe_1x_coco/faster_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.386_20200504_175733-385a75b7.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/carafe/faster_rcnn_r50_fpn_carafe_1x_coco/faster_rcnn_r50_fpn_carafe_1x_coco_20200504_175733.log.json) | -| - | - | - | - | 2000 | | | | | -| Mask R-CNN w/ CARAFE | R-50-FPN | pytorch | 1x | 1000 | 14.0 | 39.3 | 35.8 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/carafe/mask_rcnn_r50_fpn_carafe_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/carafe/mask_rcnn_r50_fpn_carafe_1x_coco/mask_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.393__segm_mAP-0.358_20200503_135957-8687f195.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/carafe/mask_rcnn_r50_fpn_carafe_1x_coco/mask_rcnn_r50_fpn_carafe_1x_coco_20200503_135957.log.json) | -| - | - | - | - | 2000 | | | | | - -## Implementation - -The CUDA implementation of CARAFE can be find at https://github.com/myownskyW7/CARAFE. diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/ms_rcnn/README.md b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/ms_rcnn/README.md deleted file mode 100644 index 76f5af3b8dcbcbeef082df3bfbaf4ea8c9ff1be0..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/ms_rcnn/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Mask Scoring R-CNN - -## Introduction - - - -``` -@inproceedings{huang2019msrcnn, - title={Mask Scoring R-CNN}, - author={Zhaojin Huang and Lichao Huang and Yongchao Gong and Chang Huang and Xinggang Wang}, - booktitle={IEEE Conference on Computer Vision and Pattern Recognition}, - year={2019}, -} -``` - -## Results and Models - -| Backbone | style | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | -|:-------------:|:----------:|:-------:|:--------:|:--------------:|:------:|:-------:|:------:|:--------:| -| R-50-FPN | caffe | 1x | 4.5 | | 38.2 | 36.0 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_r50_caffe_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r50_caffe_fpn_1x_coco/ms_rcnn_r50_caffe_fpn_1x_coco_20200702_180848-61c9355e.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r50_caffe_fpn_1x_coco/ms_rcnn_r50_caffe_fpn_1x_coco_20200702_180848.log.json) | -| R-50-FPN | caffe | 2x | - | - | 38.8 | 36.3 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_r50_caffe_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r50_caffe_fpn_2x_coco/ms_rcnn_r50_caffe_fpn_2x_coco_bbox_mAP-0.388__segm_mAP-0.363_20200506_004738-ee87b137.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r50_caffe_fpn_2x_coco/ms_rcnn_r50_caffe_fpn_2x_coco_20200506_004738.log.json) | -| R-101-FPN | caffe | 1x | 6.5 | | 40.4 | 37.6 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco/ms_rcnn_r101_caffe_fpn_1x_coco_bbox_mAP-0.404__segm_mAP-0.376_20200506_004755-b9b12a37.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco/ms_rcnn_r101_caffe_fpn_1x_coco_20200506_004755.log.json) | -| R-101-FPN | caffe | 2x | - | - | 41.1 | 38.1 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco/ms_rcnn_r101_caffe_fpn_2x_coco_bbox_mAP-0.411__segm_mAP-0.381_20200506_011134-5f3cc74f.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco/ms_rcnn_r101_caffe_fpn_2x_coco_20200506_011134.log.json) | -| R-X101-32x4d | pytorch | 2x | 7.9 | 11.0 | 41.8 | 38.7 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco/ms_rcnn_x101_32x4d_fpn_1x_coco_20200206-81fd1740.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco/ms_rcnn_x101_32x4d_fpn_1x_coco_20200206_100113.log.json) | -| R-X101-64x4d | pytorch | 1x | 11.0 | 8.0 | 43.0 | 39.5 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco/ms_rcnn_x101_64x4d_fpn_1x_coco_20200206-86ba88d2.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco/ms_rcnn_x101_64x4d_fpn_1x_coco_20200206_091744.log.json) | -| R-X101-64x4d | pytorch | 2x | 11.0 | 8.0 | 42.6 | 39.5 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/ms_rcnn/ms_rcnn_x101_64x4d_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_64x4d_fpn_2x_coco/ms_rcnn_x101_64x4d_fpn_2x_coco_20200308-02a445e2.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/ms_rcnn/ms_rcnn_x101_64x4d_fpn_2x_coco/ms_rcnn_x101_64x4d_fpn_2x_coco_20200308_012247.log.json) | diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/core/evaluation/mean_ap.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/core/evaluation/mean_ap.py deleted file mode 100644 index 1d653a35497f6a0135c4374a09eb7c11399e3244..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/core/evaluation/mean_ap.py +++ /dev/null @@ -1,469 +0,0 @@ -from multiprocessing import Pool - -import mmcv -import numpy as np -from mmcv.utils import print_log -from terminaltables import AsciiTable - -from .bbox_overlaps import bbox_overlaps -from .class_names import get_classes - - -def average_precision(recalls, precisions, mode='area'): - """Calculate average precision (for single or multiple scales). - - Args: - recalls (ndarray): shape (num_scales, num_dets) or (num_dets, ) - precisions (ndarray): shape (num_scales, num_dets) or (num_dets, ) - mode (str): 'area' or '11points', 'area' means calculating the area - under precision-recall curve, '11points' means calculating - the average precision of recalls at [0, 0.1, ..., 1] - - Returns: - float or ndarray: calculated average precision - """ - no_scale = False - if recalls.ndim == 1: - no_scale = True - recalls = recalls[np.newaxis, :] - precisions = precisions[np.newaxis, :] - assert recalls.shape == precisions.shape and recalls.ndim == 2 - num_scales = recalls.shape[0] - ap = np.zeros(num_scales, dtype=np.float32) - if mode == 'area': - zeros = np.zeros((num_scales, 1), dtype=recalls.dtype) - ones = np.ones((num_scales, 1), dtype=recalls.dtype) - mrec = np.hstack((zeros, recalls, ones)) - mpre = np.hstack((zeros, precisions, zeros)) - for i in range(mpre.shape[1] - 1, 0, -1): - mpre[:, i - 1] = np.maximum(mpre[:, i - 1], mpre[:, i]) - for i in range(num_scales): - ind = np.where(mrec[i, 1:] != mrec[i, :-1])[0] - ap[i] = np.sum( - (mrec[i, ind + 1] - mrec[i, ind]) * mpre[i, ind + 1]) - elif mode == '11points': - for i in range(num_scales): - for thr in np.arange(0, 1 + 1e-3, 0.1): - precs = precisions[i, recalls[i, :] >= thr] - prec = precs.max() if precs.size > 0 else 0 - ap[i] += prec - ap /= 11 - else: - raise ValueError( - 'Unrecognized mode, only "area" and "11points" are supported') - if no_scale: - ap = ap[0] - return ap - - -def tpfp_imagenet(det_bboxes, - gt_bboxes, - gt_bboxes_ignore=None, - default_iou_thr=0.5, - area_ranges=None): - """Check if detected bboxes are true positive or false positive. - - Args: - det_bbox (ndarray): Detected bboxes of this image, of shape (m, 5). - gt_bboxes (ndarray): GT bboxes of this image, of shape (n, 4). - gt_bboxes_ignore (ndarray): Ignored gt bboxes of this image, - of shape (k, 4). Default: None - default_iou_thr (float): IoU threshold to be considered as matched for - medium and large bboxes (small ones have special rules). - Default: 0.5. - area_ranges (list[tuple] | None): Range of bbox areas to be evaluated, - in the format [(min1, max1), (min2, max2), ...]. Default: None. - - Returns: - tuple[np.ndarray]: (tp, fp) whose elements are 0 and 1. The shape of - each array is (num_scales, m). - """ - # an indicator of ignored gts - gt_ignore_inds = np.concatenate( - (np.zeros(gt_bboxes.shape[0], dtype=np.bool), - np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool))) - # stack gt_bboxes and gt_bboxes_ignore for convenience - gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore)) - - num_dets = det_bboxes.shape[0] - num_gts = gt_bboxes.shape[0] - if area_ranges is None: - area_ranges = [(None, None)] - num_scales = len(area_ranges) - # tp and fp are of shape (num_scales, num_gts), each row is tp or fp - # of a certain scale. - tp = np.zeros((num_scales, num_dets), dtype=np.float32) - fp = np.zeros((num_scales, num_dets), dtype=np.float32) - if gt_bboxes.shape[0] == 0: - if area_ranges == [(None, None)]: - fp[...] = 1 - else: - det_areas = (det_bboxes[:, 2] - det_bboxes[:, 0]) * ( - det_bboxes[:, 3] - det_bboxes[:, 1]) - for i, (min_area, max_area) in enumerate(area_ranges): - fp[i, (det_areas >= min_area) & (det_areas < max_area)] = 1 - return tp, fp - ious = bbox_overlaps(det_bboxes, gt_bboxes - 1) - gt_w = gt_bboxes[:, 2] - gt_bboxes[:, 0] - gt_h = gt_bboxes[:, 3] - gt_bboxes[:, 1] - iou_thrs = np.minimum((gt_w * gt_h) / ((gt_w + 10.0) * (gt_h + 10.0)), - default_iou_thr) - # sort all detections by scores in descending order - sort_inds = np.argsort(-det_bboxes[:, -1]) - for k, (min_area, max_area) in enumerate(area_ranges): - gt_covered = np.zeros(num_gts, dtype=bool) - # if no area range is specified, gt_area_ignore is all False - if min_area is None: - gt_area_ignore = np.zeros_like(gt_ignore_inds, dtype=bool) - else: - gt_areas = gt_w * gt_h - gt_area_ignore = (gt_areas < min_area) | (gt_areas >= max_area) - for i in sort_inds: - max_iou = -1 - matched_gt = -1 - # find best overlapped available gt - for j in range(num_gts): - # different from PASCAL VOC: allow finding other gts if the - # best overlapped ones are already matched by other det bboxes - if gt_covered[j]: - continue - elif ious[i, j] >= iou_thrs[j] and ious[i, j] > max_iou: - max_iou = ious[i, j] - matched_gt = j - # there are 4 cases for a det bbox: - # 1. it matches a gt, tp = 1, fp = 0 - # 2. it matches an ignored gt, tp = 0, fp = 0 - # 3. it matches no gt and within area range, tp = 0, fp = 1 - # 4. it matches no gt but is beyond area range, tp = 0, fp = 0 - if matched_gt >= 0: - gt_covered[matched_gt] = 1 - if not (gt_ignore_inds[matched_gt] - or gt_area_ignore[matched_gt]): - tp[k, i] = 1 - elif min_area is None: - fp[k, i] = 1 - else: - bbox = det_bboxes[i, :4] - area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) - if area >= min_area and area < max_area: - fp[k, i] = 1 - return tp, fp - - -def tpfp_default(det_bboxes, - gt_bboxes, - gt_bboxes_ignore=None, - iou_thr=0.5, - area_ranges=None): - """Check if detected bboxes are true positive or false positive. - - Args: - det_bbox (ndarray): Detected bboxes of this image, of shape (m, 5). - gt_bboxes (ndarray): GT bboxes of this image, of shape (n, 4). - gt_bboxes_ignore (ndarray): Ignored gt bboxes of this image, - of shape (k, 4). Default: None - iou_thr (float): IoU threshold to be considered as matched. - Default: 0.5. - area_ranges (list[tuple] | None): Range of bbox areas to be evaluated, - in the format [(min1, max1), (min2, max2), ...]. Default: None. - - Returns: - tuple[np.ndarray]: (tp, fp) whose elements are 0 and 1. The shape of - each array is (num_scales, m). - """ - # an indicator of ignored gts - gt_ignore_inds = np.concatenate( - (np.zeros(gt_bboxes.shape[0], dtype=np.bool), - np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool))) - # stack gt_bboxes and gt_bboxes_ignore for convenience - gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore)) - - num_dets = det_bboxes.shape[0] - num_gts = gt_bboxes.shape[0] - if area_ranges is None: - area_ranges = [(None, None)] - num_scales = len(area_ranges) - # tp and fp are of shape (num_scales, num_gts), each row is tp or fp of - # a certain scale - tp = np.zeros((num_scales, num_dets), dtype=np.float32) - fp = np.zeros((num_scales, num_dets), dtype=np.float32) - - # if there is no gt bboxes in this image, then all det bboxes - # within area range are false positives - if gt_bboxes.shape[0] == 0: - if area_ranges == [(None, None)]: - fp[...] = 1 - else: - det_areas = (det_bboxes[:, 2] - det_bboxes[:, 0]) * ( - det_bboxes[:, 3] - det_bboxes[:, 1]) - for i, (min_area, max_area) in enumerate(area_ranges): - fp[i, (det_areas >= min_area) & (det_areas < max_area)] = 1 - return tp, fp - - ious = bbox_overlaps(det_bboxes, gt_bboxes) - # for each det, the max iou with all gts - ious_max = ious.max(axis=1) - # for each det, which gt overlaps most with it - ious_argmax = ious.argmax(axis=1) - # sort all dets in descending order by scores - sort_inds = np.argsort(-det_bboxes[:, -1]) - for k, (min_area, max_area) in enumerate(area_ranges): - gt_covered = np.zeros(num_gts, dtype=bool) - # if no area range is specified, gt_area_ignore is all False - if min_area is None: - gt_area_ignore = np.zeros_like(gt_ignore_inds, dtype=bool) - else: - gt_areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0]) * ( - gt_bboxes[:, 3] - gt_bboxes[:, 1]) - gt_area_ignore = (gt_areas < min_area) | (gt_areas >= max_area) - for i in sort_inds: - if ious_max[i] >= iou_thr: - matched_gt = ious_argmax[i] - if not (gt_ignore_inds[matched_gt] - or gt_area_ignore[matched_gt]): - if not gt_covered[matched_gt]: - gt_covered[matched_gt] = True - tp[k, i] = 1 - else: - fp[k, i] = 1 - # otherwise ignore this detected bbox, tp = 0, fp = 0 - elif min_area is None: - fp[k, i] = 1 - else: - bbox = det_bboxes[i, :4] - area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) - if area >= min_area and area < max_area: - fp[k, i] = 1 - return tp, fp - - -def get_cls_results(det_results, annotations, class_id): - """Get det results and gt information of a certain class. - - Args: - det_results (list[list]): Same as `eval_map()`. - annotations (list[dict]): Same as `eval_map()`. - class_id (int): ID of a specific class. - - Returns: - tuple[list[np.ndarray]]: detected bboxes, gt bboxes, ignored gt bboxes - """ - cls_dets = [img_res[class_id] for img_res in det_results] - cls_gts = [] - cls_gts_ignore = [] - for ann in annotations: - gt_inds = ann['labels'] == class_id - cls_gts.append(ann['bboxes'][gt_inds, :]) - - if ann.get('labels_ignore', None) is not None: - ignore_inds = ann['labels_ignore'] == class_id - cls_gts_ignore.append(ann['bboxes_ignore'][ignore_inds, :]) - else: - cls_gts_ignore.append(np.empty((0, 4), dtype=np.float32)) - - return cls_dets, cls_gts, cls_gts_ignore - - -def eval_map(det_results, - annotations, - scale_ranges=None, - iou_thr=0.5, - dataset=None, - logger=None, - tpfp_fn=None, - nproc=4): - """Evaluate mAP of a dataset. - - Args: - det_results (list[list]): [[cls1_det, cls2_det, ...], ...]. - The outer list indicates images, and the inner list indicates - per-class detected bboxes. - annotations (list[dict]): Ground truth annotations where each item of - the list indicates an image. Keys of annotations are: - - - `bboxes`: numpy array of shape (n, 4) - - `labels`: numpy array of shape (n, ) - - `bboxes_ignore` (optional): numpy array of shape (k, 4) - - `labels_ignore` (optional): numpy array of shape (k, ) - scale_ranges (list[tuple] | None): Range of scales to be evaluated, - in the format [(min1, max1), (min2, max2), ...]. A range of - (32, 64) means the area range between (32**2, 64**2). - Default: None. - iou_thr (float): IoU threshold to be considered as matched. - Default: 0.5. - dataset (list[str] | str | None): Dataset name or dataset classes, - there are minor differences in metrics for different datsets, e.g. - "voc07", "imagenet_det", etc. Default: None. - logger (logging.Logger | str | None): The way to print the mAP - summary. See `mmcv.utils.print_log()` for details. Default: None. - tpfp_fn (callable | None): The function used to determine true/ - false positives. If None, :func:`tpfp_default` is used as default - unless dataset is 'det' or 'vid' (:func:`tpfp_imagenet` in this - case). If it is given as a function, then this function is used - to evaluate tp & fp. Default None. - nproc (int): Processes used for computing TP and FP. - Default: 4. - - Returns: - tuple: (mAP, [dict, dict, ...]) - """ - assert len(det_results) == len(annotations) - - num_imgs = len(det_results) - num_scales = len(scale_ranges) if scale_ranges is not None else 1 - num_classes = len(det_results[0]) # positive class num - area_ranges = ([(rg[0]**2, rg[1]**2) for rg in scale_ranges] - if scale_ranges is not None else None) - - pool = Pool(nproc) - eval_results = [] - for i in range(num_classes): - # get gt and det bboxes of this class - cls_dets, cls_gts, cls_gts_ignore = get_cls_results( - det_results, annotations, i) - # choose proper function according to datasets to compute tp and fp - if tpfp_fn is None: - if dataset in ['det', 'vid']: - tpfp_fn = tpfp_imagenet - else: - tpfp_fn = tpfp_default - if not callable(tpfp_fn): - raise ValueError( - f'tpfp_fn has to be a function or None, but got {tpfp_fn}') - - # compute tp and fp for each image with multiple processes - tpfp = pool.starmap( - tpfp_fn, - zip(cls_dets, cls_gts, cls_gts_ignore, - [iou_thr for _ in range(num_imgs)], - [area_ranges for _ in range(num_imgs)])) - tp, fp = tuple(zip(*tpfp)) - # calculate gt number of each scale - # ignored gts or gts beyond the specific scale are not counted - num_gts = np.zeros(num_scales, dtype=int) - for j, bbox in enumerate(cls_gts): - if area_ranges is None: - num_gts[0] += bbox.shape[0] - else: - gt_areas = (bbox[:, 2] - bbox[:, 0]) * ( - bbox[:, 3] - bbox[:, 1]) - for k, (min_area, max_area) in enumerate(area_ranges): - num_gts[k] += np.sum((gt_areas >= min_area) - & (gt_areas < max_area)) - # sort all det bboxes by score, also sort tp and fp - cls_dets = np.vstack(cls_dets) - num_dets = cls_dets.shape[0] - sort_inds = np.argsort(-cls_dets[:, -1]) - tp = np.hstack(tp)[:, sort_inds] - fp = np.hstack(fp)[:, sort_inds] - # calculate recall and precision with tp and fp - tp = np.cumsum(tp, axis=1) - fp = np.cumsum(fp, axis=1) - eps = np.finfo(np.float32).eps - recalls = tp / np.maximum(num_gts[:, np.newaxis], eps) - precisions = tp / np.maximum((tp + fp), eps) - # calculate AP - if scale_ranges is None: - recalls = recalls[0, :] - precisions = precisions[0, :] - num_gts = num_gts.item() - mode = 'area' if dataset != 'voc07' else '11points' - ap = average_precision(recalls, precisions, mode) - eval_results.append({ - 'num_gts': num_gts, - 'num_dets': num_dets, - 'recall': recalls, - 'precision': precisions, - 'ap': ap - }) - pool.close() - if scale_ranges is not None: - # shape (num_classes, num_scales) - all_ap = np.vstack([cls_result['ap'] for cls_result in eval_results]) - all_num_gts = np.vstack( - [cls_result['num_gts'] for cls_result in eval_results]) - mean_ap = [] - for i in range(num_scales): - if np.any(all_num_gts[:, i] > 0): - mean_ap.append(all_ap[all_num_gts[:, i] > 0, i].mean()) - else: - mean_ap.append(0.0) - else: - aps = [] - for cls_result in eval_results: - if cls_result['num_gts'] > 0: - aps.append(cls_result['ap']) - mean_ap = np.array(aps).mean().item() if aps else 0.0 - - print_map_summary( - mean_ap, eval_results, dataset, area_ranges, logger=logger) - - return mean_ap, eval_results - - -def print_map_summary(mean_ap, - results, - dataset=None, - scale_ranges=None, - logger=None): - """Print mAP and results of each class. - - A table will be printed to show the gts/dets/recall/AP of each class and - the mAP. - - Args: - mean_ap (float): Calculated from `eval_map()`. - results (list[dict]): Calculated from `eval_map()`. - dataset (list[str] | str | None): Dataset name or dataset classes. - scale_ranges (list[tuple] | None): Range of scales to be evaluated. - logger (logging.Logger | str | None): The way to print the mAP - summary. See `mmcv.utils.print_log()` for details. Default: None. - """ - - if logger == 'silent': - return - - if isinstance(results[0]['ap'], np.ndarray): - num_scales = len(results[0]['ap']) - else: - num_scales = 1 - - if scale_ranges is not None: - assert len(scale_ranges) == num_scales - - num_classes = len(results) - - recalls = np.zeros((num_scales, num_classes), dtype=np.float32) - aps = np.zeros((num_scales, num_classes), dtype=np.float32) - num_gts = np.zeros((num_scales, num_classes), dtype=int) - for i, cls_result in enumerate(results): - if cls_result['recall'].size > 0: - recalls[:, i] = np.array(cls_result['recall'], ndmin=2)[:, -1] - aps[:, i] = cls_result['ap'] - num_gts[:, i] = cls_result['num_gts'] - - if dataset is None: - label_names = [str(i) for i in range(num_classes)] - elif mmcv.is_str(dataset): - label_names = get_classes(dataset) - else: - label_names = dataset - - if not isinstance(mean_ap, list): - mean_ap = [mean_ap] - - header = ['class', 'gts', 'dets', 'recall', 'ap'] - for i in range(num_scales): - if scale_ranges is not None: - print_log(f'Scale range {scale_ranges[i]}', logger=logger) - table_data = [header] - for j in range(num_classes): - row_data = [ - label_names[j], num_gts[i, j], results[j]['num_dets'], - f'{recalls[i, j]:.3f}', f'{aps[i, j]:.3f}' - ] - table_data.append(row_data) - table_data.append(['mAP', '', '', '', f'{mean_ap[i]:.3f}']) - table = AsciiTable(table_data) - table.inner_footing_row_border = True - print_log('\n' + table.table, logger=logger) diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/models/dense_heads/deformable_detr_head.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/models/dense_heads/deformable_detr_head.py deleted file mode 100644 index 92c980a91c8fde66dc3822df31cfefb74b676b11..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/models/dense_heads/deformable_detr_head.py +++ /dev/null @@ -1,317 +0,0 @@ -import copy - -import torch -import torch.nn as nn -import torch.nn.functional as F -from mmcv.cnn import Linear, bias_init_with_prob, constant_init -from mmcv.runner import force_fp32 - -from mmdet.core import multi_apply -from mmdet.models.utils.transformer import inverse_sigmoid -from ..builder import HEADS -from .detr_head import DETRHead - - -@HEADS.register_module() -class DeformableDETRHead(DETRHead): - """Head of DeformDETR: Deformable DETR: Deformable Transformers for End-to- - End Object Detection. - - Code is modified from the `official github repo - `_. - - More details can be found in the `paper - `_ . - - Args: - with_box_refine (bool): Whether to refine the reference points - in the decoder. Defaults to False. - as_two_stage (bool) : Whether to generate the proposal from - the outputs of encoder. - transformer (obj:`ConfigDict`): ConfigDict is used for building - the Encoder and Decoder. - """ - - def __init__(self, - *args, - with_box_refine=False, - as_two_stage=False, - transformer=None, - **kwargs): - self.with_box_refine = with_box_refine - self.as_two_stage = as_two_stage - if self.as_two_stage: - transformer['as_two_stage'] = self.as_two_stage - - super(DeformableDETRHead, self).__init__( - *args, transformer=transformer, **kwargs) - - def _init_layers(self): - """Initialize classification branch and regression branch of head.""" - - fc_cls = Linear(self.embed_dims, self.cls_out_channels) - reg_branch = [] - for _ in range(self.num_reg_fcs): - reg_branch.append(Linear(self.embed_dims, self.embed_dims)) - reg_branch.append(nn.ReLU()) - reg_branch.append(Linear(self.embed_dims, 4)) - reg_branch = nn.Sequential(*reg_branch) - - def _get_clones(module, N): - return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) - - # last reg_branch is used to generate proposal from - # encode feature map when as_two_stage is True. - num_pred = (self.transformer.decoder.num_layers + 1) if \ - self.as_two_stage else self.transformer.decoder.num_layers - - if self.with_box_refine: - self.cls_branches = _get_clones(fc_cls, num_pred) - self.reg_branches = _get_clones(reg_branch, num_pred) - else: - - self.cls_branches = nn.ModuleList( - [fc_cls for _ in range(num_pred)]) - self.reg_branches = nn.ModuleList( - [reg_branch for _ in range(num_pred)]) - - if not self.as_two_stage: - self.query_embedding = nn.Embedding(self.num_query, - self.embed_dims * 2) - - def init_weights(self): - """Initialize weights of the DeformDETR head.""" - self.transformer.init_weights() - if self.loss_cls.use_sigmoid: - bias_init = bias_init_with_prob(0.01) - for m in self.cls_branches: - nn.init.constant_(m.bias, bias_init) - for m in self.reg_branches: - constant_init(m[-1], 0, bias=0) - nn.init.constant_(self.reg_branches[0][-1].bias.data[2:], -2.0) - if self.as_two_stage: - for m in self.reg_branches: - nn.init.constant_(m[-1].bias.data[2:], 0.0) - - def forward(self, mlvl_feats, img_metas): - """Forward function. - - Args: - mlvl_feats (tuple[Tensor]): Features from the upstream - network, each is a 4D-tensor with shape - (N, C, H, W). - img_metas (list[dict]): List of image information. - - Returns: - all_cls_scores (Tensor): Outputs from the classification head, \ - shape [nb_dec, bs, num_query, cls_out_channels]. Note \ - cls_out_channels should includes background. - all_bbox_preds (Tensor): Sigmoid outputs from the regression \ - head with normalized coordinate format (cx, cy, w, h). \ - Shape [nb_dec, bs, num_query, 4]. - enc_outputs_class (Tensor): The score of each point on encode \ - feature map, has shape (N, h*w, num_class). Only when \ - as_two_stage is Ture it would be returned, otherwise \ - `None` would be returned. - enc_outputs_coord (Tensor): The proposal generate from the \ - encode feature map, has shape (N, h*w, 4). Only when \ - as_two_stage is Ture it would be returned, otherwise \ - `None` would be returned. - """ - - batch_size = mlvl_feats[0].size(0) - input_img_h, input_img_w = img_metas[0]['batch_input_shape'] - img_masks = mlvl_feats[0].new_ones( - (batch_size, input_img_h, input_img_w)) - for img_id in range(batch_size): - img_h, img_w, _ = img_metas[img_id]['img_shape'] - img_masks[img_id, :img_h, :img_w] = 0 - - mlvl_masks = [] - mlvl_positional_encodings = [] - for feat in mlvl_feats: - mlvl_masks.append( - F.interpolate(img_masks[None], - size=feat.shape[-2:]).to(torch.bool).squeeze(0)) - mlvl_positional_encodings.append( - self.positional_encoding(mlvl_masks[-1])) - - query_embeds = None - if not self.as_two_stage: - query_embeds = self.query_embedding.weight - hs, init_reference, inter_references, \ - enc_outputs_class, enc_outputs_coord = self.transformer( - mlvl_feats, - mlvl_masks, - query_embeds, - mlvl_positional_encodings, - reg_branches=self.reg_branches if self.with_box_refine else None, # noqa:E501 - cls_branches=self.cls_branches if self.as_two_stage else None # noqa:E501 - ) - hs = hs.permute(0, 2, 1, 3) - outputs_classes = [] - outputs_coords = [] - - for lvl in range(hs.shape[0]): - if lvl == 0: - reference = init_reference - else: - reference = inter_references[lvl - 1] - reference = inverse_sigmoid(reference) - outputs_class = self.cls_branches[lvl](hs[lvl]) - tmp = self.reg_branches[lvl](hs[lvl]) - if reference.shape[-1] == 4: - tmp += reference - else: - assert reference.shape[-1] == 2 - tmp[..., :2] += reference - outputs_coord = tmp.sigmoid() - outputs_classes.append(outputs_class) - outputs_coords.append(outputs_coord) - - outputs_classes = torch.stack(outputs_classes) - outputs_coords = torch.stack(outputs_coords) - if self.as_two_stage: - return outputs_classes, outputs_coords, \ - enc_outputs_class, \ - enc_outputs_coord.sigmoid() - else: - return outputs_classes, outputs_coords, \ - None, None - - @force_fp32(apply_to=('all_cls_scores_list', 'all_bbox_preds_list')) - def loss(self, - all_cls_scores, - all_bbox_preds, - enc_cls_scores, - enc_bbox_preds, - gt_bboxes_list, - gt_labels_list, - img_metas, - gt_bboxes_ignore=None): - """"Loss function. - - Args: - all_cls_scores (Tensor): Classification score of all - decoder layers, has shape - [nb_dec, bs, num_query, cls_out_channels]. - all_bbox_preds (Tensor): Sigmoid regression - outputs of all decode layers. Each is a 4D-tensor with - normalized coordinate format (cx, cy, w, h) and shape - [nb_dec, bs, num_query, 4]. - enc_cls_scores (Tensor): Classification scores of - points on encode feature map , has shape - (N, h*w, num_classes). Only be passed when as_two_stage is - True, otherwise is None. - enc_bbox_preds (Tensor): Regression results of each points - on the encode feature map, has shape (N, h*w, 4). Only be - passed when as_two_stage is True, otherwise is None. - gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image - with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. - gt_labels_list (list[Tensor]): Ground truth class indices for each - image with shape (num_gts, ). - img_metas (list[dict]): List of image meta information. - gt_bboxes_ignore (list[Tensor], optional): Bounding boxes - which can be ignored for each image. Default None. - - Returns: - dict[str, Tensor]: A dictionary of loss components. - """ - assert gt_bboxes_ignore is None, \ - f'{self.__class__.__name__} only supports ' \ - f'for gt_bboxes_ignore setting to None.' - - num_dec_layers = len(all_cls_scores) - all_gt_bboxes_list = [gt_bboxes_list for _ in range(num_dec_layers)] - all_gt_labels_list = [gt_labels_list for _ in range(num_dec_layers)] - all_gt_bboxes_ignore_list = [ - gt_bboxes_ignore for _ in range(num_dec_layers) - ] - img_metas_list = [img_metas for _ in range(num_dec_layers)] - - losses_cls, losses_bbox, losses_iou = multi_apply( - self.loss_single, all_cls_scores, all_bbox_preds, - all_gt_bboxes_list, all_gt_labels_list, img_metas_list, - all_gt_bboxes_ignore_list) - - loss_dict = dict() - # loss of proposal generated from encode feature map. - if enc_cls_scores is not None: - binary_labels_list = [ - torch.zeros_like(gt_labels_list[i]) - for i in range(len(img_metas)) - ] - enc_loss_cls, enc_losses_bbox, enc_losses_iou = \ - self.loss_single(enc_cls_scores, enc_bbox_preds, - gt_bboxes_list, binary_labels_list, - img_metas, gt_bboxes_ignore) - loss_dict['enc_loss_cls'] = enc_loss_cls - loss_dict['enc_loss_bbox'] = enc_losses_bbox - loss_dict['enc_loss_iou'] = enc_losses_iou - - # loss from the last decoder layer - loss_dict['loss_cls'] = losses_cls[-1] - loss_dict['loss_bbox'] = losses_bbox[-1] - loss_dict['loss_iou'] = losses_iou[-1] - # loss from other decoder layers - num_dec_layer = 0 - for loss_cls_i, loss_bbox_i, loss_iou_i in zip(losses_cls[:-1], - losses_bbox[:-1], - losses_iou[:-1]): - loss_dict[f'd{num_dec_layer}.loss_cls'] = loss_cls_i - loss_dict[f'd{num_dec_layer}.loss_bbox'] = loss_bbox_i - loss_dict[f'd{num_dec_layer}.loss_iou'] = loss_iou_i - num_dec_layer += 1 - return loss_dict - - @force_fp32(apply_to=('all_cls_scores_list', 'all_bbox_preds_list')) - def get_bboxes(self, - all_cls_scores, - all_bbox_preds, - enc_cls_scores, - enc_bbox_preds, - img_metas, - rescale=False): - """Transform network outputs for a batch into bbox predictions. - - Args: - all_cls_scores (Tensor): Classification score of all - decoder layers, has shape - [nb_dec, bs, num_query, cls_out_channels]. - all_bbox_preds (Tensor): Sigmoid regression - outputs of all decode layers. Each is a 4D-tensor with - normalized coordinate format (cx, cy, w, h) and shape - [nb_dec, bs, num_query, 4]. - enc_cls_scores (Tensor): Classification scores of - points on encode feature map , has shape - (N, h*w, num_classes). Only be passed when as_two_stage is - True, otherwise is None. - enc_bbox_preds (Tensor): Regression results of each points - on the encode feature map, has shape (N, h*w, 4). Only be - passed when as_two_stage is True, otherwise is None. - img_metas (list[dict]): Meta information of each image. - rescale (bool, optional): If True, return boxes in original - image space. Defalut False. - - Returns: - list[list[Tensor, Tensor]]: Each item in result_list is 2-tuple. \ - The first item is an (n, 5) tensor, where the first 4 columns \ - are bounding box positions (tl_x, tl_y, br_x, br_y) and the \ - 5-th column is a score between 0 and 1. The second item is a \ - (n,) tensor where each item is the predicted class label of \ - the corresponding box. - """ - cls_scores = all_cls_scores[-1] - bbox_preds = all_bbox_preds[-1] - - result_list = [] - for img_id in range(len(img_metas)): - cls_score = cls_scores[img_id] - bbox_pred = bbox_preds[img_id] - img_shape = img_metas[img_id]['img_shape'] - scale_factor = img_metas[img_id]['scale_factor'] - proposals = self._get_bboxes_single(cls_score, bbox_pred, - img_shape, scale_factor, - rescale) - result_list.append(proposals) - return result_list diff --git a/spaces/tracinginsights/F1-analysis/pages/Longitudinal_Acceleration_VS_speed.py b/spaces/tracinginsights/F1-analysis/pages/Longitudinal_Acceleration_VS_speed.py deleted file mode 100644 index d4954af2fb348fb058c6d444372f691d7d875838..0000000000000000000000000000000000000000 --- a/spaces/tracinginsights/F1-analysis/pages/Longitudinal_Acceleration_VS_speed.py +++ /dev/null @@ -1,25 +0,0 @@ -import streamlit as st -from repo_directory import Longitudinal_Acceleration_VS_Speed -from repo_directory import button - -YEAR_SELECTED = st.selectbox( - 'Select year', - (2023, 2022, 2021, 2020, 2019, 2018)) - -RACE_SELECTED = st.selectbox( - 'Select Race', - (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)) - -SESSION = st.selectbox( - 'Select Session', - ('FP1', 'FP2', 'FP3','SS', 'Q', 'SQ', 'R')) - - -laps, f1session, drivers = Longitudinal_Acceleration_VS_Speed.get_data(YEAR_SELECTED, RACE_SELECTED, SESSION) - - -DRIVERS_SELECTED = st.multiselect( - 'Select Drivers to compare', - drivers) - -Longitudinal_Acceleration_VS_Speed.plot(DRIVERS_SELECTED, laps, f1session, SESSION) \ No newline at end of file diff --git a/spaces/tracinginsights/F1-analysis/style.css b/spaces/tracinginsights/F1-analysis/style.css deleted file mode 100644 index 27411b8835fd4916ee70296794d00fb0f7aaca97..0000000000000000000000000000000000000000 --- a/spaces/tracinginsights/F1-analysis/style.css +++ /dev/null @@ -1,30 +0,0 @@ -.css-12oz5g7.egzxvld2 { - padding-top: 0px; -} - -.css-1v0mbdj.etr89bj1 { - display: block; - margin-left: auto; - margin-right: auto; - min-width: 180px; - max-width: 40%; -} - -.css-10trblm.e16nr0p30 { - font-weight: bold; - text-align: center; -} - -p { - font-size: 19px; -} - -MainMenu { - visibility: hidden; -} -footer { - visibility: hidden; -} -header { - visibility: hidden; -} \ No newline at end of file diff --git a/spaces/trttung1610/musicgen/audiocraft/grids/musicgen/__init__.py b/spaces/trttung1610/musicgen/audiocraft/grids/musicgen/__init__.py deleted file mode 100644 index d3f101f5a29ff85271e44e4f27545168a8f27baa..0000000000000000000000000000000000000000 --- a/spaces/trttung1610/musicgen/audiocraft/grids/musicgen/__init__.py +++ /dev/null @@ -1,6 +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. -"""MusicGen grids.""" diff --git a/spaces/trttung1610/musicgen/tests/models/test_audiogen.py b/spaces/trttung1610/musicgen/tests/models/test_audiogen.py deleted file mode 100644 index 3850af066cedd5ea38bd9aead9634d6aaf938218..0000000000000000000000000000000000000000 --- a/spaces/trttung1610/musicgen/tests/models/test_audiogen.py +++ /dev/null @@ -1,53 +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 pytest -import torch - -from audiocraft.models import AudioGen - - -class TestAudioGenModel: - def get_audiogen(self): - ag = AudioGen.get_pretrained(name='debug', device='cpu') - ag.set_generation_params(duration=2.0, extend_stride=2.) - return ag - - def test_base(self): - ag = self.get_audiogen() - assert ag.frame_rate == 25 - assert ag.sample_rate == 16000 - assert ag.audio_channels == 1 - - def test_generate_continuation(self): - ag = self.get_audiogen() - prompt = torch.randn(3, 1, 16000) - wav = ag.generate_continuation(prompt, 16000) - assert list(wav.shape) == [3, 1, 32000] - - prompt = torch.randn(2, 1, 16000) - wav = ag.generate_continuation( - prompt, 16000, ['youpi', 'lapin dort']) - assert list(wav.shape) == [2, 1, 32000] - - prompt = torch.randn(2, 1, 16000) - with pytest.raises(AssertionError): - wav = ag.generate_continuation( - prompt, 16000, ['youpi', 'lapin dort', 'one too many']) - - def test_generate(self): - ag = self.get_audiogen() - wav = ag.generate( - ['youpi', 'lapin dort']) - assert list(wav.shape) == [2, 1, 32000] - - def test_generate_long(self): - ag = self.get_audiogen() - ag.max_duration = 3. - ag.set_generation_params(duration=4., extend_stride=2.) - wav = ag.generate( - ['youpi', 'lapin dort']) - assert list(wav.shape) == [2, 1, 16000 * 4] diff --git a/spaces/uSerNameDDHL/bingo/src/components/chat-scroll-anchor.tsx b/spaces/uSerNameDDHL/bingo/src/components/chat-scroll-anchor.tsx deleted file mode 100644 index ac809f4486a48e134cb69314c3d0dae5e68d614e..0000000000000000000000000000000000000000 --- a/spaces/uSerNameDDHL/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/umoubuton/atri-bert-vits2/text/japanese_bert.py b/spaces/umoubuton/atri-bert-vits2/text/japanese_bert.py deleted file mode 100644 index 5dd196483da4355746383253879190ce538b9df9..0000000000000000000000000000000000000000 --- a/spaces/umoubuton/atri-bert-vits2/text/japanese_bert.py +++ /dev/null @@ -1,38 +0,0 @@ -import torch -from transformers import AutoTokenizer, AutoModelForMaskedLM -import sys - -tokenizer = AutoTokenizer.from_pretrained("./bert/bert-base-japanese-v3") - -models = dict() - - -def get_bert_feature(text, word2ph, device=None): - if ( - sys.platform == "darwin" - and torch.backends.mps.is_available() - and device == "cpu" - ): - device = "mps" - if not device: - device = "cuda" - if device not in models.keys(): - models[device] = AutoModelForMaskedLM.from_pretrained( - "./bert/bert-base-japanese-v3" - ).to(device) - with torch.no_grad(): - inputs = tokenizer(text, return_tensors="pt") - for i in inputs: - inputs[i] = inputs[i].to(device) - res = models[device](**inputs, output_hidden_states=True) - res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu() - assert inputs["input_ids"].shape[-1] == len(word2ph) - word2phone = word2ph - phone_level_feature = [] - for i in range(len(word2phone)): - repeat_feature = res[i].repeat(word2phone[i], 1) - phone_level_feature.append(repeat_feature) - - phone_level_feature = torch.cat(phone_level_feature, dim=0) - - return phone_level_feature.T diff --git a/spaces/usbethFlerru/sovits-modelsV2/example/Affi Come Back Vybz Kartel A Guide to the Patois Slang.md b/spaces/usbethFlerru/sovits-modelsV2/example/Affi Come Back Vybz Kartel A Guide to the Patois Slang.md deleted file mode 100644 index 6a708d8b30537ab612da1dd3c8cf847923caac55..0000000000000000000000000000000000000000 --- a/spaces/usbethFlerru/sovits-modelsV2/example/Affi Come Back Vybz Kartel A Guide to the Patois Slang.md +++ /dev/null @@ -1,5 +0,0 @@ - -

          Poor dem
          We nuh run into people
          We nuh beg friend
          We nuh affi guh nuhweh fi come back, boomerang
          If a gun and gunshot, Lawd God, mi fulla dem
          Copper jump ina yuh face like mi ninja Timberland
          Mek yuh marrow fly so far dem seh Look, a superman
          Blood a run outta yuh nose instead of oxygen
          Salt Spring, we head steamy like rice, Uncle Ben
          Yow, a wah do dem

          -

          affi come back vybz kartel


          DOWNLOAD 🔗 https://urlcod.com/2uyX8p



          aaccfb2cb3
          -
          -
          \ No newline at end of file diff --git a/spaces/usbethFlerru/sovits-modelsV2/example/Autodata 3.18 2cd English Serial Key Keygen.md b/spaces/usbethFlerru/sovits-modelsV2/example/Autodata 3.18 2cd English Serial Key Keygen.md deleted file mode 100644 index 8f368246fea5e7a1380e0570da65f82102ed77e5..0000000000000000000000000000000000000000 --- a/spaces/usbethFlerru/sovits-modelsV2/example/Autodata 3.18 2cd English Serial Key Keygen.md +++ /dev/null @@ -1,72 +0,0 @@ - -

          Autodata 3.18 2'cd English Serial Key Keygen: How to Get and Use the Best Automotive Software

          -

          Are you looking for a software that can help you with your car repair and maintenance needs? Do you want to access the most comprehensive and accurate data on various models of vehicles from different manufacturers? If yes, then you might be interested in Autodata 3.18 2'cd English Serial Key keygen.

          -

          Autodata 3.18 2'cd English Serial Key keygen


          Download Zip 🆗 https://urlcod.com/2uyWv2



          -

          Autodata 3.18 2'cd English is a software that provides you with all the information and tools that you need to diagnose, service, and repair any vehicle. It covers over 17,000 models of cars, motorcycles, trucks, and vans from over 80 manufacturers worldwide. It includes data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.

          -

          However, Autodata 3.18 2'cd English is not a free software. It requires a license key and an activation code to run on your computer. If you don't have these codes, you may be tempted to look for a keygen, which is a program that generates serial keys and activation codes for software products. However, using a keygen is not only illegal but also risky. You may end up downloading a fake or malicious file that can harm your device or data.

          -

          In this article, we will show you how to get Autodata 3.18 2'cd English Serial Key keygen safely and legally. We will also give you some tips on how to use Autodata 3.18 2'cd English effectively and efficiently. So, without further ado, let's get started!

          -

          How to Get Autodata 3.18 2'cd English Serial Key Keygen Safely and Legally?

          -

          The best way to get Autodata 3.18 2'cd English Serial Key keygen safely and legally is to buy it from the official website of Autodata Limited. Autodata Limited is a British multinational company that specializes in automotive data and software solutions. It has been in the industry since 1975 and has a reputation for quality and reliability.

          -

          To buy Autodata 3.18 2'cd English from the official website, you need to follow these steps:

          -
            -
          1. Visit the official website of Autodata Limited: You can visit the official website of Autodata Limited by clicking here. You will see a homepage with various options and information.
          2. -
          3. Select your region and language: You can select your region and language from the drop-down menus at the top right corner of the homepage. You will see different products and prices depending on your region and language.
          4. -
          5. Select Autodata 3.18 2'cd English: You can select Autodata 3.18 2'cd English from the list of products on the homepage or from the menu bar at the top of the page. You will see a product page with a description, features, benefits, screenshots, and system requirements of Autodata 3.18 2'cd English.
          6. -
          7. Add Autodata 3.18 2'cd English to your cart: You can add Autodata 3.18 2'cd English to your cart by clicking on the "Add to Cart" button on the product page. You will see a pop-up window with your cart details and options.
          8. -
          9. Proceed to checkout: You can proceed to checkout by clicking on the "Proceed to Checkout" button on the pop-up window or on the cart icon at the top right corner of the page. You will see a checkout page with your order summary and payment options.
          10. -
          11. Enter your billing and shipping information: You can enter your billing and shipping information on the checkout page by filling in the required fields and selecting your preferred delivery method.
          12. -
          13. Enter your payment information: You can enter your payment information on the checkout page by choosing your preferred payment method and providing your card details or PayPal account.
          14. -
          15. Confirm your order: You can confirm your order on the checkout page by reviewing your order details and clicking on the "Place Order" button. You will see a confirmation page with your order number and invoice.
          16. -
          17. Receive your license key and activation code: You will receive your license key and activation code via email within a few minutes after placing your order. You will also receive a confirmation email with your order details and tracking information.
          18. -
          19. Download Autodata 3.18 2'cd English: You can download -

            - from the confirmation email or from the official website by clicking on the "Download" button. You will see a download page with instructions and a link to download the software.
          20. -
          21. Install Autodata 3.18 2'cd English: You can install on your computer by following the instructions on the download page or on the installation wizard. You will need to agree to the terms and conditions, choose your installation location, and enter your license key and activation code.
          22. -
          23. Enjoy Autodata 3.18 2'cd English: You can enjoy on your computer by launching it from your desktop or start menu. You will see a user interface with various options and features that you can use to access and manage the automotive data and software.
          24. -
          -

          By following these steps, you can get safely and legally from the official website of Autodata Limited. You can also avoid any legal, security, or quality issues that may arise from using a keygen or a fake file.

          -

          How to Use Autodata 3.18 2'cd English Effectively and Efficiently?

          -

          Now that you have on your computer, you may wonder how to use it effectively and efficiently to diagnose, service, and repair any vehicle. Here are some tips that you should follow to do so:

          -
            -
          • Update Autodata 3.18 2'cd English regularly: You should update regularly to get the latest data and software updates from Autodata Limited. You can update by clicking on the "Update" button on the user interface or by checking for updates manually from the menu bar.
          • -
          • Select your vehicle model and year: You should select your vehicle model and year from the drop-down menus on the user interface or by typing in the registration number or VIN number of your vehicle. This will help you access the relevant data and software for your vehicle.
          • -
          • Browse through the data and software categories: You should browse through the data and software categories on the user interface or from the menu bar to find what you need. Some of the categories are wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.
          • -
          • Use the search function: You should use the search function on the user interface or from the menu bar to find what you need quickly and easily. You can type in keywords, phrases, codes, or numbers related to your query and get results instantly.
          • -
          • Use the print function: You should use the print function on the user interface or from the menu bar to print out any data or software that you need for reference or documentation purposes. You can choose what to print, how to print, and where to print.
          • -
          • Use the help function: You should use the help function on the user interface or from the menu bar to get assistance or guidance on how to use . You can access tutorials, FAQs, manuals, videos, forums, and customer support from this function.
          • -
          -

          By following these tips, you can use effectively and efficiently to diagnose, service, and repair any vehicle. You can also save time, money, and effort by using this software.

          -

          Conclusion

          -

          is a software that provides you with comprehensive and accurate information on various aspects of automotive repair and maintenance. It covers over 17,000 models of vehicles from over 80 manufacturers worldwide. It includes data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.

          -

          The best way to get -

          The best way to use Autodata 3.18 2'cd English effectively and efficiently is to update it regularly, select your vehicle model and year, browse through the data and software categories, use the search function, use the print function, and use the help function. You can also save time, money, and effort by using this software.

          -

          We hope that this article was helpful and informative for you. If you want to learn more about Autodata 3.18 2'cd English Serial Key keygen, you can visit the official website of Autodata Limited or contact their customer support. You can also check out some of the other articles on our website for more tips and tricks on automotive repair and maintenance. Thank you for reading and have a great day!

          -

          What are the Benefits of Autodata 3.18 2'cd English Serial Key keygen?

          -

          By using Autodata 3.18 2'cd English Serial Key keygen, you can enjoy many benefits that can improve your automotive repair and maintenance skills and experience. Some of these benefits are:

          -
            -
          • Comprehensive and accurate data: You can access comprehensive and accurate data on various aspects of automotive repair and maintenance for over 17,000 models of vehicles from over 80 manufacturers worldwide. You can find data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.
          • -
          • Easy and convenient access: You can access Autodata 3.18 2'cd English on your computer anytime and anywhere. You don't need an internet connection or a subscription to use it. You just need a license key and an activation code to run it.
          • -
          • User-friendly interface: You can use Autodata 3.18 2'cd English easily and comfortably with its user-friendly interface. You can navigate through the data and software categories, use the search function, use the print function, and use the help function with ease.
          • -
          • Regular updates: You can get regular updates from Autodata Limited to get the latest data and software updates for Autodata 3.18 2'cd English. You can update Autodata 3.18 2'cd English by clicking on the "Update" button on the user interface or by checking for updates manually from the menu bar.
          • -
          • Customer support: You can get customer support from Autodata Limited if you have any questions or issues regarding Autodata 3.18 2'cd English Serial Key keygen. You can contact their customer support by email, phone, or online chat. You can also access tutorials, FAQs, manuals, videos, forums, and more from the help function.
          • -
          -

          These are some of the benefits that you can enjoy by using Autodata 3.18 2'cd English Serial Key keygen. You can also improve your automotive repair and maintenance knowledge and skills by using this software.

          -

          What are the Alternatives to Autodata 3.18 2'cd English Serial Key keygen?

          -

          If you are looking for alternatives to Autodata 3.18 2'cd English Serial Key keygen, you may want to check out some of these options:

          -
            -
          • AllData: AllData is another software that provides comprehensive and accurate data on various aspects of automotive repair and maintenance. It covers over 38,000 models of vehicles from over 100 manufacturers worldwide. It includes data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.
          • -
          • Mitchell OnDemand: Mitchell OnDemand is another software that provides comprehensive and accurate data on various aspects of automotive repair and maintenance. It covers over 30,000 models of vehicles from over 80 manufacturers worldwide. It includes data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.
          • -
          • ElsaWin: ElsaWin is another software that provides comprehensive and accurate data on various aspects of automotive repair and maintenance. It covers over 20,000 models of vehicles from over 50 manufacturers worldwide. It includes data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.
          • -
          • EsiTronic: EsiTronic is another software that provides comprehensive and accurate data on various aspects of automotive repair and maintenance. It covers over 15,000 models of vehicles from over 40 manufacturers worldwide. It includes data on wiring diagrams, diagnostics -
          • -
          -

          These are some of the alternatives that you can try if you are looking for other software that can provide you with automotive data and software solutions. However, you should be aware that these software may also require license keys and activation codes to run on your computer. You should also check their prices, features, benefits, and reviews before buying them.

          -

          Conclusion

          -

          Autodata 3.18 2'cd English Serial Key keygen is a software that provides you with comprehensive and accurate data on various aspects of automotive repair and maintenance. It covers over 17,000 models of vehicles from over 80 manufacturers worldwide. It includes data on wiring diagrams, diagnostics, service schedules, technical specifications, repair times, and more.

          -

          The best way to get Autodata 3.18 2'cd English Serial Key keygen safely and legally is to buy it from the official website of Autodata Limited. You can also avoid any legal, security, or quality issues that may arise from using a keygen or a fake file.

          -

          The best way to use Autodata 3.18 2'cd English effectively and efficiently is to update it regularly, select your vehicle model and year, browse through the data and software categories, use the search function, use the print function, and use the help function. You can also save time, money, and effort by using this software.

          -

          If you are looking for alternatives to Autodata 3.18 2'cd English Serial Key keygen, you may want to check out some of these options: AllData, Mitchell OnDemand, ElsaWin, and EsiTronic. However, you should be aware that these software may also require license keys and activation codes to run on your computer. You should also check their prices, features, benefits, and reviews before buying them.

          -

          We hope that this article was helpful and informative for you. If you want to learn more about Autodata 3.18 2'cd English Serial Key keygen, you can visit the official website of Autodata Limited or contact their customer support. You can also check out some of the other articles on our website for more tips and tricks on automotive repair and maintenance. Thank you for reading and have a great day!

          3cee63e6c2
          -
          -
          \ No newline at end of file diff --git a/spaces/usbethFlerru/sovits-modelsV2/example/Cubase 7 5 Dongle Emulator Crack Download and Enjoy the Latest Features of Cubase 7.5 for Free.md b/spaces/usbethFlerru/sovits-modelsV2/example/Cubase 7 5 Dongle Emulator Crack Download and Enjoy the Latest Features of Cubase 7.5 for Free.md deleted file mode 100644 index 676683d672f76c7ae5011f62bf2bb5a1238ff09f..0000000000000000000000000000000000000000 --- a/spaces/usbethFlerru/sovits-modelsV2/example/Cubase 7 5 Dongle Emulator Crack Download and Enjoy the Latest Features of Cubase 7.5 for Free.md +++ /dev/null @@ -1,5 +0,0 @@ -
          -

          Our team provide different types of services such as: - proffessional cracking of any kind of software
          (CAD,CAM,CAE,EDA,GIS,PCB,FEA,FEM,CNC,CFD,PDS,3D,Optics etc.) designed
          for any kind of operating systems(Windows 95/98/ME/2000/XP, Linux,
          FreeBSD, OS/2, MAC OS etc.) - producing keygens, licenses for different proctection systems (FlexLM,
          SentinelLM, ElanLM, CrypKey, etc.) - producing emulators for any kind of dongles (SentinelPro,
          SentinelSuperPro, Hasp4, Hardlock, WIBU, Guardant, etc.) - quality reverse engineering (decompilation of programs, algorithms
          reconstruction, etc.) - any other reverse engineering services... Also we have an excellent relationship with all our customers and we
          always happy to help them solve their problems. Our skills and experince
          will help you make a valuable conribution to your business. All soft we offer have been completely cracked and tested carefully by
          expert in corresponding field. All programs are full copies of originals
          (not demo, evaluation, trial or educational version) including English
          or multilanguage tutorial and crack or license file that makes program
          work as registered software from the house.
          Here is just a part of our software list.For getting the additional
          information, view our software list and ordering programs just visit our
          WEBSITE:




          >> Contact e-mail:


          ProSof...@yahoo.com

          or

          ProSof...@yahoo.comHere is an example of the most popular offered latest software: 20-20 Kitchen Design 6.1
          20-20 Kitchen Design 6.4
          20-20 Kitchen Design 8.0
          3D Geometrical Objects v1.4. WinAll
          3D Home Architect Home Design Deluxe 6.0
          3D Home Design Deluxe 6.0
          3D Home Design Suite Professional 5.0 Broderbund
          3D Home Landscape Designer Deluxe 5
          3D Spades Deluxe v1.6.WinAll
          3D Studio Max 6.0
          3D Studio Max 7.0
          3D Studio Max 7.5
          3D Studio Max 8.0
          3D Studio Max 9.0
          3D Total Textures vol. 12
          4M Fine Adapt 2005
          AAS MIDUSS V2.0
          ABAQUS 6.4
          ABAQUS 6.5.1
          ABB Pickmaster 2.3
          ABB Programmaker 4.3
          ABB Quickteach 5.3
          ABB Robot Studio 2.0
          ABB Robot Studio 3.1
          ABB Virtual IRC5 5.0
          ABB Webware SDK 4.0
          ABB Webware SDK 4.5
          ABBYY Fine Reader Pro 7.0
          ABSOFT Pro Fortran FOR WINDOWS 6.0
          ABVENT Artlantis 4.5 - ISO
          ABVENT Photocad 1.0
          Accel EDA 15.0
          Accel PCAD 2005
          Accelrys Materials Studio 2.2
          Accelrys Materials Studio 3.2
          Accelrys Materials Studio 3.01
          Accelrys DS Viewer Pro 5.0
          Access Password Recovery Genie 1.30
          Accumark 8
          Accumark Gerbertech 8.02
          Accumark Gerbertech 8.08
          ACD Systems ACDSee 6.0 PowerPack Deluxe
          ACD Systems ACDSee 7.0.47 Powerpack
          ACD Real View 3D Pro 2.0
          ACDsee 5.0
          ACDsee 6.0 Powerpack 3
          Acme CAD Converter 4.2
          Acme CAD Converter 4.3
          Acme Cad Converter v4.3.WinAll
          Acme Cad Packer v1.01.WinAll
          Acme CadSee 3.51
          Acme CADSee v3.5.WinAll
          Acme TraceArt v3.7
          ACNielsen Spaceman Store Suite 5.0
          ACNielsen Spaceman Application Builder 5.0
          ACNielsen Spaceman Professional 6.0
          Acrobat Capture 3.0 (Adobe)
          Acronis Disk Director Suite 9.0
          Acronis Disk Editor 6.0
          Acronis DriveCleanser 6.0
          Acronis OS Selector 5.0
          Acronis Partition Expert 2003 267
          Acronis Power Utilities 2003
          Acronis Privacy Expert 2003
          Acronis Privacy Expert Suite 8.0
          ACT 6 for 2004X
          Act - 3D Quest 3D Enterprise Edition 2.1
          Actel Designer 6.2
          Actel Designer 6.3
          Actify Spinfire Complete Pro 2004
          Actinic E-Commerce Business Suite 5.1 - E-Commerce
          Actinic E-Commerce 7.0.4
          Actinic Business 7.0.1
          Actinic Catalog 7.0.1
          Actinic Catalog 7.1
          Actinic Developer 7.0.1
          Actinic Order Manager 7.0.1
          Action Request System 6.0
          Actual Drawing 5.7
          Actual Transparent Window 2.8
          Actual Window Guard 2.8
          Actual Window Manager 2.8
          Actual Window Menu 2.8
          Actual Window Minimizer 2.8
          Actual Window Rollup 2.8
          Actuate 7 SP2
          AD VISUAL DSP v3.5
          AD ASSURED v3.5
          Adams 12
          ADAPT BUILDER 1.5.4
          Adapt PT 6.15
          Adapt PT 6.18
          Adaptsoft Adapt Builder 1.11
          Adaptsoft Adapt PT 6.15
          Adaptsoft Adapt PT 6.18
          ADAPTSOFT ADAPT PT 7.10
          Adina System 7.5.4
          Adina System 8.07
          Adina System 8.1
          AdLib eXpress Desktop 2.7
          AdLib eXpress Server 2.7
          Adobe Acrobat 5.0 for Mac OSX
          Adobe Acrobat 6.0 Professional
          Adobe Acrobat 6.0. Professional for Mac OSX
          Adobe Acrobat 7.0 Professional
          Adobe Acrobat 8.0 Professional
          Adobe Acrobat 7.0. Professional for Mac OSX
          Adobe Acrobat 7.0 Standard
          Adobe Acrobat Capture 3.0
          Adobe After Effect Pro 6.5
          Adobe After Effect Pro 7.0
          Adobe After Effects Professional 6.5. for Mac OSX
          Adobe After Effects 6.0. Professional for Mac OSX
          Adobe Atmosphere 1.0
          Adobe Audition 1.0
          Adobe Audition 2.0
          Adobe Creative Suite 2005
          Adobe Creative Suite Premium Edition 2.0 (7 cds)
          Adobe Creative Suite Premium Edition 2.0 for Mac (6 cds)
          Adobe Creative Suite Premium Edition 3.0
          Adobe Creative Suite Premium Edition 3.0 for Mac
          Adobe Creative Suite CS CE Premium Edition
          Adobe Encore DVD 1.0 for Windows XP
          Adobe Encore DVD 1.5
          Adobe Font Folio Open Type Edition 10
          Adobe Font Folio Open Type Edition Hybrid
          Adobe Frame Maker 7.0
          Adobe Frame Maker 7.1
          Adobe Graphics Server 2.1
          Adobe GoLive 6.0
          Adobe GoLive CS 7.0
          Adobe Illustrator 10.0
          Adobe Illustrator 11.0
          Adobe Illustrator 11.0 for MAC OSX
          Adobe Illustrator 12.0
          Adobe Illustrator 10.0.3. for MAC OSX
          Adobe Illustrator CS 11.00
          Adobe Illustrator CS 11.01
          Adobe Illustrator CS 11.02
          Adobe InCopy CS 3.0
          Adobe InCopy CS 3.0. for MAC OSX
          Adobe InDesign 2.0.1 CE
          Adobe InDesign CS 3.0 Pagemaker Edtion
          Adobe Indesign 2.0 for MAC OSX
          Adobe LiveMotion 2.0
          Adobe LiveMotion 2.0 for MAC OSX
          Adobe PageMaker 7.0
          Adobe PageMaker 7.0.1 for MAC OSX
          Adobe Photoshop 3d Textures
          Adobe Photoshop 7.0
          Adobe Photoshop 7.0 Final for MAC OSX
          Adobe Photoshop Album 2.0
          Adobe Photoshop CS 8.0
          Adobe Photoshop CS2 9.0
          Adobe Photoshop CS3 10
          Adobe Photoshop Elements 2.0
          Adobe Photoshop Elements 3.0
          Adobe Photoshop Elements 3.0 for MAC OSX
          Adobe Photoshop Elements 4.0
          Adobe Premiere Pro 1.5
          Adobe Premiere Pro 7.0
          Adobe Premier 6
          Adobe Premier 6.5
          Adobe SmartSound 6.5 for Adobe Premier 6.5
          Adorage 7.0
          Ad Visual Dsp 3.5
          Advanced Design System 1.5 AGILENT
          Advanced Electronics Design System 1.2
          Advanced GET EOD 8.0
          AEA CFX 5.5.1
          AEA Pipesys 1.13
          AEA Technology CFX 4.4
          AEA Technology HYSYS 3.0.1
          AEC CADPIPE 2002.Building Services 6.6 for AutoCAD
          AEC CADPIPE 2002.Commercial Pipe 6.6 for AutoCAD
          AEC Cadpipe 2002 HVAC 6.6 for AutoCAD
          AEC Cadpipe 2002 Industrial 6.6 for AutoCAD
          AEC CADPIPE 2004 Commercial Pipe_v6 6 for AutoCAD
          AEC CADPIPE 2004 HVAC_v6 6 for AutoCAD
          AEC CADPIPE 2004 Industrial_v6 6 for AutoCAD
          AEC CADPIPE 2005 Building Services_v6 6 for AutoCAD
          AEGIS CIRCUITCAM SUITE V5.0
          Aerofly Professional
          Aerofly Professional Expansion Pack
          Afterworks Afterburn 2.6
          Afterworks Dreamscape 1.0 for 3DSMAX4
          Agilent Advanced Design System 2003A
          AGILENT ADVANCED DESIGN SYSTEM 2005A
          Agilent VEE Pro 6.2
          Agilent VEE Pro 7.0
          Ahead Nero 7.0 Premium Edition
          Aicon 3d Studio 3.5
          Aid Submission Genius 2.8
          Aid System Restorer 2.5
          Aladdin Systems Internet Cleanup 4.0
          Aladdin Systems Stuffit Deluxe 7.0 for MAC OSX
          Aladdin Systems Stuffit Deluxe 9.0 for MAC OSX
          Alcatech BPM Studio Professional 4.80
          Aldec Active HDL 6.1
          Aldec Active HDL 7.1
          ALGOR Designcheck v18.0
          ALGOR InCAD Designer Mechanical Desktop v13
          Algor 12.0 for WINDOWS
          Algor 15.0
          Algor 16.0
          ALIAS IMAGE STUDIO V2.1
          Alias Maya 5 Beginers Guide Animation
          Alias Maya 5 Beginers Guide Rendering
          Alias Maya 6.0 Unlimited
          Alias Maya 7.0 Unlimited
          Alias Maya Masterclasses 2005
          ALIAS MENTAL RAY 3.3 for Maya
          Alias Mental Ray 3.4
          Alias MotionBuilder 6
          Alias MotionBuilder 6
          Alias MotionBuilder Pro 7.0
          Alias StudioTools 12.0
          Alias StudioTools 13.0
          Alias Wavefront Maya 5 MacOSX
          Alias Wavefront Maya 7.0 Unlimited
          Alias Wavefront Portfoliowall 1.6
          Alias Wavefront Studio Tools 10
          Alias Wavefront Studio Tools 11
          Alibre Design Proffesional 6.0
          Alibre Design Professional 7.0
          Alibre Design Professional 8.0
          All Plan 2005
          AlphaCAM 2004
          AlphaCAM v.6 2005
          Alsoft Diskwarrior 3.0.2. for MAC OSX
          Altair.Hyper Graph 5.0
          Altair.Hyper Form 5.0
          Altair Hyper Works 6.0
          Altair Hyper Works 7.0
          Altair Motion View 5.0
          Altair MotionView 5.1
          Altair Optistruct 5.0
          Altair Optistruct 5.1
          Altera Quartus 2 v.3.0
          Altera Quartus 2 v.4.0
          Altera Quartus 2 v.5.0
          Altera Max Plus 2 v.10.2
          Altium P-CAD 2002 SP1
          Altium Dxp Suite 2004
          ALTIVERB V4.0 MAC OSX ISO
          Altris EB Suite 12.5
          Alturion GPS Professional v5.2
          Alturion GPS Professional v5.3
          Alturion GPS Standart 5.0
          Alventive Ironcad Authoring Engine 2.0.SP2
          Amiable FlexiSign Family Pro v7.5 R3
          Amiable FlexiSign Family Pro v7.5 R4
          Amiable FlexiSign Pro 7.0
          Amiable FlexiSign Pro 7.5
          Amiable FlexiSign Pro 7.6
          Amtech ProDesign Nec 9.2.5
          Analytical Graphics Stk Pro 5.0
          Analyse 4.0
          Animator Professional 8.0
          Ansoft Designer 1.0
          Ansoft Designer 1.1
          Ansoft Designer 2.2
          Ansoft Electromagnetic 8.0
          Ansoft Ensemble 8.0
          Ansoft Ephysics 1.0
          Ansoft Hfss 9.0
          Ansoft Hfss 10.0
          ANSOFT HFSS v12.0
          Ansoft Maxwell 2D v8.0 3D v6.0
          Ansoft Maxwell EM 9
          Ansoft Maxwell EM 10
          Ansoft Pexprt 5.0
          Ansoft Optimetrics 2.5
          Ansoft Scap 5.5
          Ansoft Serenade Design Environment 8.0
          Ansoft Simplorer 6.0
          AnSys 8.0
          AnSys 8.1
          AnSys 9.0
          Ansys Ai Enviroment 1.0
          Ansys Ai Enviroment 2.0
          Ansys Ai Nastran 1.0
          Ansys CFX 10.0
          Ansys DesignSpace Suite 6.1
          ANSYS DesignSpace 8 1
          ANSYS Icem CFD 10.0
          ANSYS Icem CFD 5.0
          ANSYS Icem CFD 5.0 LINUX
          ANSYS Multiphysics 10.0
          ANSYS Multiphysics 9.0
          ANSYS Workbench 8.0
          ANSYS Workbench 10.0
          ANSYS Turbogrid 10.0
          Aplac 8.0
          Apple Final CUT Express 2.0 MAC OSX
          APPLE FINAL CUT PRO HD 4.5.DVD MAC OSX
          Apple MAC OSX 10.2
          Apple MAC OSX Panther 10.3
          Apple Remote Desktop 2 for MAC OSX
          Apple Web Objects 5.1
          Apple Works 6.2.9 for MAC OSX
          Applix Integra 1.2.2
          Applix Integra 1.2.3
          Arc + Progress 3.0
          ArchiCAD 9.0
          ArchiCAD 10.0
          ArchiCAD 11.0
          Arcon 5.0
          Arcon 6.5
          Armcade 2005
          ArcSoft Photo Impression 4.0
          ArcView 9.0
          Ardent Data Stage 6.0 R3
          ArendiX RSS Captor 2.31.Pro
          ArendiX RSS Captor 2.33.Pro
          Arete Digital Nature Tools Premiere 4.0 For Maya 3.0
          Aris Easy Design And Toolset 5.0 & Windows Db Server 6.0
          ARM Developer Suite 1.2
          Art Explosion Greeting Card Factory 2.0
          ArtiCAD PRO 10.1
          Artlantis 4.5
          ASC Integrity Data Re-Enginering Environment 4.0
          Ascential Datastage 7.0
          Ascential Datastage 7.1
          Ascential Datastage XE 6
          Ascential Datastage 6.0.1 R4
          Ascential Integrity 6
          Ascential Meta Stage 6.1 R3
          Ascential Metastage 6.1 R8
          Ascential Metastage 7.0 R4
          Ascential MetaRecon 6.1
          Ascential Quality Stage Designer 7.0
          Aspen Engineering Suite 12.1
          Aspen Tech Aspen Engineering Suite 11.1
          Aspen Tech Aspen Framework 2.3
          Aspen Tech Aspin ICARUS Products 12.0
          Asymetrix Tool Book Assistant 8.6
          Asymetrix Tool Book Instructor 8.6
          Aucotec Elcad 7.1
          Auto Eye 2.0
          Auto Fx Photographic Edges 6.0
          Autodesk Architectural Desktop 2005
          Autodesk Architectural Desktop 2006
          Autodesk Architectural Desktop 2007
          Autodesk AutoCAD 2005
          Autodesk AutoCAD 2006
          Autodesk AutoCAD 2007
          Autodesk AutoCAD 2008
          Autodesk AutoCAD Architecture 2008
          Autodesk AutoCAD Electrical 2005
          Autodesk AutoCAD Electrical 2006
          Autodesk AutoCAD Electrical 2007
          Autodesk AutoCAD Electrical 2008
          Autodesk AutoCAD Land Devlopment Desktop R2I
          Autodesk AutoCAD LT 2004
          Autodesk AutoCAD LT 2006
          Autodesk AutoCAD LT 2007
          Autodesk AutoCAD LT 2008
          Autodesk AutoCAD Mechanical 2005
          Autodesk AutoCAD Mechanical 2006
          Autodesk AutoCAD Mechanical 2007
          Autodesk AutoCAD Mechanical 2008
          Autodesk Building Electrical 1.0.
          Autodesk Building Mechanical 1.0.
          Autodesk Building System R3
          Autodesk Building Systems 2005
          Autodesk Building Systems 2006
          Autodesk Building Systems 2007
          Autodesk Civil 3D 2004
          Autodesk Civil 3D 2006
          Autodesk Civil 3D 2007
          Autodesk Civil Design 2005
          Autodesk Civil Design 2006
          Autodesk Civil Design 2007
          Autodesk Civil Design Companian 2006
          Autodesk Civil Design Companian 2007
          Autodesk Composer 2005
          Autodesk Envision 7.0
          Autodesk Inventor 8.0
          Autodesk Inventor 9.0
          Autodesk Inventor 10
          Autodesk Inventor Professional 7.0
          Autodesk Inventor Professional 8.0
          Autodesk Inventor Professional 9.0
          Autodesk Inventor Professional 10.0
          Autodesk Inventor Series 6.0
          Autodesk Inventor Series 9.0
          Autodesk Land Desktop 2005
          Autodesk Land Desktop 2006
          Autodesk Land Desktop 2007
          Autodesk Map 3d 2005
          Autodesk Map 3d 2006
          Autodesk Map 3d 2007
          Autodesk Map Series 5
          Autodesk MapGuide 6
          Autodesk MapGuide 6.5
          Autodesk Mechanical Desktop 2004
          Autodesk Mechanical Desktop 2006
          Autodesk Mechanical Desktop 2007
          Autodesk Raster Design 2004
          Autodesk Raster Design 2005
          Autodesk Raster Design 2006
          Autodesk Raster Design 2007
          Autodesk Revit 4.5
          Autodesk Revit 5.0
          Autodesk Revit Series 6.1
          Autodesk Survey 2005
          Autodesk Survey 2006
          Autodesk Survey 2007
          Autodesk VIZ 2005
          Autodesk VIZ 2006
          Autodesk VIZ 2007
          Autodesk VIZ 2008
          Autodesk VIZ 4.2 incl. SP2
          AutoExpert 4
          Automation Studio 5.0 Pro
          Autoxplorer 7.5.0
          Avellino Discovery 3.2
          Avery Design Pro 5
          AVID ALIENBRAIN STUDIO V7.1.1
          Avid DS HD 6.1
          Avid Express 5.0
          Avid Newscutter XP 5.3
          Avid SoftImage 3D 4.0
          Avid SoftImage XSI 2.0.2
          Avid SoftImage XSI 4.0
          Avid Xpress Pro 4.3.5
          Avid Xpress Pro 4.5.1
          Avid Xpress Pro 4.6
          AVL Workspace Suite 4.0
          Barcode Generator 2.0
          Barcode Generator 2.62
          BARTENDING ONLINE V1.0
          BARUDAN TES 3.0
          BCAD Designer 3.8
          BCGSoft Professional Editor 6.75
          BCL All PDF Converter 2.01for Windows
          Bea Weblogic Integration 8.1.3
          Bea Weblogic Integration 8.5
          Bea Weblogic Platform 8.1.3.
          Bea Weblogic Portal V8.1.3
          Bea Weblogic Server V8.1.3
          Bea Weblogic Workshop 8.1.3
          Bee Line Artprofile V 3
          Bentley Architecture 8
          Bentley AutoPIPE v6.30
          Bentley Explorer 2004
          Bentley GeoPak Civil Engineering Suite 2001
          Bentley Geopak Rebar 2004 Edition
          Bentley InRoads Suite 2004
          BENTLEY INROADS V8 3
          Bentley Microstation v.8 2004 Edition
          Bentley Microstation 8.1
          Bentley Microstation 8.5
          Bentley Projectwise 3.8
          Bentely Redline 8.1
          Bernina Artista 3.0
          Bernina Artista 4.0
          BEST COLOUR PROOFING V5.0
          BEST Screenproof 5.0.0
          Better Homes and Gardens Home Designer Suite 6.0
          Biographic Technologies Ai Implant 1.0. for Maya
          Biz Plan Builder 8.0
          Biz Plan Builder 8.1
          BizPrac Professional 5.03 WinAll
          BLUE RIDGE NUMERICS CFDESIGN V8.0
          Blueberry 3D Terrain Tools 1.0
          BluffTitler DX9. 2.01 for Windows
          BluffTitler DX9. 2.02 for Windows
          BMC Distribution Server 7.1.0
          BMC Patrol Storage Management Nodes 7.1.01 for Unix/Win NT2K
          BMW Etk 2004 Multilanguage
          BOBWIRE V19.3
          BobCAD-Cam 19.6
          BobCAD-Cam 19.7
          BobCAD-Cam 20.5
          Bocad 3D 19
          Bocad 3D 20
          Boomerang Digital Photo Album 2004.Edition v5
          Bookmark Buddy 3.2.4
          Bookmark Buddy 3.2.5
          Boris Continuum Complete 3.0
          Boris FX 6.0
          Boris FX 7.0
          Boris FX 8
          Boris Red 2.5
          Boris Red 3.0
          Borland C# Builder Architect Edition 1.0
          Borland C++ Builder 6.0 Enterprise Edition
          Borland C++ BuilderX 1.0 Enterprise Edition
          BORLAND C SHARP BUILDER ENTERPRISE V1.0
          Borland Delphi 2005 Architect
          Borland Delphi 2006 Architect
          Borland Delphi 8 Architect
          Borland Delphi 8 Enterprise
          Borland Delphi 8 Professional
          Borland Delphi 7 Studio Companion Tools
          Borland Delphi 7 Studio Enterprise
          Borland JBuilder 2005 Enterprise
          Borland JBuilder 2006 Enterprise
          Borland JBuilder 2007 Enterprise
          Borland JBuilder X Enterprise 10.0
          Borland JBuilder X Enterprise WebLogic Edition 10.0
          Borland JDataStore 7
          Borland StarTeam 6.0
          Borland Together Architect 2006
          Borland Together for Eclipse v6.3
          Breault ASAP 7.5
          Breault ASAP 8.0
          Broderbund 3D Home Architect Landscape Design Deluxe 6X
          Broderbund 3D Home Architect Professional 5.0
          Broderbund 3D Home Design Deluxe 6.0
          Broderbund 3D Home Design Suite Professional
          Broderbund Media Shop Digital Studio 2
          Broderbund Movie Shop Deluxe 6.5
          Broderbund PrintShop Pro Publisher Deluxe 15
          Broderbund Professional Business Labels 5.03
          Broderbund The Print Shop Resume Pro Deluxe
          Business Objects 5.1.4
          Business Objects 11
          Business Plan Pro 2005
          Business Plan Pro 2006
          Business Plan Pro 2007
          Business Plan Pro Premier Edition 2005
          Business Plan Pro Premier Edition 2006
          Business Plan Pro Premier Edition 2007
          Business Plan Writer Deluxe 8.0 2005
          Business Plan Writer Deluxe 2006
          Business Suite Deluxe 2nd Edition
          CNC Mastercam CAD 9.0
          Cabinet Vision Solid 3.5
          CAD Fix 5.0
          CAD Fix 5.2
          Cadence Allegro SPB Release 15.5
          Cadence Silicon Package Board Codesign v.15.2
          Cadence IC Design 5.0 for Linux
          Cadence Logic Design And Verification 5.0
          Cadence Logic Design And Verification 5.1
          Cadence Orcad Unison Suite Pro 10.0
          Cadence Pcb Design Studio 15.0
          Cadance Pcb Design Studio 15.1
          CAD Link SignLab 7.1
          CAD Link SignLab e6 Revision 1
          CAD Link Vision Pro 6
          Cadison Pipes 4.12
          CADraster Ltx 5.10 for Autocad
          CADraster Pro 5.10 for Autocad
          CADS Hyper Steel 7.1 SP1
          CADSoft EAGLE 4.13 Professional
          CADSoft Envisioneer 1.0
          CADWorx 2006
          CakeWalk Club Tracks 2.0.1
          Cakewalk Home Studio 2004X
          Cakewalk Home Studio XL 2004
          Cakewalk MediaWorks
          Cakewalk Music Creator 2.0
          Cakewalk Music Creator 2.0X
          CakeWalk Music Creator 2003
          CakeWalk Music Creator Pro 24
          CakeWalk Plasma 2003
          CakeWalk Project 5
          Cakewalk Pyro 2004X
          Cakewalk Pyro Plus 2005
          Cakewalk Sonar 3 Producer Edition
          Caligari Truespace 6.0
          Caligari Truespace 6.5
          Calyx Point 4.3
          Calyx Point 4.4
          Cambridge Animation Systems Animo 5.0
          Cambridge Animation Systems Animo 6.0
          Cambridge Soft Chemoffice Ultra 2005
          Canon Digital Camera Solution 7.1
          Canopus Edius 1.0
          Canopus Edius 2.0
          Canopus Imaginate 2.0
          Canopus Lets Edit 1.0
          Canopus Photoalbum 2.0
          Canopus Procoder 1.5
          Canopus Procoder 2.0
          Canopus Procoder Express 1.0
          Canopus Xploded Professional 4.0
          Captaris Rightfax 8.5
          Cara 2.2 Plus
          Cardiff Liquid Office Form Designer 3
          Cardiff Liquid Office Form Server 3
          Casemaker DBMaker 4.1 SP3
          Casemaker DBMaker 4.1.3 LINUX
          Casemaker DBMaker 4.1.3 SOLARIS
          Cast for Unigraphics 18.0
          Cast for Unigraphics NX 3.0
          Catia 5R8
          Catia 5R9
          Catia 5R16
          Catia Smarteam Pdm 4.0
          Ccvision Car Special 11
          CD DVD Analyse 3.01
          CD DVD Diagnostic 2.1.3
          CEI Ensight 7.6.6 GOLD
          CEI Ensight 7.6.6 GOLD for MAC
          CF Design 6
          CFX 5.6
          CFX 5.6 SP1
          CFX BladeGen Plus v 4.0
          CFX Bladegen Plus 4.1 Aea Technology
          CGtech Vericut 5.1
          CGtech Vericut 5.2
          CGtech Vericut 5.3
          CGtech Vericut 5.4
          Chem 3D 2005
          ChemCAD 5.2
          ChemOffice Ultra 2004
          ChemStation ChemCAD 5.2
          Chief Architect 9.0
          Chief Architect 9.5
          Chief Architect 10
          Ciber Control Pro 4.0 Multilanguage
          CIM-Team E3 Series 2004
          CIMAgraphi 7
          CIMatrion Elite 5.0
          CIMatrion Elite 5.1
          CIMatron Elite 6.0 with SP2
          Cimatron IT 13.0
          Cimatron IT 13.1
          Cimatron Quck NC 4.0
          Cimatron Quck NC 4.1
          Cinegy Extreme 6.0
          Cisco Works for Windows 6.1
          Cisco Works QoS Policy Manager 3.1
          Cisco Works VPN-Security Management Solution 2.2
          Cisco Ciscoworks Hosting Solution Engine 1.8
          Cisco Ciscoworks Lan Management Solution 2.2
          Cisco Ciscoworks Routed Wan Management Solution 1.3
          Cisco Systems Call Manager 3.2a
          Citrix Metaframe XP Enterprise Edition 1.0
          Civiltech Allpile 6.2
          Civiltech Liquefy Pro 4.3K
          Civiltech Shoring Suite 7.4K
          Civiltech Superlog 4.0
          Clarion 5.5
          ClarkConnect Office 2.1
          Classon Demand Lightwave 3D Character Builder vol 1
          Cocreate Designer Modeling 13
          Cocreate Net Model Explorer 2004 12
          Cocreate Onespace Data Management 12.0
          Cocreate Onespace Designer Drafting 12.0
          CODE 9.50
          CODEsoft 7.10 Enterprise
          Componentone Studio Q4. 2002
          Computer Associates ARCserve Back up 11
          Computer Associates BrightStor ARCserve Backup 9.01 for Windows
          Computer Associates BrightStor ARCserve Backup for Laptops & Desktops
          11.0
          Computer Associates BrightStor Mobile Backup 4.0
          Computer Associates Brightstore Storage Resurse manager 6.4
          Computer Associates eTrust Antivirus 7.0
          Computer Associates eTrust Secure Content Manager 1.0
          Compuware Devpartner Studio Professional Edition 7.
          Compuware Optimal J 2.1.04 with Optimal Server 6.5
          Compuware Qaload 5.0
          Compuware Soft ICE Driver Suite
          Comsol Femlab 2.2
          Comsol Femlab 2.3
          Comsol Femlab 3.0
          Comsol Femlab 3.1
          Comsol Femlab 3.2
          Concept Draw Professional 1.8
          Concept Draw Professional 5.2
          Concept XL 2.5 SR2
          Corel Bryce 3D 5.1 R4
          Corel Draw 12
          Corel Draw Graphics Suite 12
          Corel Painter 8.0
          Corel Painter 8.0 for MAC
          Corel Painter 8.1
          Corel Photobook 10.3
          Corel PrintHouse 6.0
          Corel R.A.V.E. 2
          Corel Ventura 10
          Corel Word Perfect Family Pack 5
          Corel Word Perfect Office 11 Standart Edition
          Corel XMetal 4.0.3
          Coretechnologie 3D Evolution 1.0
          Cosmopolitan Virtual Makeover Deluxe 3
          Cosmos Design Star 4.0
          Cosmos Feature Supressor 1.0
          Cosmos Flow 4.1
          Cosmosworks 2004
          Cosmosworks 2006
          Crystal Analysis Professional 9.0 Multilanguage
          Crystal Analysis Professional 10.0 Multilanguage
          Crystal Enterprise 10.0
          Crystal Reports Professional 10.0
          CSC Fastrak 9.0
          CSC Structual Office 6.2
          CSC Tedds 7.0
          CSI Etabs Nonlinear 8.11
          CSI Etabs Nonlinear 8.13
          CST Design Studio 2
          CST Design Studio 3
          CST EM Studio 2.0
          CST Mafia 4.1
          CST Microwave Studio 5.0
          CST Microwave Studio 5.1
          Cubus Suite 4.0
          Curious Labs Poser 5.0. for MAC OSX
          Curious Software Curious World Maps 3.5
          Curious World Maps 4.5
          Curious World Maps 6.0
          Cyberlink Power Cinema 3.0 for WinXP
          Cyberlink Power Director 3.0
          CyberLink Power DVD 5 Gold Edition
          CyberLink Power Producer 2.0
          Cyberlink Video Live Mail 4.0
          C Module Viewer 4.0
          C Module Viewer 4.1
          Dalet 5.1E
          Dassault Systems CATIA 5 R12 SP4
          Dassault Systems CATIA 5 R13 SP4
          Dassault Systems CAA CATIA 5 R14
          Dassault Systemes Caa Rade 5R14
          Dassault Systems CATIA User Companion for Dmu 5R13
          Dassault Systems CATIA User Companion for Design 5R13
          Dassault Systems CATIA User Companion for Mechanical Design 5R13
          Dassault Systems CATIA User Companion for Strutural Analysis 5R13
          Dassault Systems DELMIA Multicax 5R14
          Dassault Systems ENOVIA 3D Com 5R14
          Dassault Systems ENOVIA Dmu Navigator 5R14
          Dassault Systems ENOVIA Vpm Navigator 5R14
          Dassault Systems Smarteam 4.0 SP 5.5
          Data Becker Complete Home Designer 5
          Data Becker Digital Sound Planet Music Center Live 3.0
          Data Becker PDF Producer 1.0
          Data Becker Photo Center 2.4
          Data Links 1.0
          Database Architect 1.2.2
          Database Tour 4.9.3.6
          Database Tour 4.9.4.4
          Database Tour 4.9.5.2
          Datastage 7.5
          Datastage XE 5.1
          Dazzle DVD Complete Deluxe 2.02
          DBF To XML 1.0
          DBF To XML 1.1
          DB Reader 1.8
          DEC Superscan II
          Deep Paint 3D 2.0
          Deform 3D 4.03
          Deform 3D 5.03
          Deksi Network Inventory 3.5.0
          Deksi Network Inventory 3.5.1
          Delcam ArtCAM Pro 5.509 C
          Delcam ArtCam 6.008
          Delcam ArtCam Pro 7
          Delcam ArtCam Pro 8
          Delcam ArtCam Pro 9
          Delcam Artcam Insignia 3.5
          Delcam Artcam Jewelsmith 7.1
          Delcam CopyCad 5.002
          Delcam CopyCad 6.0
          Delcam Power Mill 4.1
          Delcam Power Mill 4.5
          Delcam Power Mill 5.5
          Delcam PowerShape 5.2
          Delcam PowerShape 5.4
          Delcam PowerShape 5.6
          Delmia VMAP 5R9
          DeltaGraph 5.4
          Deluo Routis 2004
          Designer CAD 3D Max 14
          Designer CAD 3D Max 15
          Desktop DNA 4.6
          Desktop DNA 4.7
          Desktop DNA 6.4 Enterprise
          DialogBlocks 1.58
          DialogBlocks 1.68
          Dicad Starcon 4.3
          Digital Anarchy 3D Layer 1.0 for AE
          Digital Anarchy Backdrop Designer Full 1.0 for Photoshop
          Digital Element WorldBuilder Pro 3.55
          Digital Fusion 3.0
          Digital Fusion 4.0
          Dimsoln Combined 3D 3.6.1
          Dimsoln Foundation 3D 3.8.5
          Dimsoln Mat 3D 3.8.4
          Discreet 3DSMAX 6.0
          Discreet 3DSMAX 7.0
          Discreet 3DSMAX Unplugged 2005
          Discreet 3DSMAX Unplugged 2006
          Discreet Cleaner XL 6.01.401
          Discreet Combustion 3
          Discreet Edit 6.5
          Discreet Plasma 1.0
          Discus 3.0.3 for MAC OSX
          Dolphin Smash 5.3.3
          Dolphin Smash 5.3.3 for LINUX
          Downstream CAM350 8.5
          Downstream CAM350 8.51
          DP Technology Espirit 2003
          Dragon Naturally Speaking Medical Solutions
          Dragon Naturally Speaking Pro 6
          Dragon Naturally Speaking Pro 7.1
          Dream FlashSee 1.1
          Dream FlashSee 1.2
          Driver Guide Toolkit 1.1
          DSC Gosteel 4.1 for ACAD
          Dynamic Designer Motion Pro 2005
          E-Campaign Corporate 3.2
          E-Press Easy Office 7.1
          e-book, PDF Autodesk Autocad 2004-2006
          e-book, PDF Autodesk Electrical 2004-2006
          E3 Series 2002 PLUS
          E3 Series 2002
          E3 Series 2003
          Easy Gradebook 3.5
          Easy Sign 4
          Easy Sign 4.5
          EagleWare GENESYS 2005
          Easy Translator Deluxe 4
          Easy Gradebook v3.5
          EBP Assistant Particulier 2005 RETAIL
          ECS CAD Standalone 4.00
          Edge CAM Part Modeler 9.75
          Edge CAM 8.0
          Edge CAM 8.75
          Edge CAM 9.5
          EDS Courses Guide For Unigraphics NX V2.0
          EDS Design Shop 2004
          EDS Design Shop 2005
          EDS Factory 8.0
          EDS Factory 8.3
          EDS Femap 8.3
          EDS I-Deas V9M2 PTF2 Update
          EDS I-Deas V10M1PTF1 Update
          EDS I-Deas NX 11
          EDS Imageware 11
          EDS Imageware 11.1
          EDS Imageware NX 12.1
          EDS Solid Edge 14
          EDS Solid Edge 15
          EDS Solid Edge 16
          EDS Solid Edge 17
          EDS Solid Edge 18
          EDS Team Center Engineering iMAN 8.0 for Unigraphics 1
          EDS Team Center Engineering IMAN 8.1
          EDS Teamcenter Visualization 5.0
          EDS Teamcenter Visualization 5.1
          EDS Unigraphics NX 2.0
          EDS Unigraphics NX 3.0
          EGS Featurecam 9.3
          Elcut 4.1
          Elcut 4.2
          Electric Image Animation System DVD 5.5.1
          Electronic Workbench 10
          Elibrium My Database 6.5
          Emagic Logic Audio Platinum 5.3
          Embarcadero DT Studio 1.8
          Embarcadero ER Studio 6.5
          Embird 2004
          Embird 2005
          Embird 2006
          Emedia Guitar Method 2
          EMC ControlCenter 5.2
          Empirix Onesight 4.6
          Entirex Xml Gateways 7.2.2
          Entirex Xml Mediator 7.3.1
          Eon Studio 5.0
          Eon Studio 5.2
          Eonreality Eon Professional For Eon Studio 5.11
          Eovia Amapi 3D 6
          Eovia Amapi Pro 7.1
          Eovia Carrara Studio 2 for PC and MAC
          Epcon Chem Pro Engenering Suite 6.31
          EPLAN Professional 5.4 SP1
          EPLAN Professional 5.5
          ERDAS Imagine 8.6
          ERDAS Imagine 8.7
          ERDAS Imagine 9.0
          ERM Er Mapper 6.4
          ESI CFDRC 2004
          ESI Pam Crash 2G 2004
          ESI Pam Stamp 2G 2003
          ESPRIT 2002 Plus incl. SP4
          ESRI ArcGIS 4 for Red Hat Linux
          ESRI ArcGIS 4 for Windows NT/2K/XP
          ESRI ArcGIS Desktop 8.3
          ESRI ArcGIS Desktop 9.0
          ESRI ArcGIS Workstation 8.2
          ESRI ArcGIS Workstation 8.3
          ESRI ArcIMS 4.0.1
          ESRI ArcSDE Client 8.2
          ESRI ArcSDE Client 8.3
          ESRI ArcView 8.1
          ESRI Business Map Pro 3
          ESRI MapObjects 2.2
          ETA Dynaform 5.1
          ETAP Power Station 4.0
          ETAP Power Station 5.0
          ETAP Power Station 5.5
          ETRUST AUDIT 1.5 SP3
          ETRUST OCS PRO 2.0 P1
          EuroCut CoCut Professional 11.0
          EuroCut CoCut Professional 12.0
          Euronav Sea Pro 2000 3.505
          Execntive Software Disk Alert Administrator 2.0
          Exceed 7.0
          Extensis Portfolio 6.1 for MAC OSX
          Extensis Suitcase 10.2.1 for MAC OSX
          Extra Drive Creator Professional 3.1
          Extra Drive Creator Professional 3.3
          Eye Matic Face Station 2.0
          Eye-On Digital Fusion 4
          EZ Eudora Backup 1.22
          EZ ThunderBird Backup 1.22
          EZ Video Splicer 1.5.2
          F-secure Policy Manager 5.60
          F-secure Policy Manager 5.60. LINUX
          Faces 3.0 - Photorobot
          Family Lawyer 2004 Deluxe Home And Business
          Family Lawyer 2005 Deluxe Home And Business
          Family Lawyer 2006 Deluxe Home And Business
          Famous 3D Proface Complete 2.5
          FARO CAM 2 v.1.6
          FASTCAD 7.14
          FASTCAD 7.21
          Fashion Cad 2005
          Fastrip 7.8
          Fastrip 8.0
          Favo Audio Converter 5.0
          Favo Audio Editor 5.0
          Favo Video Converter 5.0
          FE - Design Tosca 5.0
          FelixCAD 5 SP6
          FEM Design 4.2
          FEM Tools 2.1.1
          FEMAP 8.2.1
          FEMLAB 3.1
          FEMLAB 3.2
          Filemaker Pro 7.0
          Filemaker Pro 8.0
          Filemaker Pro 8.5
          Filemaker Developer 7 for Win MAC
          Film Fix For AE 6 Plus 1.0
          Final Cut Pro 4 DVD for MAC OSX
          Final Cut Pro 5 DVD for MAC OSX
          Final Draft 6.0
          Final Draft 7.0
          Final Draft 8.0
          Final Draft 7 for MAC OSX
          Finale 2005
          Finale 2006
          Finale 2007
          Finecut 5.01
          Finereader 7.0 Professionl
          Finjan Vital Security Suite 7.0
          Flexign 7.5 Pro
          Flexign 7.6 v. 2
          Flitestar 8.5
          Flomerics Flotherm 4.1
          Flomerics Flotherm 4.2
          Flow 3D 8.2
          Flowscience Flow 3D 8.0
          Flowscience Flow 3D 8.1
          Fluent Fidap 8.7.2
          Fluent Fidap 8.7.2 LINUX
          Fluent Fidap 8.7.4
          FLUENT ICEPAK 4 0
          FLUENT MIXSIM 2.0.2
          Fluent 6.1
          Fluent 6.0 LINUX
          FM 7.0 Native Instruments
          FME Suite 2004 ICE3
          FME Suite 2003 X2
          Focus GCSE 6.0
          Focus Photoeditor 4.0.1
          Focus Photoeditor 4.0.2
          Focus RedShift 5
          Folio 7.5E
          Fonix I-Speak 3
          Formsys MaxSurf 9.52
          Form Z Radiozity 3.9
          Form Z Radiozity 4.1
          Form Z Radiozity 5.0
          Form Z Radiozity 5.5
          Form Z Radiozity 6.0
          Franklin Software Advanced Development System 8.63
          Fruity Loops Studio Producer Edition 4.1
          FTP Bullet 2.43
          Functionbay Recurdyn 5.1 SP1
          Furnace 1.0 v.2 for ADOBE AE
          Fxray 5.0 For Felixcad
          G6 FTP Server 3.1.0 Professional
          GAEA POLLUTE 7.061
          GAEA WINLOG 4.34
          GaebGetter Professional 2.9
          Gamma Tech GT Suite 5.2
          Garmin MapSource 5.4
          GARMIN MAPSOURCE METROGUIDE EUROPE 7
          Genius Inventor 6.0
          Genius Inventor 7.0
          Geo Pack 2001
          Geo Pak Civil Engineering Suite 2000
          Geo Pak Civil Engineering Suite 2001
          Geo Express 4.0
          Geo Magic Studio 6.0
          Geo Magic Studio Qualify 6.0
          Geo Magic Studio Qualify 7.0
          Geo Slope Office 5
          GEOSOLVE WALLAP 5.03
          Geo System Delta 5
          Gerber Accumark Professional 8.1
          GFI FAXmaker 12
          GFI Network Server Monitor 6
          GGU STABILITY 7.05
          GGU TRENCH 5.10
          GHI HMO Pharmaceutical Business And Provider Directory 2005
          GibbsCAM 2004 v.7.0
          GibbsCAM 2005
          GibbsCAM 2005 v.7.7
          GibbsCAM 2006
          GibbsCAM 2006 v.8.0.13
          Gigasampler Studio 2.5
          GIZA Pro 2002
          GIZA Pro 2003
          Glasspalace Multimedia Vegas 5
          Global Star Digital Darkroom Photo Editor 2.1
          Graitec Advance Steel Suite 4.2 SP1
          GRAFIS 9
          Graphisoft Archicad International 7.0
          Graphisoft Archicad International 8.0
          Graphisoft Archicad International 9.0
          Graphisoft Archicad International 10
          Graphisoft Archicad 8.1 R1 International
          GretagMacbeth ProfileMaker Pro 5.0.4
          GT Suite 6.0
          GT Suite 6.1
          GUS Multimedia Speech System 10
          Haestad Flowmaster 2005
          Haestad Methods Sewercad 5.0
          Haestad Methods Hammer 7.0
          Haestad Methods Stormcad 7.0
          Haestad Methods Watercad 6.0
          Hallmark Card Studio 2004X
          Hampson Russel CE V5 R6
          HARDATA DINESAT RADIAL V 4.5
          Hardata Dinesat 7.0.3.5
          Hash Animation Master 2004 11.0P
          Hash Animation Master 2005 11.1D Plus Netrender Edition
          HDL Entry EASE v.6.0 R3
          HEAL v.8.1
          HeartSounds Basic Cardiac Auscultation v.3.0
          HEAT Service and Support v.8.0
          Heidelberg Signastation 8.0.1
          Hellas Navigator 2005 MASTER
          Helicon Filter 1.61.Pro
          Helicon Focus 2.03.Pro
          Henzo Photo Studio Multilingual
          HEXTRAN 8.11
          HKS ABAQUS v.6.4
          HOME BREW KIT MASTER v.1.6
          Home Design Quick And Easy 3.0
          Home Plan Pro 4.5.26
          Home Plan Pro 4.5.29
          Houdini Master 6.0
          HP Open View Data Storage Protector 5.1
          HP Open View Network Node Manager Advance 7
          HP Open View Network Node Manager Advance 7.1
          HTFS 2001
          HTFS 2004
          HTFS 2006
          Hummingbird DM Suite 5.0.
          Hummingbird DOCSFusion Suite 4.0.1
          Hummingbird Exceed 7.1.1
          HUMMINGBIRD EXCEED 3D v.11 2006
          HUMMINGBIRD EXCEED POWERSUITE v.11 2006
          Hypercad 8.4
          Hyperion Enterprise 5.1
          Hyperion Essbase Suite 6.0
          HyperSteel 6
          HyperSteel 7
          HyperSteel Release 7
          HyperSteel 7.1 SP1
          Hyprotech Hysys 3.1
          Hyprotech Hysys 3.2
          HYSYS 2004
          HYSYS 2004 Manuals
          HYSYS 2006
          I-DEAS 9
          I-DEAS NX 10
          I-DEAS 11
          I-DEAS NX 12
          I-DEAS 8 M2A
          I-LOGIX Rhapsody 4.1 MR2
          I-LOGIX Rhapsody 5.0
          I-LOGIX Statemate 3.2
          IAR EWAVR 310C PRO ISO
          IBAAN CRM DBSYNC SERVER v.4.3 SP2
          IBAAN E-configuration Enterprise 5.2
          IBI Webfocus Desktop Suite 5.22
          IBM Communications Server 6.1.2
          IBM DB2 Application Development Clients 8.1 FP3
          IBM DB2 Everyplace Enterprise Edition 7.2 Req.
          IBM DB2 Everyplace Enterprise Edition 8.2
          IBM DB2 Office Connect Web Edition 4.0 TC1
          IBM DB2 UDB Enterprise Edition 8.2
          IBM Enterprise Information Portal 8.2
          IBM Lotus Domino Server 6.5
          IBM Online Analysis Processing Server 8.0
          IBM Personal Communications 5.7.1
          IBM Screen Customizer 2.0.70
          IBM Tivoli NetView 7.1.3
          IBM Tivoli Web Site Analyzer 4.5
          IBM WebSphere Application Server 5.1
          IBM WebSphere Application Server 5.1 LINUX
          IBM WebSphere Business Integration Adapters 2.3.1
          IBM WebSphere Commerce Business/Professional Edition for Linux 5.4
          IBM WebSphere Development Tools for iSeries 5.1
          IBM WebSphere Host On-Demand Toolkit 7.0
          IBM WebSphere Portal Server 5.0
          IBM WebSphere Studio Application Developer 5.11
          IBM WebSphere Studio Application Developer 5.11 FINAL
          IBM WebSphere Studio Site Developer 5.5
          IBM WebSphere Transcoding Publisher 4.0
          IBM WebSphere Translation Server 5.0
          ICEM CFD v.4.2.2
          ICEM Surf 4.3
          ICEM Surf 4.4
          ICEM Surf 4.4 LINUX
          ICEM Surf 4.4 SOLARIS
          IDVDMAX 1.0
          IDVDMAX 1.1
          IGESUG 2 0
          Iges Works 6.0
          Ilight Fieldview 9.1
          Ilight Fieldview 11.0
          Illuminatus Opus Pro 2.6
          Ilog Software Components Suite 5.0
          Image Comparer 2.0
          Image - Pro Plus 4.5
          Image - Pro Plus 5.0
          Image Ware Unilet Pro 6.0.5
          Image - Ware Surfacer and Verdict 10.6
          Imold Works 2.0 for Solidworks
          Imold for Solidworks 2003 SP1
          IMSI Floorplan 3D Design Suite 8
          IMSI Floorplan 3D Design Suite 9.0 ISO
          IMSI Org Chart Professional 1.2
          IMSI Org Plus 4.0 Standard
          IMSI TurboCAD Pro 9.0
          IMSI TurboCAD Pro 11.0
          Incite 3.0
          Incite 3.1
          Inet Form Filler Professional 2.6
          Informatix Piranesi 3.0
          Innovmetric Polyworks 9.0.2
          Insightful S-Plus for Windows 6.1 R1
          Install Shield Admin Studio 5.5
          Install Shield Admin Studio 6.0
          Install Shield Devstudio 9.0
          Install Shield Devstudio 9.01
          Install Shield Demo Shield 7.5
          Install Shield Professional 7.01
          Install Shield X Premier Edition 10.0 SP1
          Instant 3D Landscape Design 2.0
          Instant Stitch: PM Stitch Creator 2.0
          Intergraph INTools Engineering Suite 5.2
          Intec Simpack 8.6.07
          Intec Simpack 8.6.07 Solaris
          Intel Math Kernel Library 7.0.11 Linux
          Intergraph Intools Engineering Suite 5.2
          International Bussines Edition 9
          InterVideo DVDCopy 2.5 Platinum Plus
          InterVideo WINDVD Creator v.2 Platinum
          Intools 6.0
          Intools 6.03
          Intuit Quick Books 2003 Pro Edition
          Intuit Quicken 2005 for MAC OSX
          Intuit Quicken XG 2004
          Inuit QuickTax 2004
          Inus Technology Rapidform 2004
          Inus Technology Rapidform 2004 SP1.5
          Invensys SIM SCI Pro 2 v.5.6.1
          INVENSYS SIMSCI PIPEPHASE v.9.0
          INVESTRONICA 7.4
          Invision Power Board v.2.0.0
          InvoMax 2005 Books Pro
          Iomega Hotburn Burn and Go Professional 2.3
          Iron CAD 6.0
          Iron CAD 7.0
          Iron CAD 8.0
          Ise Tcad 10
          Isight 8.0
          Iso Draw 5.01
          Iso Draw 6.0
          ITASCA 3DEC v.4.0
          ITEDO ISODRAW v.6.0
          IVideoMAX 3.0.5
          IWAY Web Focus Server 5.2
          IWAY Soapswitch 5.5
          Jacs Paint Shop Photo Album 5.0
          Jalasoft Xian 2005 Network Manager (Jalasoft)
          Jasc Affter Shot Premium Edition 1.0
          Jasc Paint Shop Photo Album 5.0
          Jasc Paint Shop Pro 8.0
          Jasc Paint Shop Pro 9.0
          Jasc Paint Shop Pro 9.1
          Jasc Virtual Painter 3
          Jaws PDF Creator 2.1
          Jbuilder 6 Companion Tools
          JewelCAD 4.1
          JewelCAD 4.2
          JewelCAD 5.1
          Kaplan Higher Score Sat Act Psat 2004X
          Kaspersky Anti-Hacker And Anti-Virus Personal 5
          Kaydara Motion Builder Pe 4.02 Video Tutorials
          Kaydara Filmbox 3.2
          Keystone Building Scalable Networks Level 4
          Kristanix Memory Puzzle 1.0
          Kristanix Shuffle Puzzle 1.0
          Kubotek KeyCreator 4.5
          KWP 2000
          LabView 7.0
          LabView 7.1
          LabView 8.0
          LAJ Design Drop Watermark 2.0.2
          LAJ Design E Ordering Pro 2.5.0
          Landesk Management Suite 8
          Language Engineering Power Translator Pro 8.0 Multilanguage
          LapLink Every Ware Deluxe 1.5
          Lattice Isplever 2.0
          Lattice Isplever 3.0
          Leadtools Vector Imaging Pro 14.0 ISO
          LEAP SOFTWARE AXSYS V4.0.0
          LEAP SOFTWARE CONBOX V1.4.0
          LEAP SOFTWARE CONSPAN V3.10
          LEAP SOFTWARE CONSPLICE V1.2.2
          LEAP SOFTWARE GEOMATH V4.4.0
          LEAP SOFTWARE PRESTO V8.6.1
          LEAP SOFTWARE RC PIER V4.01
          LECTRA 5.2
          LECTRA KALEDO STYLE V1 R1 C11
          LECTRA ROMANSCAD 2D V7.0
          LECTRA ROMANSCAD 3D V7.0
          LECTRA ROMANSCAD CUT V7.0
          LECTRA ROMANSCAD SL V7.0
          LECTRA ROMANSCAD SOLE V7.0
          Licom Systems Alphacam 2003
          Licom Systems Alphacam 2004
          Licom Systems Alphacam 2006
          LightTools 4.0
          LightTools 5.0
          LightTools 5.1 incl. SP1
          LightWave 3D 7.5 Lighting Book
          LightWave 3D 8.0
          Lindows OS 4.5
          Lindows OS Click-N-Run Express 4.5
          Lindows CD 4.5
          Linux Office 2000
          Linux Red Hat Advanced Server 2.1
          Linux Slackware 8.0
          Liscad 6.2 Multilanguage
          Lizardtech Geoexpress 4.0
          Lizardtech Geoexpress 5.0
          LJZsoft ExcelReport 1.3
          LJZsoft WordReport 1.3
          LMS TEST LAB V4.0
          LOGA 3.3.2
          LogiXML LGX Info Server 6.1.1
          LogiXML LGX Info Studio 6.1.1
          LogiXML LGX Report Plus Server 6.1.1
          LogiXML LGX Report Plus Studio 6.1.1
          LOGO DESIGN STUDIO 2005
          Loopology v1.0 Adobe Audition 1.0
          Lotus Domino 6.0.1: Enterprise Server
          Lotus Domino 6.0.2: Enterprise Server
          Lotus Extended Search 4.0
          Lotus Learing Space 5.01 Core Mobule
          Lotus Learning Managemens System 1.0.1
          Lotus QuickPlace 3.0.1.
          Lotus Sametime 3.1
          Lotus Team Workplace 6.5.1
          LS Backup PRO v.1.5.1
          Lusas Fea 13.55
          Lusas Fea 13.57
          Luxology Modo 1.0
          Lynda.com Flash Professional 8 New Features
          Lynda.com Learning Illustrator 10.0
          Lynda.com Learning Java Script with Charals & Hocding
          Lynda.com Learning Macromedia Dreamwaver MX
          Lynda.com Learning Photoshop CS
          Lynda.com Learning Quark Xpress 6.0
          Lynda.com Learning Windows XP
          Lynda.com New in Photoshop CS
          Mac OSX 10.2
          Macro Mania 9.3.7
          Macro Mania 9.3.8
          Macromedia Authorware 6.5
          Macromedia Authorware 7
          Macromedia Captivate 1.0
          Macromedia Cold Fusion MX Server 6 Enterprise Edition
          Macromedia ColdFusion MX 7 Enterprise
          Macromedia ColdFusion MX 7 Standard
          Macromedia Contribute Mx 2004 OSX
          Macromedia Contribute 2.0
          Macromedia Contribute 3.0
          Macromedia Director MX 2004
          Macromedia Director MX 2004 10.1
          Macromedia Dreamweaver MX 6.0 2004
          Macromedia Dreamweaver 8.0
          Macromedia Essentials MX 2002
          Macromedia Fireworks 8.0
          Macromedia Fire Works MX 6.0 2004
          Macromedia Flash MX Professional 2004
          Macromedia Flash Professional 8.0
          Macromedia Flash MX Professional 2004 7.2
          Macromedia Flash MX Application Development Toolkit
          Macromedia Flash MX Communication Server 1.0
          Macromedia Flex 1.0
          Macromedia Freehand 10
          Macromedia HomeSite 5.5
          Macromedia JRun 4.0 for Windows/Linux
          Macromedia Studio MX 2004 for Mac OSX
          Macromedia Studio MX 2004
          Macromedia Studio 8
          MagiCAD 2003.3
          MagiCAD 2003.5
          MagicDraw UML Enterprise 8.0
          MagicDraw UML Enterprise 8.0 for MAC OSX
          Magix Audio Cleaning Lab 2005
          Magix Audio Cleaning Lab 2006
          Magix Audio Cleaning Lab 2005 DELUXE
          Magix Audio Cleaning Lab 2006 DELUXE
          Magix Guitar Workshop 2nd EDITION
          Magix Movie Maker Deluxe 3.0
          Magix Digital Photo Maker 2004
          Magix Digital Photo Maker 2006
          Magix Photo Cleaning Lab 1.0
          Magix Movie Edit Pro 2004
          Magix Movie Edit Pro 2005
          Magix MP3 Maker Deluxe 2005
          MAGIX MP3 Maker Titanium 2004
          Magix Music Maker 2005 Deluxe
          Magix Music Studio 2005 Deluxe
          Magix Music Studio 2006 Deluxe
          Magix Video Deluxe Plus 2
          Mak Software Suite 3.2
          Mak Software Suite 4.0
          Mak Stealth 5.2A
          Mandrake Linux 10.0 PowerPack
          MapInfo Mapx Mobile 5.0
          MapInfo Mapx Treme Java Edition 4.0
          MapInfo Professional 7.0
          MapInfo Professional 7.5
          Maplesoft Maple 9.5
          Maptech Chart Navigator 5.0.2
          Mastercam Art 9.0
          Mastercam 9.1 SP2
          Mastercam X 10.0
          MASTERCAM X V10.2 MR2
          Mastercam X 10.0 SP1
          Mastercook Deluxe 7.0
          Materialise Magics RP 9.0
          Materialise Magics 9.9
          Materialise Magics Tooling 5.1
          MathCAD 12
          MathCAD 13
          Mathematica 5.1
          Mathematica 5.2
          Mathsoft MathCAD 12
          Mathworks Matlab 6.5
          Mathworks Matlab 6.5.1
          Mathworks Matlab 7.0.1 R14 SP1
          MatLab 7.0 Mathworks R14
          Matrix 3d v4
          Matrix 3d v5
          Matrix42 Empirum Pro 9.5.2
          Matrix42 Empirum Pro 9.5.3
          Maximizer 8.0
          Maxon Bodypaint 3D R2 8.206
          Maxon Bodypaint 3D 2.0 for MAC OSX
          MAXON CINEMA 4D V8
          Maxon Cinema 4D Release 8 Studio Bundle for MAC OSX
          Maxon Cinema 4D XL With Bodypaint 3D 7.1
          Maxon Dynamics 1.0. for Cinema 4D XL 7.2
          Maxsurf 10.5
          Maxsurf Pro 8.5
          McAfee Alert Manager 4.7.1
          McAfee Internet Security Suite 6.0
          McAfee Personal Firewall Plus 2005
          McAfee Personal Firewall Plus 2006
          McAfee SpamKiller 2005
          McAfee SpamKiller 2006
          McAfee Super Pack 5.0 Professional
          McAfee VirusScan Home Edition 2005
          McAfee VirusScan Home Edition 2006
          McAfee VirusScan Professional 8.0
          McAfee VirusScan Professional 9.0
          MCGRAW HILL SIMNET EXCEL TUTOR 2004
          Mechanical Dynamics Adams 12.0
          MECHSOFT FOR AUTODESK INVENTOR SERIES 5.3
          Mechsoft for Inventor 8.0
          Mechsoft Productivity Pack for Inventor 8.0
          Mechsoft for Solidedge 15
          MECHSOFT MECHANICAL DESIGN PACK FOR NX2
          MediSoft: Network Professional 9.0
          MediSoft: Network Professional 10.0
          MediSoft: Office Hours Professional 7.02
          Melco Eds 2.0
          Melco Eds 3.0
          Memscap Mems Pro 4.0
          Mental Ray 3.0.5 for MAYA 4
          Mentor Graphics E Product Designer 3.0
          MENTOR GRAPHICS HDL DESIGNER V2004.1B
          MENTOR GRAPHICS HDL DESIGNER V2005.2
          Mentor Graphics HyperLynx 7.5
          MENTOR GRAPHICS MODELSIM SE V6.0C
          MENTOR GRAPHICS MODELSIM SE V6.1B
          MENTOR GRAPHICS POWERPCB WITH BLAZE ROUTER V5.0.1
          Mentor Graphics Sdd 2004
          Mentor Graphics Wg 2004
          Mercury Interactive Loadrunner 7.6
          Mercury Interactive Quick Test Pro 6.5
          Mercury Winrunner 7.5
          Mercury Winrunner 8.0
          MetaStock Professional 9.0
          MetaStock Professional 10
          Metrowerks Code Warrior Pro 8
          Metrowerks Code Warrior Pro 9.3
          Microimages Tnt 6.8
          Microimages Tnt 6.9
          Micromat Techtool Pro 4.01 for MAC OSX
          Microsoft Autoroute 2005
          Microsoft Business Solutions CRM Suite 1.0
          Microsoft Business Solutions CRM Suite 1.2
          Microsoft Business Solutions Small Business Manager 7.5
          Microsoft Encarta 2005
          Microsoft Encarta Reference Library Premium 2005
          Microsoft LCS 2005 Standard Edition RC SUB 100
          Microsoft Money Premium 2005
          Microsoft Money Small Business 2005
          Microsoft Navision Axapta 3.0
          Microsoft Office 2004 for MAC OSX
          Microsoft Office Publisher 2003
          Microsoft Office System Professional 2003
          Microsoft Office XP Professional 2001
          Microsoft Operations Manager 2005 SP1
          Microsoft Project Server 2003
          Microsoft Proofing Tools 2003
          Microsoft SharePoint Portal Server 2003
          Microsoft System Center Reporting Manager 2005
          Microsoft Solution for Internet Business 1.0
          Microsoft Speech Server 2004 Enterprise Edition
          Microsoft Virtual PC 2004
          Microsoft Virtual Server 2005
          Microsoft Visio 2003 Proffesional
          Microsoft Visual Basic 2005
          Microsoft Visual J++ 6.0
          Microsoft Visual Studio 2005
          Microsoft Windows XP Professional
          Microsoft Windows XP Professional Corporate incl SP2
          Microsoft Windows XP Tablet PC Edition 2005
          Microsoft Windows Vista Ultimate
          Microsoft Works Suite 2004
          Microsoft Works 7
          Microsoft Works 8
          MicroSurvey CAD 2002
          Microwave Office 2002
          Microwave Studio 5.0
          Midas Civil 6.3
          Midas Set 3.2.1
          Missler TopSolid 2003 6.5
          Mitsubishi GX Developer 7 and Simulator 6
          MixMan Studio Pro 4.0
          MKS Toolkit for Interoperability 8.5
          ModelSim SE v.5.8A
          ModelSim SE v.6.0
          Moldflow Plastics Insight 4.0.1
          MOLDFLOW WORKS 1.1 R1
          Monarch 7 Professional Edition (Datawatch)
          Monarch 7 Standard Edition (Datawatch)
          MSC ADAMS 2003
          MSC ADAMS 2005
          MSC ADAMS 2005 R2
          MSC Construct 3.0
          MSC Dytran 2004
          MSC Dytran 2005
          MSC Easy 2004
          MSC Easy 5 v.7.1
          MSC Enterprise Mvision 2004
          MSC Fatigue 2004
          MSC Fatigue 2005 for Patran 2005
          MSC FEA AFEA 2005 R2
          MSC Interactive Physics 2004
          MSC Marc 2005
          MSC Nastran 2004 R3
          MSC Nastran 2005
          MSC Patran 2004
          MSC Patran 2005
          MSC Simdesigner 2004 R2 for CATIA 5R12
          MSC Simdesigner 2004 R3 for CATIA 5R13
          MSC Simdesigner 2004 R4 for CATIA 5R13
          MSC Superform 2004
          MSC Superform 2005
          MSC Visual Nastran for Windows 2004
          MSC Visual Nastran Desktop 2003
          MSC Visual Nastran Desktop 2004 SP1
          MSDN Library for Visual Studio Net 2003
          MSDN UNIVERSAL 7 0
          MSN 9 Gold Edition Final
          Multiactive Maxiwizer 7.0 Enferprise Edition
          Multigen Creator Terrain Studio 1.0
          Multigen Paradigm Creator 2.6
          MULTIGEN PARADIGM VEGA PRIME FOR LINUX V1.2
          MULTIGEN PARADIGM VEGA PRIME V1.2
          MULTIGEN PARADIGM VEGA V3.7.1
          Multigen Vega Prime 1.1
          Myob Accountedge 2004 for MAC OSX
          Myob Accountedge 2005
          Myob Premiere 7.5
          Myriad 6.1
          Myriad 6.2
          MYSOFTWARE BOOKKEEPER V3.0.1
          Namo WebEditor 6 Suite
          Nastran 2004.1
          National Instruments Diadem 9.0
          National Instruments Labview 7.0
          National Instruments Labview 7.1 Professional Development System
          National Instruments Measurment Studio 6
          Native Instruments Absynth 1.0
          Native Instruments Absynth 2.0
          Native Instruments Kompakt 1.0
          Nativie Instruments Vokator 1.0
          Natural Xml 6.1.1
          Navis Works 3.0
          Navis Works 3.1
          NC Graphics DEPOCAM 2005
          NC Graphics Depocam 5.0.19
          NC Graphics Depocam 5.0.20
          NC Graphics Depocam 6.0.9
          NC Graphics Machining Strategist 4.0
          NC Micro Router CIM 8.3
          NCODE NSOFT 5.3.1
          NCSS 2004 Statistical Analysis System
          NCSS 9.2
          NE Nastran 8.3
          Nedgraphics Software 2005
          Nedgraphics Carpet Workshop 2004 V2.0.0.0
          Nedgraphics Fashion Studio V5.0.1.4
          Nedgraphics Layer Master V6.0.0.7
          Nedgraphics Print Studio V5.0.1.4
          Nemetschek Allplan 2003.1ą
          Nemetschek Allplan 2005.1ą
          Nemetschek PlanDesign V2004
          Nemetschek Vectorworks 10.0
          Nemetschek Vectorworks 11.0
          Nemetschek Vectorworks 11.0 for MAC OSX
          NeoDVD Plus 3.0.1
          Neopack Professional 2.7
          Nero 6
          Nero Photoshow Elite 1.0X
          NetAdvantage 2005 (Infragistics)
          Netiq App Manager Suite 5.0.1
          Netiq Security Administration Suite 4.1
          Netopia Netoctopus Enterprise 5.0
          NetObjects Fusion 8.0
          NetObjects Fusion 9.0
          NetObjects Fusion 10
          NETOPIA NETOCTOPUS ENTERPRISE V5.0
          Network Associates E Policy Orchestrator 2.5
          Newtek Lightwave 3D 8.0 for MAC OSX
          Nextlimit Flowtracer for Lightwave 1.02
          Nextpage Folio Builder 4.5
          Nextpage Folio Integrator 4.5
          Nextpage Folio Product Suite 4.5
          Nextpage Folio Publisher 4.5
          Nextpage Folio Views 4.5
          Ne Nastran 8.3
          NI-motion 6.1.4
          NI Analog Waveform Editor 1.1
          NI ECU MEASUREMENT AND CALIBRATION TOOLKIT V1.01
          NI LabView Professional v.8.0
          NI SPECTRAL MEASUREMENTS TOOLKIT V2.1
          NI Teststand 3.1
          NI Teststand 3.5
          NI Vision Development Module 7.1.
          NI Vision 7.0 Development Module for Labview
          Nobeltec Admiral 7.0
          Nobeltec Admiral 8.0
          Nobeltec Admiral 9.0
          Nobeltec Visual Navigation Suite 7.0
          Nobeltec Visual Navigation Suite 8.0
          Nobeltec Visual Navigation Suite 8.1
          Nobeltec Visual Navigation Suite 9.0
          Norton AntiSpam 2005
          Norton Antivirus 2005
          Norton Internet Security 2005
          Norton Internet Security 2006
          Norton System Works 2005
          Norton System Works Premier 2005X
          Novell Net Ware 5
          Novell Net Ware 6
          Nozzle Pro 5.2
          NSC Visual Nastran for Catia v5iR9
          Omega CP 2.0.2
          OnTime Enterprise 5.0.5
          Onyx PosterShop 6.0
          Onyx PosterShop 6.5
          Onyx PosterShop 7.0
          Onyx TREE PROFESSIONAL Suite 6
          Open View Storge Data Protector 5.0
          Opticad 5 0
          Opticore Opus Studio 4.1
          Optimal Solutions Sculptor 1.7.1
          Optitex 9.0
          Optitex 9.2
          Optitex 9.5
          Optiwave System 3
          Optiwave BPM 6
          Optiwave FDTD 4
          Oracle Developer Server 6.0
          Oracle Internet Commerce Server Suit 1.1.0.7.5
          Orange Micro WebCam DV 1.0
          Origin Lab Pro 7.0
          Origin Lab Origin Pro 7.5
          OrCAD 9.2 - Complete Suite
          OrCAD 9.23 Cadence
          OrCad 10
          OrCad 10.3
          OrCAD Unison Suite Pro 10
          OrCAD Unison Suite Pro 10.5
          1PRIMAVERA EXPEDITION 8.5
          P-CAD 2004
          P-CAD 2006
          PAD 4.5
          Paint Shop Photo Album 5 (Corel Corporation)
          Paint Shop Pro 9 (Corel Corporation)
          Panda AntiVirus Platinium 7.0
          Panda Platinum Internet Security 8.05 SUB100
          Panda Titanium Antivirus 2005
          Panda Titanium Antivirus 2006
          Panopticum Custom Speed 2.0 for AE
          Paradigm Multigen Creator 2.5
          Paradigm Multigen Vega 3.7
          Paradigm Vega 3.2
          Paradigm Vega 3.7
          Particle Illusion 3.0
          Partmaker 6.0
          Pathloss 4.0
          Pathtrace Edgecam Part Modeler 2.1
          Pathtrace Edgecam 7.0
          Pathtrace Edgecam 8.0
          Pathtrace Edgecam 8.5
          Pathtrace Edgecam 9.0
          Pathtrace Edgecam 9.5
          Pathtrace Edgecam 10.0
          PC Anywhere 10.5
          PC ABEAM 1.5
          PC AMATS 6.1
          PC DNC Suite 3
          PC OMR 4.2
          PC Stitch 6
          PC - DMIS 3.5
          PCI Geomatica 9.0
          PCI Net Support Manager 8.0
          Peachtree Complete Accounting 2005
          Peachtree Complete Accounting 2006
          Peachtree Complete Accounting 2007
          Peachtree by Sage Complete Accounting 2006
          Peachtree by Sage Complete Accounting 2007
          People Soft 8.4 Enterprise Portal
          People Soft People Tools 8.45
          PGI Workstation 5.2
          PG Music Power Tracks Pro Audio 8
          PG Music Power Tracks Pro Audio 9
          PGP Desktop Professional 9
          Phoenics 3.5
          Photo Graphic Edges 6.0
          Photomodeler 4.0
          PhotoPrint 7.5 v.5
          Picasoft Mayka Suite 6.0
          Pinnacle Clean 4.0
          Pinnacle Edition DV 4.02
          Pinnacle Edition 5.0
          Pinnacle Holiwood FX Pro 5.1
          Pinnacle Liquid Edition 5.5 DIRFIX
          Pinnacle Liquid Edition 6.1 ISO
          Pinacle Liquid Edition Upgrade 6
          Pinnacle Impression DVD Pro 2.2
          Pinnacle Instant Copy 8.0
          Pinnacle MP3 Pro 4
          Pinnacle Studio 9 Moviebox Deluxe DVD
          Pinnacle Studio Plus 9.3
          Pinnacle Systems Commotion Pro 4.1
          Pinnacle Systems Liquid Edition 6.0
          Pixel Studio 2.0 SUB 100X
          PlanDesign FT 2003 3.0
          Planit Millennium 8.2
          Planit Millennium 8.3
          Planix Home Design Suite 3D
          Point Line CAD 18.0 Professional
          Pointwise Gridgen 14.02 Multiplatform
          Polar SB 200A Professional 2.0
          PowerCAD Pro 6
          PowerCAD Sitemaster XP 5
          PowerQuest Drive Image 7.01
          PowerQuest Partition Magic 8.05
          PowerQuest V2i Protector 2.01 Desktop Edition
          PowerQuest V2i Protector 2.01 Server Edition
          Precience PCB Navigator 5 ISO
          Prefit 8.5
          Primavera Enterprise 4.0
          Primavera Enterprise 5.0
          Primavera Expedition 8.5
          Primavera Project Planner 3.1
          Print Shop for MAC OSX
          Print WorkShop 2005
          Print WorkShop 2006
          Print WorkShop 2007
          Pro Engineer Wildfire 2002
          Pro Engineer Wildfire Datecode 2003 370
          ProCAD 2D Designer 2004
          ProCAD 2D Designer 2007
          Proclarity Analytics Platform 5.3 Desktop Professional
          PROCLARITY ANALYTICS SERVER 5.2
          Procreate Painter 7.1.357
          ProgeCAD 2006 Professional
          Profile Master 2000 CAM-DUCT 2.26
          Prokon Calcpad 2.0
          Propellerhead Reason 2.5
          Protel 2004 SP2
          Protel DXP 7.0
          PST Driver 2
          Psych Now 2
          PTC Expert Moldbase Extension 4.0 for Pro Enginer 2001
          PTC Expert Moldbase Extension 4.1
          PTC Graphics Library 2001
          PTC ICEM Surf 2002 v.4.2
          PTC Intralink 3.4
          PTC Optegra 6.0 Datecode 2002 500
          PTC Pro Concept 2.0
          PTC Pro Engineer 2003 FIX
          PTC Pro Engineer Routed Systems Designer 5.3
          PTC Pro Engineer Wildfire 2004 2.0
          PTC Pro Intralink 3.2
          PTC Pro/Desktop 2001 SP 1
          PTC Progressive Die Extension 2.1
          PTC Productview 6.0
          PTC Routed Systems Desiguer 2002 3.0
          PTC Optegra 6.0
          PTG Interactive Training Course for Red Hat Linux
          Punch Home Design Architectural Series 3000
          QNX Momentics Professional 6.2.1A
          Quantum 3D Opengvs 4.5
          Quark Xpress 5.0
          Quark Xpress 6.1 Passport
          Quark Xpress 6.1 for MAC OSX
          QuarkXPress 6.5
          QuarkXPress 7.0
          QuarkXPress 7.2 for MAC OSX
          Quemix Utilities 2004.v3.0.2005
          Quest 3D Enterprise Edition 2.0B
          Quest3D 3.0 Professional Edition
          Quest Knowledge Xpert for Oracle Administration 8.0
          Quick Verse 2006 Platinum
          Quickbooks Premier Accountant Edition 2005
          Quickbooks Premier Accountant Edition 2006
          Quickbooks Premier Accountant Edition 2007
          Quickbooks Contractor Pro 2005
          Quickbooks Contractor Pro 2006
          Quickbooks Contractor Pro 2007
          Quickbooks Pro 2005
          Quickbooks Pro 2006
          Quickbooks Pro 2007
          Quickbooks Pro 5.0 for MAC OSX
          Quicken Lawyer 2003 Business Deluxe 2.0
          Quicken Lawyer 2003 Personal 2.0
          Quicken Premier Home and Business 2006
          Quicken Premier Home and Business 2007
          Quicken Legal Business Pro 2005
          Quicken Legal Business Pro 2006
          Quicken Legal Business Pro 2007
          RADAR 9
          Radiant Prometric 8.1
          Rainbow Geomagic Studio 4.1.1
          Raindrop Geomagic Cadmus Fashion 6.0
          Raindrop Geomagic Qualify 6.0
          Raindrop Geomagic Studio 5.0
          Raindrop Geomagic Studio 6.0
          RAINDROP GEOMAGIC STUDIO 8.0
          RAL Digital 3.0 Multilanguage
          Ramint Ram Advanse 5.1
          Rams 2.5
          RasterDesk Pro 6.0
          Rational Robot 2003.6
          RATIONAL ROSE ALL EDITIONS V2003.6.12
          Rational XDE Pro Plus 2002
          Rational XDE Professional Java Edition Release 2
          Readiris Pro 9.0
          Readiris Pro 10
          Readiris Pro 11
          REAL Steel 3.0
          REAL Steel 3.5.0
          REAL Steel 3.5.1
          Realsoft 3D 4.2
          Real Systems Real Server 8.01
          RealViz Matchmover Pro 3.01 - DVD
          RealViz Stitcher 4.0
          RealViz Stitcher 5.0
          RealViz Stitcher 5.5
          RealViz ImageModeler 4.0
          Reanimator XP 9 Disk 3: Multimedia
          Reanimator XP 9 Disk 5: Utilities
          Red Had Linux 9.0
          Red Hat Linux 7.1 Deluxe Workstation
          Red Hat Linux 7.1 Professional
          Red Hat Linux 7.2
          RED HAT ENTERPRISE LINUX AS V3.0
          RED HAT LINUX ADVANCED SERVER V2.1
          REDASOFT VISUAL CLONING V3.0
          Redhouse Dictionary 1.52
          Reiusa Staad Pro 2004
          Reiusa Staad Pro 2005
          RENESAS CC32R V4.30
          RENESAS NC30WA V5.30
          Research IDL 6.1
          Research Watsyn 1.5
          Rhinocerus 3D 2.0
          RHINOCEROS V3.0.WITH FLAMINGO V1.1
          Ricardo Software Wave 5.1
          Ricardo Vectis 3.8
          Ricardo Wave 7
          RichPeace Design Pro 2000 4.1
          RichPeace Design Pro 2000 4.28
          Right Hemisphere Deep Paint 3D 2.0
          Right Hemisphere Deep Paint 3D 2.1
          RISA TECHNOLOGIES RISA 3D V5.5
          RISA-3D 5.5
          Robo Help Enterprise 2002 R2
          Robot Millennium 17.0
          Robot Millennium 17.0.1
          ROBOT Office 17.5
          ROXAR IRAP RMS V7.3
          Roxio DigitalMedia Studio Deluxe Suite 7.0
          Roxio Easy CD DVD Creator 6.0
          Roxio Easy DVD Copy
          Roxio Easy Media Creator 7
          Roxio Easy Media Creator 7.1
          Roxio Goback 3.03 Deluxe
          Roxio PhotoSuite Platinum 5
          Roxio PhotoSuite Platinum 7.0
          Roxio Toast Titanium 6 for MAC OSX
          Roxio Video Wave Movie Creator 1.5
          Roxio Video Wave 7.0 Professional
          Roxio WinOnCD 6 DVD Edition
          Roxio WinOnCD 6.0 Power Edition
          RS Logix 5 v.5.0
          RS1 CAMCAD Pro v.4.5
          RSI CAMCAD Professional 4.3
          RSI CAMCAD Professional 4.5
          RX Autoimage Pro R7.5
          Safetechnology FE-Safe 5.0
          Samplitude Professional 7.0
          SAP FRONT-END 6.4
          SAS 8 2
          SAS JMP Statistical Discover Software 5.0.1a
          SCAD Office 7.31 R3
          SCAD Office 7.31 R4
          SCAD Office 7.31 R5
          Scan Soft Text Bridge Pro 11
          Scansoft Dragon Naturally Speaking 7
          Scansoft Dragon Naturally Speaking 8
          Scansoft Dragon Naturally Speaking 9
          Scansoft Omnipage Pro 12
          ScanSoft OmniPage 14 Office
          Scansoft Omnipage Professional 15 Multilangual
          Scansoft Paper Port Deluxe 9.0
          Scanvec Amiable Flexisign Pro 7.5 v.2
          Scanvec Amiable Flexisign Pro 7.5 v.3
          Scanvec PhotoPrint 3.02
          Scanvec PhotoPrint Server Pro 4.05
          SCIA ESA PT V4.5 AND ESA PW V3.6
          SCIA ESA PT V5.2
          Schlumberger Pipesim 2003 1.0
          Schlumberger Pipesim 2006 1.0
          SCO Open Server Enterprise System 5.0.6 A
          Scrapbook Factory Deluxe 2.0X
          Screenblast Acid 4.0
          Screenblast Movie Studio 3.0
          Seakeeper 15
          Seagate Crystal Reports 8.5
          Semcad 1.8
          Serif Draw Plus 7.0X
          Serif DVD Plus 1.0X
          Serif Impact Plus 4.0
          Serif Impact Plus 5.0
          Serif Learn To Draw 7.0X
          Serif Media Plus 1.0
          Serif Media Plus 2.0
          Serif Page Plus 8.0
          Serif Page Plus 9.0X
          Serif PhotoPlus 9.0
          Serif Web Plus 8.05
          Serif Web Plus 9.0
          Shade 7.1 Professional for MAC OSX
          Sibelius 2.0
          Sibelius 3.0
          Sibelius 4.0
          Side FX Houdini 5.5 Final
          Side FX Houdini 6.0
          Siebel Financial Services 7.03 Bookshelf
          Siebel Financial Services 7.03 Web Client Programs
          Siebel Financial Services 7.03 Windows Server Programs
          SignCut 2002
          Signsoft Intellibo 3.6
          Sign Tools 3
          Siemens SIMATIC Step7 Professional Edition 2004 SR3
          Siemens SIMATIC Step7.Professional Edition 2004
          Siemens SIMATIC Step7 Professional Edition 2006
          Simply Accounting Pro 2005
          Simply Accounting Pro 2006
          Simply Accounting Pro 2007
          SIMSCI PRO II 7.1
          SIMSCI PRO II 6.0
          Sofistik Soficad 2004 16.3
          Softimage 3D Realistic Character Development 1
          Softimage 3D Realistic Character Development 2
          Softissimo Lexibase Pro 5.1
          SOFTTECH STRUDS V2005
          Softplan 11
          Softplan 12
          Softplan 13
          Softpress Systems Freeway 3.5 for MAC
          Solaris 8
          Solid Edge 9.0 Service Pack 4
          Solid Edge 15
          Solid Edge 16
          Solid Edge 17
          Solid Edge 18
          Solid Edge 19
          Solid Works 2004
          Solid Works 2005
          Solid Works 2006
          Solid Works 2007
          Sonic RecordNow Deluxe Suite 7.0
          Sonic ReelDVD 3.0
          Sonic Stylus Studio 5.3
          Sonnet Suite Pro 9.5.2
          Sony Sound Forge 7.0
          Sony Sound Forge 8.0
          Sony Vegas Plus DVD Production Suite 5.0
          Sound Forge 6
          Sound Quest Infinity 2.05a
          SPAM Reporter 2.0
          SPAN 8 5
          Speedsix Monsters v.5 For Digital Fusion
          Speedsix Speedo v.1.1 For Digital Fusion
          SPSS 12.0
          SPSS 14.0
          SPSS 15.0
          SPSS Clementine 6.5
          SPX Instant Screen Capture 5.0
          SPYEX 1.0
          SPRUTCAM V4.0
          SQUARE ONE ECOTECT V5.2B
          Srac Cosmos Designstar 3.0
          SRAC Cosmos FloWorks 2006
          SRAC Cosmos FloWorks 2007
          SRAC Cosmos Works 2006
          SRAC Cosmos Works 2007
          Srac Cosmos Works 7
          STAAD Pro 2006
          StarOffice 7 Office Suite
          StatSoft Statistica 6.0 Multilanguage
          STATISTICA 7
          Steinberg Cubase SX 2.0
          Steinberg Cubase SX 2.2
          Steinberg Nuendo 2.0
          Steinberg Nuendo 3.0
          Steinberg Virtual Guitarist VST 1.0
          Steinbichler Cometinspect 2.0
          Steinbichler Cometplus 5.1
          Sticth Pro 2004
          Stitch Vista 2005
          Stitch Vista 2006
          StimCADE 2.0
          Storage Central 5.0
          Strata 3D Pro 3.5
          Strucad Pro 10.1
          Strucad Pro 10.2
          Strucad Pro 11.0
          Strydent Inksaver 2.0
          Studioline Photo 2.0
          StudioView Interactive Virtual Pose 2
          Sun Java Studio Enterprise 6 2004Q1
          Sun Java Studio Enterprise 6 2004Q1
          SUN JAVA STUDIO ENTERPRISE V6.0
          Sun Star Office Suite 7.0 Linux
          Surf Ware SurfCam 2003
          SURFWARE SURFCAM VELOCITY V2005 SP1
          SuSE Linux 9.1
          Suse Linux Enterprise Server 8
          Swarshala 2.0
          Swift Software Cosmi Forms Maker Flow Charts and Labels 7.0
          Swift Software Cosmi Perfect Video and Photo Editor Platinuim 1.0
          Sybase Power Builder Enterprise 9.0
          Sybase Power Designer Studio Enterprise 10.0
          Symantec Antivirus Corporate Edition 9
          Symantec Collection 2003
          Symantec Enterprise Firewall 8
          Symantec Enterprise Security Manager 6.0
          Symantec Ghost 8.0
          Symantec Net Recon 3.6
          Symantec Norton AntiSpam 2004
          Symantec Norton Antivirus 2005
          Symantec Norton Internet Security 2005
          Symantec Norton Internet Security 2006
          Symantec Norton System Works 2005
          Symantec Norton System Works 2006
          Symantec Norton System Works 3.0 for Mac OSX
          Symantec Norton Utilities 8.0 for Mac OSX
          Synapticad Allproducts 10.01B
          Synapticad Allproducts 10.02A
          Synopsys Saber Designer 2003 6
          Synplicity Certify 6.4
          Synplicity Synplify Pro 7.6.1
          Synplicity Synplify 8.0
          Synplicity Synplify 8.1
          Synthetik Studio Artist 2.0 for MAC OSX
          System Mechanic Pro 4.0F
          System Mechanic Professional v5.0
          System Mechanic Professional v5.0a
          Systran Premium 4.0 Multilingual
          Systran Professional Premium 3.0
          Systran Professional Premium 5.0
          T-FLEX 3D 6.2
          T-Flex 7.0
          T-Flex 7.1
          T-FLEX CAD 8.0
          T-Flex Parametric CAD 7.2
          T-SYSTEMS MEDINA 7.3.2
          Tally Solutions Tally EES 6.3
          TECHMASTER 2006
          Tecnomatix Empower 7.2
          Tekla Structures 10.0
          Tekla Structures 12.0
          Tekla Xsteel 8.2
          Tekla Xsteel 9.0
          Tekla Xsteel 10.1
          Tekla Xsteel 11.1
          Tekla Xsteel 12
          Teksoft CAM Works 2003
          Teksoft CAM Works 2007
          Teksoft CAM Works 2006 for Solid Works 2006
          Teksoft PROCAM 2 2003
          Teksoft PROCAM 2 2006
          Terra Vista 3.0
          TestTrack Pro v6.1.6 Linux
          TestTrack Pro v6.1.6 for MAC OSX
          T-FLEX 7.2
          T-FLEX CAD 8.0
          TGS Amira 3.11
          Thermoanalytics Radtherm 7.1.1
          Thermoanalytics Wintherm 7.1.1
          Thermoflow 13.0
          Think 3 ThinkDesign 8.2
          Think 3 ThinkDesign 9.0
          ThunderSite DeLuxe 3.0
          TI C5000 Code Composer Studio 2.0
          TI Code Composer Studio 2.2 for C6X
          Tibeis CAD/CAM 3.1 R12
          Timber Creek Software Sold v.5.1.44 WinAll
          Timbuktu Pro Enterprise 2.1.4
          Tinderbox1 V1.3 v.1 for Adobe AE
          Tinderbox2 V1.2 v.1 for Adobe AE
          Tinderbox3 V1.0 v.2 for Adobe AE
          Tivoli Monitoring Tools 5.1
          Tivoli NetView 7.1
          Tivoli Risk Manager 4.2 Multiplatform
          Tivoli Storage Manager 4.2.1 Client and Server
          Toolbox for Solidworks 2005
          Toolbox for Solidworks 2006
          Torchmate CAD Module 5.3 R12
          TOTALCAD 2D 3D
          Total 3D Home & Landscape Design Suite
          Total 3D Home Deluxe 6.0
          Total 3D Landscape Deluxe 6.0
          Total Training Adobe Acrobat 6
          Total Training for Adobe After Effects 6 Set3 DVD4
          Total Training for Adobe Photoshop 7.0
          Total Training for Adobe Photoshop 7.0 Basics Special Edition
          Trace Pro 3.0
          Trace Pro 3.2.2
          Trade Power Suite 8.1
          TRADESTATION PROSUITE 2000i PLATINUM EDITION
          Trados 6.5 Freelance
          Trados 7.0 Freelance
          TRANSDAT 9.02
          Translogic Ease 5.2 R10 and Eale 5.2 R8
          Translogic HDL Entry Ease 6.0 R1
          Trans Magic Plus 2005
          Trans Trainer for C# NET Windows 1.1
          TREPCAD St3 3.2.1
          Trillium Software System 7
          Turbo Linux Server Edition 6.0.4
          Turbo Linux Workstation Edition 6.04
          TurboCAD Deluxe 9.2
          TurboCAD Deluxe 10.1
          TurboCAD Pro 7
          TurboCAD Pro 10.1
          TurboCAD Pro 11.2
          UG NX 3
          UGS FEMAP 9.0
          UGS IMAGEWARE 12.0 ISO
          UGS NX V3.0 DOKUMENTATION ISO
          UGS Solid Edge v.17 Update 3
          UGS Solid Edge v.18
          UGS Unigraphics 18
          Ulead Cool 3D Studio 1.0
          Ulead Cool 3D 3.5
          Ulead DVD Movie Factory 3.5
          Ulead DVD Picture Show 2.0
          Ulead DVD Workshop 2.0
          Ulead Gif Animator 5
          Ulead Media Studio Pro 7
          Ulead Photo Impact 8.0
          Ulead Photo Impact 11.0
          Ulead Photo Show 3 Deluxe
          Ulead Video Studio 8
          Ultra Flex Express 7.5
          Ultra Flex 7.5 for STIKA
          Unigraphics NX 2.0
          Unigraphics NX 3.0
          Unigraphics NX 4.0
          Unigraphics ProductVision 3.0
          Unigraphics Upgrade 18.0.2.1
          UNIGRAPHICS 19
          UTS Advanced Spring Design 6.0
          V-Com Fix-It Utilities 5.0
          V-Communications Webeasy Professional 4.0
          V-Communications Webeasy Professional 5.0
          Value SAP Edition 2
          Vantage Plant Design Management System 11.5
          Vaps Suite 6.3
          Vaps Ccglite 6.3
          Vaps Designdoc 6.3
          Vaps Simulink 6.3
          Varimetrix VX 6.51
          Vcom Web Easy Professional 5.0X
          Vector Works Landmark 10
          Vectorworks 11
          Vectorworks 12
          Ventana Vensim Ple 5.1B
          Verias Primo DVD 2.0 Multilingual
          Vericut 5.2
          Veritas Backup Exec 9.1
          Veritas Backup Exec 10
          Veritas Net Backup Datacenter 4.5 FP3
          Veritas Net Backup Datacenter 4.5 MP6
          Veritas Netbackup Enterprise Server UNIX V5.0
          Veritas Netbackup Enterprise Server 5.0
          Veritas Storage Replicator 2.11 SP3
          Veritas Storage Reporter 3.5
          Veritas Netbackup Pro 3.6
          Veritas Volume Replicator 3.1
          Vero Machining Strategist 5.0
          Vero Machining Strategist 6.0
          Vero VISI Series 11.0
          Vero VISI Series 11.1
          Vero VISI Series 11.2
          Vero VISI Series 11.3
          Vero VISI Series 14 SP1
          Vero VISI Server 10.1
          Versa Check 2003 Platinum 7.0
          Versa Check 2004 Platinum
          Verscta Studio 5.5.0.11: Corba Edition
          Vicon Animation Suite 2.0
          Vicon Software Suite 2.0
          Vicon IQ 1.0
          Vicon IQ 1.5
          VINYL MASTER PRO 2.5
          Virtools Dev 2.1
          Vision Numeric Type 3 v.4.4
          Vision Numeric Type 3 v.4.5
          Vision Numeric Type 3 v.4.6
          VISION TYPE 3 NUMERIC 5.0
          Visual Fortran 6.6
          Visual Mill 5.07
          Visual Studio 6.0
          Vitec PC 4.1
          VIZRT V2.7 PL4
          Voxit Budgie Pro 1.0 Multilingual
          Voyetra Audio Station 2004
          Voyetra Audio Surgeon 5
          Voyetra Record Producer 5.0.4X
          VTC Autocad 2005 for Architects
          VTC Autocad 2006 for Architects
          VX Cad Cam 8.31 22
          VX Cad Cam 9.51
          VX Cad Cam 11.21
          WaterGEMS 2005
          WaterGEMS V.8 EDITION
          Web Focus Developer Studio 5.2.5.
          WebGain VisualCafe Expert Edition 4.5.2
          WebSphere Commerce Express Linux 5.5
          Webshop Platinum 2004 v.9
          WHISQU Signcut 1.63
          WinDVD Creator 2 Platinium
          Wilcom 8.0
          Wilcom 9.0
          Wilcom 9.2
          Wilcom ES-65 2006
          Wilcom 2007
          WinDVD Platinum 4.5
          WINDRIVER WORKBENCH v2.3.1
          WINNOZZLE v3.0
          WINPROVEX ADRESSBUCH 5.10
          Winternals Administrators Pack 4.0 Enterprise Edition
          Wise Package Studio 4.6 Enterprise Edition
          World Book Encyclopedia 2004 Deluxe Edition
          World Book Encyclopedia 2007 Deluxe Edition
          WORLEY LABS FPRIME V2.0
          WORLEY LABSG2 V1.7 FOR LW
          Xsteel 8.0
          Xsteel 8.1
          Xsteel 8.2
          Xsteel 8.3
          Xsteel 9.0
          Xsteel 9.1
          Xsteel 10.0
          Xsteel 11.0
          Yamaha Vocaloid Leon 1.0.
          Yamaha Vocaloid Lola 1.0.
          ZAXWERKS 3D FLAG AE V1.0.0
          ZAXWERKS 3D FLAG PP V1.0.0
          Zend Performance Suite 3.5
          Zend SafeGuard Suite 3.1
          Zend Studio 2.6
          ZenSCAD 4.3
          Zend Studio Client 3.5.1
          Zuken CADStar 5.0
          Zuken CADStar 6.0
          Zuken CADStar 7.0
          Zuken CADStar 8.0This is not our complete software list. If you want to get access to our
          Software archive you should visit our website:



          >> Contact e-mail:


          ProSof...@yahoo.com

          or

          ProSof...@yahoo.com*** Sent via Developersdex ***

          -

          Cubase 7 5 Dongle Emulator Crack


          Download Zip --->>> https://urlcod.com/2uyXeQ



          aaccfb2cb3
          -
          -
          \ No newline at end of file diff --git a/spaces/utec/FedericoRodriguezDetectorSentimentalTwitter/app.py b/spaces/utec/FedericoRodriguezDetectorSentimentalTwitter/app.py deleted file mode 100644 index 06bc0582639e36ebadaf5232e672590515bc07b8..0000000000000000000000000000000000000000 --- a/spaces/utec/FedericoRodriguezDetectorSentimentalTwitter/app.py +++ /dev/null @@ -1,5 +0,0 @@ -import gradio as gr - -examples = [["INPUT: I feel so sad"], ["OUTPUT: SAD"]] - -gr.Interface.load("huggingface/cardiffnlp/twitter-roberta-base-emotion",title="Mi Primer Demo", examples=examples).launch(); \ No newline at end of file diff --git a/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/ultralytics/yolo/engine/exporter.py b/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/ultralytics/yolo/engine/exporter.py deleted file mode 100644 index 5d236272bc33fdaf5354feb7f7176473c83dbe49..0000000000000000000000000000000000000000 --- a/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/ultralytics/yolo/engine/exporter.py +++ /dev/null @@ -1,922 +0,0 @@ -# Ultralytics YOLO 🚀, AGPL-3.0 license -""" -Export a YOLOv8 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit - -Format | `format=argument` | Model ---- | --- | --- -PyTorch | - | yolov8n.pt -TorchScript | `torchscript` | yolov8n.torchscript -ONNX | `onnx` | yolov8n.onnx -OpenVINO | `openvino` | yolov8n_openvino_model/ -TensorRT | `engine` | yolov8n.engine -CoreML | `coreml` | yolov8n.mlmodel -TensorFlow SavedModel | `saved_model` | yolov8n_saved_model/ -TensorFlow GraphDef | `pb` | yolov8n.pb -TensorFlow Lite | `tflite` | yolov8n.tflite -TensorFlow Edge TPU | `edgetpu` | yolov8n_edgetpu.tflite -TensorFlow.js | `tfjs` | yolov8n_web_model/ -PaddlePaddle | `paddle` | yolov8n_paddle_model/ -NCNN | `ncnn` | yolov8n_ncnn_model/ - -Requirements: - $ pip install ultralytics[export] - -Python: - from ultralytics import YOLO - model = YOLO('yolov8n.pt') - results = model.export(format='onnx') - -CLI: - $ yolo mode=export model=yolov8n.pt format=onnx - -Inference: - $ yolo predict model=yolov8n.pt # PyTorch - yolov8n.torchscript # TorchScript - yolov8n.onnx # ONNX Runtime or OpenCV DNN with --dnn - yolov8n_openvino_model # OpenVINO - yolov8n.engine # TensorRT - yolov8n.mlmodel # CoreML (macOS-only) - yolov8n_saved_model # TensorFlow SavedModel - yolov8n.pb # TensorFlow GraphDef - yolov8n.tflite # TensorFlow Lite - yolov8n_edgetpu.tflite # TensorFlow Edge TPU - yolov8n_paddle_model # PaddlePaddle - -TensorFlow.js: - $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example - $ npm install - $ ln -s ../../yolov5/yolov8n_web_model public/yolov8n_web_model - $ npm start -""" -import json -import os -import shutil -import subprocess -import time -import warnings -from copy import deepcopy -from pathlib import Path - -import torch - -from ultralytics.nn.autobackend import check_class_names -from ultralytics.nn.modules import C2f, Detect, RTDETRDecoder -from ultralytics.nn.tasks import DetectionModel, SegmentationModel -from ultralytics.yolo.cfg import get_cfg -from ultralytics.yolo.utils import (ARM64, DEFAULT_CFG, LINUX, LOGGER, MACOS, ROOT, __version__, callbacks, colorstr, - get_default_args, yaml_save) -from ultralytics.yolo.utils.checks import check_imgsz, check_requirements, check_version -from ultralytics.yolo.utils.downloads import attempt_download_asset, get_github_assets -from ultralytics.yolo.utils.files import file_size -from ultralytics.yolo.utils.ops import Profile -from ultralytics.yolo.utils.torch_utils import get_latest_opset, select_device, smart_inference_mode - - -def export_formats(): - """YOLOv8 export formats.""" - import pandas - x = [ - ['PyTorch', '-', '.pt', True, True], - ['TorchScript', 'torchscript', '.torchscript', True, True], - ['ONNX', 'onnx', '.onnx', True, True], - ['OpenVINO', 'openvino', '_openvino_model', True, False], - ['TensorRT', 'engine', '.engine', False, True], - ['CoreML', 'coreml', '.mlmodel', True, False], - ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True], - ['TensorFlow GraphDef', 'pb', '.pb', True, True], - ['TensorFlow Lite', 'tflite', '.tflite', True, False], - ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', True, False], - ['TensorFlow.js', 'tfjs', '_web_model', True, False], - ['PaddlePaddle', 'paddle', '_paddle_model', True, True], - ['NCNN', 'ncnn', '_ncnn_model', True, True], ] - return pandas.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU']) - - -def gd_outputs(gd): - """TensorFlow GraphDef model output node names.""" - name_list, input_list = [], [] - for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef - name_list.append(node.name) - input_list.extend(node.input) - return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp')) - - -def try_export(inner_func): - """YOLOv8 export decorator, i..e @try_export.""" - inner_args = get_default_args(inner_func) - - def outer_func(*args, **kwargs): - """Export a model.""" - prefix = inner_args['prefix'] - try: - with Profile() as dt: - f, model = inner_func(*args, **kwargs) - LOGGER.info(f'{prefix} export success ✅ {dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)') - return f, model - except Exception as e: - LOGGER.info(f'{prefix} export failure ❌ {dt.t:.1f}s: {e}') - return None, None - - return outer_func - - -class Exporter: - """ - A class for exporting a model. - - Attributes: - args (SimpleNamespace): Configuration for the exporter. - save_dir (Path): Directory to save results. - """ - - def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None): - """ - Initializes the Exporter class. - - Args: - cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG. - overrides (dict, optional): Configuration overrides. Defaults to None. - _callbacks (list, optional): List of callback functions. Defaults to None. - """ - self.args = get_cfg(cfg, overrides) - self.callbacks = _callbacks or callbacks.get_default_callbacks() - callbacks.add_integration_callbacks(self) - - @smart_inference_mode() - def __call__(self, model=None): - """Returns list of exported files/dirs after running callbacks.""" - self.run_callbacks('on_export_start') - t = time.time() - format = self.args.format.lower() # to lowercase - if format in ('tensorrt', 'trt'): # engine aliases - format = 'engine' - fmts = tuple(export_formats()['Argument'][1:]) # available export formats - flags = [x == format for x in fmts] - if sum(flags) != 1: - raise ValueError(f"Invalid export format='{format}'. Valid formats are {fmts}") - jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, ncnn = flags # export booleans - - # Load PyTorch model - self.device = select_device('cpu' if self.args.device is None else self.args.device) - - # Checks - model.names = check_class_names(model.names) - if self.args.half and onnx and self.device.type == 'cpu': - LOGGER.warning('WARNING ⚠️ half=True only compatible with GPU export, i.e. use device=0') - self.args.half = False - assert not self.args.dynamic, 'half=True not compatible with dynamic=True, i.e. use only one.' - self.imgsz = check_imgsz(self.args.imgsz, stride=model.stride, min_dim=2) # check image size - if self.args.optimize: - assert not ncnn, "optimize=True not compatible with format='ncnn', i.e. use optimize=False" - assert self.device.type == 'cpu', "optimize=True not compatible with cuda devices, i.e. use device='cpu'" - if edgetpu and not LINUX: - raise SystemError('Edge TPU export only supported on Linux. See https://coral.ai/docs/edgetpu/compiler/') - - # Input - im = torch.zeros(self.args.batch, 3, *self.imgsz).to(self.device) - file = Path( - getattr(model, 'pt_path', None) or getattr(model, 'yaml_file', None) or model.yaml.get('yaml_file', '')) - if file.suffix == '.yaml': - file = Path(file.name) - - # Update model - model = deepcopy(model).to(self.device) - for p in model.parameters(): - p.requires_grad = False - model.eval() - model.float() - model = model.fuse() - for k, m in model.named_modules(): - if isinstance(m, (Detect, RTDETRDecoder)): # Segment and Pose use Detect base class - m.dynamic = self.args.dynamic - m.export = True - m.format = self.args.format - elif isinstance(m, C2f) and not any((saved_model, pb, tflite, edgetpu, tfjs)): - # EdgeTPU does not support FlexSplitV while split provides cleaner ONNX graph - m.forward = m.forward_split - - y = None - for _ in range(2): - y = model(im) # dry runs - if self.args.half and (engine or onnx) and self.device.type != 'cpu': - im, model = im.half(), model.half() # to FP16 - - # Filter warnings - warnings.filterwarnings('ignore', category=torch.jit.TracerWarning) # suppress TracerWarning - warnings.filterwarnings('ignore', category=UserWarning) # suppress shape prim::Constant missing ONNX warning - warnings.filterwarnings('ignore', category=DeprecationWarning) # suppress CoreML np.bool deprecation warning - - # Assign - self.im = im - self.model = model - self.file = file - self.output_shape = tuple(y.shape) if isinstance(y, torch.Tensor) else \ - tuple(tuple(x.shape if isinstance(x, torch.Tensor) else []) for x in y) - self.pretty_name = Path(self.model.yaml.get('yaml_file', self.file)).stem.replace('yolo', 'YOLO') - trained_on = f'trained on {Path(self.args.data).name}' if self.args.data else '(untrained)' - description = f'Ultralytics {self.pretty_name} model {trained_on}' - self.metadata = { - 'description': description, - 'author': 'Ultralytics', - 'license': 'AGPL-3.0 https://ultralytics.com/license', - 'version': __version__, - 'stride': int(max(model.stride)), - 'task': model.task, - 'batch': self.args.batch, - 'imgsz': self.imgsz, - 'names': model.names} # model metadata - if model.task == 'pose': - self.metadata['kpt_shape'] = model.model[-1].kpt_shape - - LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with input shape {tuple(im.shape)} BCHW and " - f'output shape(s) {self.output_shape} ({file_size(file):.1f} MB)') - - # Exports - f = [''] * len(fmts) # exported filenames - if jit or ncnn: # TorchScript - f[0], _ = self.export_torchscript() - if engine: # TensorRT required before ONNX - f[1], _ = self.export_engine() - if onnx or xml: # OpenVINO requires ONNX - f[2], _ = self.export_onnx() - if xml: # OpenVINO - f[3], _ = self.export_openvino() - if coreml: # CoreML - f[4], _ = self.export_coreml() - if any((saved_model, pb, tflite, edgetpu, tfjs)): # TensorFlow formats - self.args.int8 |= edgetpu - f[5], s_model = self.export_saved_model() - if pb or tfjs: # pb prerequisite to tfjs - f[6], _ = self.export_pb(s_model) - if tflite: - f[7], _ = self.export_tflite(s_model, nms=False, agnostic_nms=self.args.agnostic_nms) - if edgetpu: - f[8], _ = self.export_edgetpu(tflite_model=Path(f[5]) / f'{self.file.stem}_full_integer_quant.tflite') - if tfjs: - f[9], _ = self.export_tfjs() - if paddle: # PaddlePaddle - f[10], _ = self.export_paddle() - if ncnn: # NCNN - f[11], _ = self.export_ncnn() - - # Finish - f = [str(x) for x in f if x] # filter out '' and None - if any(f): - f = str(Path(f[-1])) - square = self.imgsz[0] == self.imgsz[1] - s = '' if square else f"WARNING ⚠️ non-PyTorch val requires square images, 'imgsz={self.imgsz}' will not " \ - f"work. Use export 'imgsz={max(self.imgsz)}' if val is required." - imgsz = self.imgsz[0] if square else str(self.imgsz)[1:-1].replace(' ', '') - data = f'data={self.args.data}' if model.task == 'segment' and format == 'pb' else '' - LOGGER.info( - f'\nExport complete ({time.time() - t:.1f}s)' - f"\nResults saved to {colorstr('bold', file.parent.resolve())}" - f'\nPredict: yolo predict task={model.task} model={f} imgsz={imgsz} {data}' - f'\nValidate: yolo val task={model.task} model={f} imgsz={imgsz} data={self.args.data} {s}' - f'\nVisualize: https://netron.app') - - self.run_callbacks('on_export_end') - return f # return list of exported files/dirs - - @try_export - def export_torchscript(self, prefix=colorstr('TorchScript:')): - """YOLOv8 TorchScript model export.""" - LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...') - f = self.file.with_suffix('.torchscript') - - ts = torch.jit.trace(self.model, self.im, strict=False) - extra_files = {'config.txt': json.dumps(self.metadata)} # torch._C.ExtraFilesMap() - if self.args.optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html - LOGGER.info(f'{prefix} optimizing for mobile...') - from torch.utils.mobile_optimizer import optimize_for_mobile - optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files) - else: - ts.save(str(f), _extra_files=extra_files) - return f, None - - @try_export - def export_onnx(self, prefix=colorstr('ONNX:')): - """YOLOv8 ONNX export.""" - requirements = ['onnx>=1.12.0'] - if self.args.simplify: - requirements += ['onnxsim>=0.4.17', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime'] - check_requirements(requirements) - import onnx # noqa - - opset_version = self.args.opset or get_latest_opset() - LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__} opset {opset_version}...') - f = str(self.file.with_suffix('.onnx')) - - output_names = ['output0', 'output1'] if isinstance(self.model, SegmentationModel) else ['output0'] - dynamic = self.args.dynamic - if dynamic: - dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}} # shape(1,3,640,640) - if isinstance(self.model, SegmentationModel): - dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85) - dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'} # shape(1,32,160,160) - elif isinstance(self.model, DetectionModel): - dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85) - - torch.onnx.export( - self.model.cpu() if dynamic else self.model, # --dynamic only compatible with cpu - self.im.cpu() if dynamic else self.im, - f, - verbose=False, - opset_version=opset_version, - do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False - input_names=['images'], - output_names=output_names, - dynamic_axes=dynamic or None) - - # Checks - model_onnx = onnx.load(f) # load onnx model - # onnx.checker.check_model(model_onnx) # check onnx model - - # Simplify - if self.args.simplify: - try: - import onnxsim - - LOGGER.info(f'{prefix} simplifying with onnxsim {onnxsim.__version__}...') - # subprocess.run(f'onnxsim {f} {f}', shell=True) - model_onnx, check = onnxsim.simplify(model_onnx) - assert check, 'Simplified ONNX model could not be validated' - except Exception as e: - LOGGER.info(f'{prefix} simplifier failure: {e}') - - # Metadata - for k, v in self.metadata.items(): - meta = model_onnx.metadata_props.add() - meta.key, meta.value = k, str(v) - - onnx.save(model_onnx, f) - return f, model_onnx - - @try_export - def export_openvino(self, prefix=colorstr('OpenVINO:')): - """YOLOv8 OpenVINO export.""" - check_requirements('openvino-dev>=2022.3') # requires openvino-dev: https://pypi.org/project/openvino-dev/ - import openvino.runtime as ov # noqa - from openvino.tools import mo # noqa - - LOGGER.info(f'\n{prefix} starting export with openvino {ov.__version__}...') - f = str(self.file).replace(self.file.suffix, f'_openvino_model{os.sep}') - f_onnx = self.file.with_suffix('.onnx') - f_ov = str(Path(f) / self.file.with_suffix('.xml').name) - - ov_model = mo.convert_model(f_onnx, - model_name=self.pretty_name, - framework='onnx', - compress_to_fp16=self.args.half) # export - - # Set RT info - ov_model.set_rt_info('YOLOv8', ['model_info', 'model_type']) - ov_model.set_rt_info(True, ['model_info', 'reverse_input_channels']) - ov_model.set_rt_info(114, ['model_info', 'pad_value']) - ov_model.set_rt_info([255.0], ['model_info', 'scale_values']) - ov_model.set_rt_info(self.args.iou, ['model_info', 'iou_threshold']) - ov_model.set_rt_info([v.replace(' ', '_') for k, v in sorted(self.model.names.items())], - ['model_info', 'labels']) - if self.model.task != 'classify': - ov_model.set_rt_info('fit_to_window_letterbox', ['model_info', 'resize_type']) - - ov.serialize(ov_model, f_ov) # save - yaml_save(Path(f) / 'metadata.yaml', self.metadata) # add metadata.yaml - return f, None - - @try_export - def export_paddle(self, prefix=colorstr('PaddlePaddle:')): - """YOLOv8 Paddle export.""" - check_requirements(('paddlepaddle', 'x2paddle')) - import x2paddle # noqa - from x2paddle.convert import pytorch2paddle # noqa - - LOGGER.info(f'\n{prefix} starting export with X2Paddle {x2paddle.__version__}...') - f = str(self.file).replace(self.file.suffix, f'_paddle_model{os.sep}') - - pytorch2paddle(module=self.model, save_dir=f, jit_type='trace', input_examples=[self.im]) # export - yaml_save(Path(f) / 'metadata.yaml', self.metadata) # add metadata.yaml - return f, None - - @try_export - def export_ncnn(self, prefix=colorstr('NCNN:')): - """ - YOLOv8 NCNN export using PNNX https://github.com/pnnx/pnnx. - """ - check_requirements('git+https://github.com/Tencent/ncnn.git' if ARM64 else 'ncnn') # requires NCNN - import ncnn # noqa - - LOGGER.info(f'\n{prefix} starting export with NCNN {ncnn.__version__}...') - f = Path(str(self.file).replace(self.file.suffix, f'_ncnn_model{os.sep}')) - f_ts = str(self.file.with_suffix('.torchscript')) - - if Path('./pnnx').is_file(): - pnnx = './pnnx' - elif (ROOT / 'pnnx').is_file(): - pnnx = ROOT / 'pnnx' - else: - LOGGER.warning( - f'{prefix} WARNING ⚠️ PNNX not found. Attempting to download binary file from ' - 'https://github.com/pnnx/pnnx/.\nNote PNNX Binary file must be placed in current working directory ' - f'or in {ROOT}. See PNNX repo for full installation instructions.') - _, assets = get_github_assets(repo='pnnx/pnnx') - asset = [x for x in assets if ('macos' if MACOS else 'ubuntu' if LINUX else 'windows') in x][0] - attempt_download_asset(asset, repo='pnnx/pnnx', release='latest') - unzip_dir = Path(asset).with_suffix('') - pnnx = ROOT / 'pnnx' # new location - (unzip_dir / 'pnnx').rename(pnnx) # move binary to ROOT - shutil.rmtree(unzip_dir) # delete unzip dir - Path(asset).unlink() # delete zip - pnnx.chmod(0o777) # set read, write, and execute permissions for everyone - - cmd = [ - str(pnnx), - f_ts, - f'pnnxparam={f / "model.pnnx.param"}', - f'pnnxbin={f / "model.pnnx.bin"}', - f'pnnxpy={f / "model_pnnx.py"}', - f'pnnxonnx={f / "model.pnnx.onnx"}', - f'ncnnparam={f / "model.ncnn.param"}', - f'ncnnbin={f / "model.ncnn.bin"}', - f'ncnnpy={f / "model_ncnn.py"}', - f'fp16={int(self.args.half)}', - f'device={self.device.type}', - f'inputshape="{[self.args.batch, 3, *self.imgsz]}"', ] - f.mkdir(exist_ok=True) # make ncnn_model directory - LOGGER.info(f"{prefix} running '{' '.join(cmd)}'") - subprocess.run(cmd, check=True) - - yaml_save(f / 'metadata.yaml', self.metadata) # add metadata.yaml - return str(f), None - - @try_export - def export_coreml(self, prefix=colorstr('CoreML:')): - """YOLOv8 CoreML export.""" - check_requirements('coremltools>=6.0') - import coremltools as ct # noqa - - LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...') - f = self.file.with_suffix('.mlmodel') - - bias = [0.0, 0.0, 0.0] - scale = 1 / 255 - classifier_config = None - if self.model.task == 'classify': - classifier_config = ct.ClassifierConfig(list(self.model.names.values())) if self.args.nms else None - model = self.model - elif self.model.task == 'detect': - model = iOSDetectModel(self.model, self.im) if self.args.nms else self.model - else: - # TODO CoreML Segment and Pose model pipelining - model = self.model - - ts = torch.jit.trace(model.eval(), self.im, strict=False) # TorchScript model - ct_model = ct.convert(ts, - inputs=[ct.ImageType('image', shape=self.im.shape, scale=scale, bias=bias)], - classifier_config=classifier_config) - bits, mode = (8, 'kmeans_lut') if self.args.int8 else (16, 'linear') if self.args.half else (32, None) - if bits < 32: - if 'kmeans' in mode: - check_requirements('scikit-learn') # scikit-learn package required for k-means quantization - ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode) - if self.args.nms and self.model.task == 'detect': - ct_model = self._pipeline_coreml(ct_model) - - m = self.metadata # metadata dict - ct_model.short_description = m.pop('description') - ct_model.author = m.pop('author') - ct_model.license = m.pop('license') - ct_model.version = m.pop('version') - ct_model.user_defined_metadata.update({k: str(v) for k, v in m.items()}) - ct_model.save(str(f)) - return f, ct_model - - @try_export - def export_engine(self, prefix=colorstr('TensorRT:')): - """YOLOv8 TensorRT export https://developer.nvidia.com/tensorrt.""" - assert self.im.device.type != 'cpu', "export running on CPU but must be on GPU, i.e. use 'device=0'" - try: - import tensorrt as trt # noqa - except ImportError: - if LINUX: - check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com') - import tensorrt as trt # noqa - - check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0 - self.args.simplify = True - f_onnx, _ = self.export_onnx() - - LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...') - assert Path(f_onnx).exists(), f'failed to export ONNX file: {f_onnx}' - f = self.file.with_suffix('.engine') # TensorRT engine file - logger = trt.Logger(trt.Logger.INFO) - if self.args.verbose: - logger.min_severity = trt.Logger.Severity.VERBOSE - - builder = trt.Builder(logger) - config = builder.create_builder_config() - config.max_workspace_size = self.args.workspace * 1 << 30 - # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice - - flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) - network = builder.create_network(flag) - parser = trt.OnnxParser(network, logger) - if not parser.parse_from_file(f_onnx): - raise RuntimeError(f'failed to load ONNX file: {f_onnx}') - - inputs = [network.get_input(i) for i in range(network.num_inputs)] - outputs = [network.get_output(i) for i in range(network.num_outputs)] - for inp in inputs: - LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}') - for out in outputs: - LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}') - - if self.args.dynamic: - shape = self.im.shape - if shape[0] <= 1: - LOGGER.warning(f'{prefix} WARNING ⚠️ --dynamic model requires maximum --batch-size argument') - profile = builder.create_optimization_profile() - for inp in inputs: - profile.set_shape(inp.name, (1, *shape[1:]), (max(1, shape[0] // 2), *shape[1:]), shape) - config.add_optimization_profile(profile) - - LOGGER.info( - f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and self.args.half else 32} engine as {f}') - if builder.platform_has_fast_fp16 and self.args.half: - config.set_flag(trt.BuilderFlag.FP16) - - # Write file - with builder.build_engine(network, config) as engine, open(f, 'wb') as t: - # Metadata - meta = json.dumps(self.metadata) - t.write(len(meta).to_bytes(4, byteorder='little', signed=True)) - t.write(meta.encode()) - # Model - t.write(engine.serialize()) - - return f, None - - @try_export - def export_saved_model(self, prefix=colorstr('TensorFlow SavedModel:')): - """YOLOv8 TensorFlow SavedModel export.""" - try: - import tensorflow as tf # noqa - except ImportError: - cuda = torch.cuda.is_available() - check_requirements(f"tensorflow{'-macos' if MACOS else '-aarch64' if ARM64 else '' if cuda else '-cpu'}") - import tensorflow as tf # noqa - check_requirements(('onnx', 'onnx2tf>=1.7.7', 'sng4onnx>=1.0.1', 'onnxsim>=0.4.17', 'onnx_graphsurgeon>=0.3.26', - 'tflite_support', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime'), - cmds='--extra-index-url https://pypi.ngc.nvidia.com') - - LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...') - f = Path(str(self.file).replace(self.file.suffix, '_saved_model')) - if f.is_dir(): - import shutil - shutil.rmtree(f) # delete output folder - - # Export to ONNX - self.args.simplify = True - f_onnx, _ = self.export_onnx() - - # Export to TF - int8 = '-oiqt -qt per-tensor' if self.args.int8 else '' - cmd = f'onnx2tf -i {f_onnx} -o {f} -nuo --non_verbose {int8}' - LOGGER.info(f"\n{prefix} running '{cmd.strip()}'") - subprocess.run(cmd, shell=True) - yaml_save(f / 'metadata.yaml', self.metadata) # add metadata.yaml - - # Remove/rename TFLite models - if self.args.int8: - for file in f.rglob('*_dynamic_range_quant.tflite'): - file.rename(file.with_name(file.stem.replace('_dynamic_range_quant', '_int8') + file.suffix)) - for file in f.rglob('*_integer_quant_with_int16_act.tflite'): - file.unlink() # delete extra fp16 activation TFLite files - - # Add TFLite metadata - for file in f.rglob('*.tflite'): - f.unlink() if 'quant_with_int16_act.tflite' in str(f) else self._add_tflite_metadata(file) - - # Load saved_model - keras_model = tf.saved_model.load(f, tags=None, options=None) - - return str(f), keras_model - - @try_export - def export_pb(self, keras_model, prefix=colorstr('TensorFlow GraphDef:')): - """YOLOv8 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow.""" - import tensorflow as tf # noqa - from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 # noqa - - LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...') - f = self.file.with_suffix('.pb') - - m = tf.function(lambda x: keras_model(x)) # full model - m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)) - frozen_func = convert_variables_to_constants_v2(m) - frozen_func.graph.as_graph_def() - tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False) - return f, None - - @try_export - def export_tflite(self, keras_model, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')): - """YOLOv8 TensorFlow Lite export.""" - import tensorflow as tf # noqa - - LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...') - saved_model = Path(str(self.file).replace(self.file.suffix, '_saved_model')) - if self.args.int8: - f = saved_model / f'{self.file.stem}_int8.tflite' # fp32 in/out - elif self.args.half: - f = saved_model / f'{self.file.stem}_float16.tflite' # fp32 in/out - else: - f = saved_model / f'{self.file.stem}_float32.tflite' - return str(f), None - - @try_export - def export_edgetpu(self, tflite_model='', prefix=colorstr('Edge TPU:')): - """YOLOv8 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/.""" - LOGGER.warning(f'{prefix} WARNING ⚠️ Edge TPU known bug https://github.com/ultralytics/ultralytics/issues/1185') - - cmd = 'edgetpu_compiler --version' - help_url = 'https://coral.ai/docs/edgetpu/compiler/' - assert LINUX, f'export only supported on Linux. See {help_url}' - if subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True).returncode != 0: - LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}') - sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system - for c in ( - 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -', - 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list', - 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'): - subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True) - ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1] - - LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...') - f = str(tflite_model).replace('.tflite', '_edgetpu.tflite') # Edge TPU model - - cmd = f'edgetpu_compiler -s -d -k 10 --out_dir {Path(f).parent} {tflite_model}' - LOGGER.info(f"{prefix} running '{cmd}'") - subprocess.run(cmd.split(), check=True) - self._add_tflite_metadata(f) - return f, None - - @try_export - def export_tfjs(self, prefix=colorstr('TensorFlow.js:')): - """YOLOv8 TensorFlow.js export.""" - check_requirements('tensorflowjs') - import tensorflow as tf - import tensorflowjs as tfjs # noqa - - LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...') - f = str(self.file).replace(self.file.suffix, '_web_model') # js dir - f_pb = self.file.with_suffix('.pb') # *.pb path - - gd = tf.Graph().as_graph_def() # TF GraphDef - with open(f_pb, 'rb') as file: - gd.ParseFromString(file.read()) - outputs = ','.join(gd_outputs(gd)) - LOGGER.info(f'\n{prefix} output node names: {outputs}') - - cmd = f'tensorflowjs_converter --input_format=tf_frozen_model --output_node_names={outputs} {f_pb} {f}' - subprocess.run(cmd.split(), check=True) - - # f_json = Path(f) / 'model.json' # *.json path - # with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order - # subst = re.sub( - # r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, ' - # r'"Identity.?.?": {"name": "Identity.?.?"}, ' - # r'"Identity.?.?": {"name": "Identity.?.?"}, ' - # r'"Identity.?.?": {"name": "Identity.?.?"}}}', - # r'{"outputs": {"Identity": {"name": "Identity"}, ' - # r'"Identity_1": {"name": "Identity_1"}, ' - # r'"Identity_2": {"name": "Identity_2"}, ' - # r'"Identity_3": {"name": "Identity_3"}}}', - # f_json.read_text(), - # ) - # j.write(subst) - yaml_save(Path(f) / 'metadata.yaml', self.metadata) # add metadata.yaml - return f, None - - def _add_tflite_metadata(self, file): - """Add metadata to *.tflite models per https://www.tensorflow.org/lite/models/convert/metadata.""" - from tflite_support import flatbuffers # noqa - from tflite_support import metadata as _metadata # noqa - from tflite_support import metadata_schema_py_generated as _metadata_fb # noqa - - # Create model info - model_meta = _metadata_fb.ModelMetadataT() - model_meta.name = self.metadata['description'] - model_meta.version = self.metadata['version'] - model_meta.author = self.metadata['author'] - model_meta.license = self.metadata['license'] - - # Label file - tmp_file = Path(file).parent / 'temp_meta.txt' - with open(tmp_file, 'w') as f: - f.write(str(self.metadata)) - - label_file = _metadata_fb.AssociatedFileT() - label_file.name = tmp_file.name - label_file.type = _metadata_fb.AssociatedFileType.TENSOR_AXIS_LABELS - - # Create input info - input_meta = _metadata_fb.TensorMetadataT() - input_meta.name = 'image' - input_meta.description = 'Input image to be detected.' - input_meta.content = _metadata_fb.ContentT() - input_meta.content.contentProperties = _metadata_fb.ImagePropertiesT() - input_meta.content.contentProperties.colorSpace = _metadata_fb.ColorSpaceType.RGB - input_meta.content.contentPropertiesType = _metadata_fb.ContentProperties.ImageProperties - - # Create output info - output1 = _metadata_fb.TensorMetadataT() - output1.name = 'output' - output1.description = 'Coordinates of detected objects, class labels, and confidence score' - output1.associatedFiles = [label_file] - if self.model.task == 'segment': - output2 = _metadata_fb.TensorMetadataT() - output2.name = 'output' - output2.description = 'Mask protos' - output2.associatedFiles = [label_file] - - # Create subgraph info - subgraph = _metadata_fb.SubGraphMetadataT() - subgraph.inputTensorMetadata = [input_meta] - subgraph.outputTensorMetadata = [output1, output2] if self.model.task == 'segment' else [output1] - model_meta.subgraphMetadata = [subgraph] - - b = flatbuffers.Builder(0) - b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER) - metadata_buf = b.Output() - - populator = _metadata.MetadataPopulator.with_model_file(str(file)) - populator.load_metadata_buffer(metadata_buf) - populator.load_associated_files([str(tmp_file)]) - populator.populate() - tmp_file.unlink() - - def _pipeline_coreml(self, model, prefix=colorstr('CoreML Pipeline:')): - """YOLOv8 CoreML pipeline.""" - import coremltools as ct # noqa - - LOGGER.info(f'{prefix} starting pipeline with coremltools {ct.__version__}...') - batch_size, ch, h, w = list(self.im.shape) # BCHW - - # Output shapes - spec = model.get_spec() - out0, out1 = iter(spec.description.output) - if MACOS: - from PIL import Image - img = Image.new('RGB', (w, h)) # img(192 width, 320 height) - # img = torch.zeros((*opt.img_size, 3)).numpy() # img size(320,192,3) iDetection - out = model.predict({'image': img}) - out0_shape = out[out0.name].shape - out1_shape = out[out1.name].shape - else: # linux and windows can not run model.predict(), get sizes from pytorch output y - out0_shape = self.output_shape[2], self.output_shape[1] - 4 # (3780, 80) - out1_shape = self.output_shape[2], 4 # (3780, 4) - - # Checks - names = self.metadata['names'] - nx, ny = spec.description.input[0].type.imageType.width, spec.description.input[0].type.imageType.height - na, nc = out0_shape - # na, nc = out0.type.multiArrayType.shape # number anchors, classes - assert len(names) == nc, f'{len(names)} names found for nc={nc}' # check - - # Define output shapes (missing) - out0.type.multiArrayType.shape[:] = out0_shape # (3780, 80) - out1.type.multiArrayType.shape[:] = out1_shape # (3780, 4) - # spec.neuralNetwork.preprocessing[0].featureName = '0' - - # Flexible input shapes - # from coremltools.models.neural_network import flexible_shape_utils - # s = [] # shapes - # s.append(flexible_shape_utils.NeuralNetworkImageSize(320, 192)) - # s.append(flexible_shape_utils.NeuralNetworkImageSize(640, 384)) # (height, width) - # flexible_shape_utils.add_enumerated_image_sizes(spec, feature_name='image', sizes=s) - # r = flexible_shape_utils.NeuralNetworkImageSizeRange() # shape ranges - # r.add_height_range((192, 640)) - # r.add_width_range((192, 640)) - # flexible_shape_utils.update_image_size_range(spec, feature_name='image', size_range=r) - - # Print - # print(spec.description) - - # Model from spec - model = ct.models.MLModel(spec) - - # 3. Create NMS protobuf - nms_spec = ct.proto.Model_pb2.Model() - nms_spec.specificationVersion = 5 - for i in range(2): - decoder_output = model._spec.description.output[i].SerializeToString() - nms_spec.description.input.add() - nms_spec.description.input[i].ParseFromString(decoder_output) - nms_spec.description.output.add() - nms_spec.description.output[i].ParseFromString(decoder_output) - - nms_spec.description.output[0].name = 'confidence' - nms_spec.description.output[1].name = 'coordinates' - - output_sizes = [nc, 4] - for i in range(2): - ma_type = nms_spec.description.output[i].type.multiArrayType - ma_type.shapeRange.sizeRanges.add() - ma_type.shapeRange.sizeRanges[0].lowerBound = 0 - ma_type.shapeRange.sizeRanges[0].upperBound = -1 - ma_type.shapeRange.sizeRanges.add() - ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i] - ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i] - del ma_type.shape[:] - - nms = nms_spec.nonMaximumSuppression - nms.confidenceInputFeatureName = out0.name # 1x507x80 - nms.coordinatesInputFeatureName = out1.name # 1x507x4 - nms.confidenceOutputFeatureName = 'confidence' - nms.coordinatesOutputFeatureName = 'coordinates' - nms.iouThresholdInputFeatureName = 'iouThreshold' - nms.confidenceThresholdInputFeatureName = 'confidenceThreshold' - nms.iouThreshold = 0.45 - nms.confidenceThreshold = 0.25 - nms.pickTop.perClass = True - nms.stringClassLabels.vector.extend(names.values()) - nms_model = ct.models.MLModel(nms_spec) - - # 4. Pipeline models together - pipeline = ct.models.pipeline.Pipeline(input_features=[('image', ct.models.datatypes.Array(3, ny, nx)), - ('iouThreshold', ct.models.datatypes.Double()), - ('confidenceThreshold', ct.models.datatypes.Double())], - output_features=['confidence', 'coordinates']) - pipeline.add_model(model) - pipeline.add_model(nms_model) - - # Correct datatypes - pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString()) - pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString()) - pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString()) - - # Update metadata - pipeline.spec.specificationVersion = 5 - pipeline.spec.description.metadata.userDefined.update({ - 'IoU threshold': str(nms.iouThreshold), - 'Confidence threshold': str(nms.confidenceThreshold)}) - - # Save the model - model = ct.models.MLModel(pipeline.spec) - model.input_description['image'] = 'Input image' - model.input_description['iouThreshold'] = f'(optional) IOU threshold override (default: {nms.iouThreshold})' - model.input_description['confidenceThreshold'] = \ - f'(optional) Confidence threshold override (default: {nms.confidenceThreshold})' - model.output_description['confidence'] = 'Boxes × Class confidence (see user-defined metadata "classes")' - model.output_description['coordinates'] = 'Boxes × [x, y, width, height] (relative to image size)' - LOGGER.info(f'{prefix} pipeline success') - return model - - def add_callback(self, event: str, callback): - """ - Appends the given callback. - """ - self.callbacks[event].append(callback) - - def run_callbacks(self, event: str): - """Execute all callbacks for a given event.""" - for callback in self.callbacks.get(event, []): - callback(self) - - -class iOSDetectModel(torch.nn.Module): - """Wrap an Ultralytics YOLO model for iOS export.""" - - def __init__(self, model, im): - """Initialize the iOSDetectModel class with a YOLO model and example image.""" - super().__init__() - b, c, h, w = im.shape # batch, channel, height, width - self.model = model - self.nc = len(model.names) # number of classes - if w == h: - self.normalize = 1.0 / w # scalar - else: - self.normalize = torch.tensor([1.0 / w, 1.0 / h, 1.0 / w, 1.0 / h]) # broadcast (slower, smaller) - - def forward(self, x): - """Normalize predictions of object detection model with input size-dependent factors.""" - xywh, cls = self.model(x)[0].transpose(0, 1).split((4, self.nc), 1) - return cls, xywh * self.normalize # confidence (3780, 80), coordinates (3780, 4) - - -def export(cfg=DEFAULT_CFG): - """Export a YOLOv model to a specific format.""" - cfg.model = cfg.model or 'yolov8n.yaml' - cfg.format = cfg.format or 'torchscript' - - from ultralytics import YOLO - model = YOLO(cfg.model) - model.export(**vars(cfg)) - - -if __name__ == '__main__': - """ - CLI: - yolo mode=export model=yolov8n.yaml format=onnx - """ - export() diff --git a/spaces/valhalla/minDALLE/examples/transfer_learning_ex.py b/spaces/valhalla/minDALLE/examples/transfer_learning_ex.py deleted file mode 100644 index 40a31f2a4ade672648bd7a69cf4bd60767385d20..0000000000000000000000000000000000000000 --- a/spaces/valhalla/minDALLE/examples/transfer_learning_ex.py +++ /dev/null @@ -1,172 +0,0 @@ -# ------------------------------------------------------------------------------------ -# Minimal DALL-E -# Copyright (c) 2021 KakaoBrain. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 [see LICENSE for details] -# ------------------------------------------------------------------------------------ - -import os -import sys -import argparse -from typing import Optional -from datetime import datetime - -import torch -from torch.utils.data import DataLoader -import torchvision -import torchvision.transforms as transforms -import pytorch_lightning as pl -from pytorch_lightning.callbacks import ModelCheckpoint, Callback -from pytorch_lightning.loggers import TensorBoardLogger -from pytorch_lightning.utilities.distributed import rank_zero_only - -sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from dalle.models import ImageGPT - - -parser = argparse.ArgumentParser() - -parser.add_argument('-d', '--config-downstream', type=str, default=None, required=True) -parser.add_argument('-u', '--path-upstream', type=str, default=None, required=True) -parser.add_argument('-r', '--result-path', type=str, default=None, required=True) -parser.add_argument('--imagenet-path', type=str, default=None, required=True) - -parser.add_argument('--n-gpus', type=int, default=1) -parser.add_argument('--seed', type=int, default=0) - - -args = parser.parse_args() - - -class ImageLogger(Callback): - def __init__(self): - super().__init__() - - @rank_zero_only - def log_img(self, pl_module, batch, current_epoch, split="train"): - with torch.no_grad(): - images, labels = batch - recons = pl_module.stage1(images) - images = images.cpu() - recons = recons.cpu() - - grid_org = (torchvision.utils.make_grid(images, nrow=8) + 1.0) / 2.0 - grid_rec = (torchvision.utils.make_grid(recons, nrow=8) + 1.0) / 2.0 - grid_rec = torch.clip(grid_rec, min=0, max=1) - - pl_module.logger.experiment.add_image(f"images_org/{split}", grid_org, global_step=current_epoch) - pl_module.logger.experiment.add_image(f"images_rec/{split}", grid_rec, global_step=current_epoch) - - def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): - if batch_idx == 0 and trainer.current_epoch < 5: - self.log_img(pl_module, batch, current_epoch=trainer.current_epoch, split="train") - - def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): - if batch_idx == 0 and trainer.current_epoch < 5: - self.log_img(pl_module, batch, current_epoch=trainer.current_epoch, split="test") - - -class ImageNetDataModule(pl.LightningDataModule): - def __init__(self, - data_dir: Optional[str] = None, - image_resolution: int = 256, - train_batch_size: int = 2, - valid_batch_size: int = 32, - num_workers: int = 8): - super().__init__() - - self.data_dir = data_dir - self.image_resolution = image_resolution - self.train_batch_size = train_batch_size - self.valid_batch_size = valid_batch_size - self.num_workers = num_workers - - self.train_transform = transforms.Compose( - [transforms.Resize(image_resolution), - transforms.RandomCrop(image_resolution), - transforms.ToTensor(), - transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])] - ) - self.valid_transform = transforms.Compose( - [transforms.Resize(image_resolution), - transforms.CenterCrop(image_resolution), - transforms.ToTensor(), - transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])] - ) - - def setup(self, stage=None): - self.trainset = torchvision.datasets.ImageNet(root=self.data_dir, split='train', transform=self.train_transform) - self.validset = torchvision.datasets.ImageNet(root=self.data_dir, split='val', transform=self.valid_transform) - - def train_dataloader(self): - return DataLoader(self.trainset, - batch_size=self.train_batch_size, - num_workers=self.num_workers, - pin_memory=True) - - def valid_dataloader(self): - return DataLoader(self.validset, - batch_size=self.valid_batch_size, - num_workers=self.num_workers, - pin_memory=True) - - -def setup_callbacks(config): - # Setup callbacks - now = datetime.now().strftime('%d%m%Y_%H%M%S') - result_path = os.path.join(args.result_path, - os.path.basename(args.config_downstream).split('.')[0], - now) - ckpt_path = os.path.join(result_path, 'ckpt') - log_path = os.path.join(result_path, 'log') - - checkpoint_callback = ModelCheckpoint( - dirpath=ckpt_path, - filename="imagenet-clscond-gen-{epoch:02d}" if config.stage2.use_cls_cond else - "imagenet-uncond-gen-{epoch:02d}", - every_n_epochs=config.experiment.save_ckpt_freq, - save_weights_only=True, - save_last=True - ) - logger = TensorBoardLogger(log_path, name="iGPT") - logger_img = ImageLogger() - return checkpoint_callback, logger, logger_img - - -if __name__ == '__main__': - pl.seed_everything(args.seed) - - # Build iGPT - model, config = ImageGPT.from_pretrained(args.path_upstream, args.config_downstream) - - # Setup callbacks - ckpt_callback, logger, logger_img = setup_callbacks(config) - - # Build data modules - dataset = ImageNetDataModule(data_dir=args.imagenet_path, - image_resolution=config.dataset.image_resolution, - train_batch_size=config.experiment.local_batch_size, - valid_batch_size=config.experiment.valid_batch_size, - num_workers=16) - dataset.setup() - train_dataloader = dataset.train_dataloader() - valid_dataloader = dataset.valid_dataloader() - print(f"len(train_dataset) = {len(dataset.trainset)}") - print(f"len(valid_dataset) = {len(dataset.validset)}") - - # Calculate how many batches are accumulated - assert config.experiment.total_batch_size % (config.experiment.local_batch_size * args.n_gpus) == 0 - grad_accm_steps = config.experiment.total_batch_size // (config.experiment.local_batch_size * args.n_gpus) - config.optimizer.max_steps = len(dataset.trainset) // config.experiment.total_batch_size * config.experiment.epochs - - # Build trainer - trainer = pl.Trainer(max_epochs=config.experiment.epochs, - accumulate_grad_batches=grad_accm_steps, - gradient_clip_val=config.optimizer.grad_clip_norm, - precision=16 if config.experiment.use_amp else 32, - callbacks=[ckpt_callback, logger_img], - accelerator="gpu", - devices=args.n_gpus, - strategy="ddp", - logger=logger) - trainer.fit(model, train_dataloader, valid_dataloader) diff --git a/spaces/verkaDerkaDerk/face-image-to-face-obj/README.md b/spaces/verkaDerkaDerk/face-image-to-face-obj/README.md deleted file mode 100644 index 4c91ff6f8bd8acb4dc12b5a018e56a7dec0c956f..0000000000000000000000000000000000000000 --- a/spaces/verkaDerkaDerk/face-image-to-face-obj/README.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Face Image to Face Quad Mesh -emoji: 🐢 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.35.2 -app_file: app.py -pinned: false ---- - -Uses MediaPipe to detect a face in an image and convert it to a (mostly) quad mesh. -Currently saves to OBJ, hopefully glb at some point with color data. -The 3d viewer has Y pointing the opposite direction from Blender, so ya hafta spin it. - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/verkaDerkaDerk/face-image-to-face-obj/examples/converted/README.md b/spaces/verkaDerkaDerk/face-image-to-face-obj/examples/converted/README.md deleted file mode 100644 index 277309caf5cc1b3b7c8ad13f65530d3c5a644576..0000000000000000000000000000000000000000 --- a/spaces/verkaDerkaDerk/face-image-to-face-obj/examples/converted/README.md +++ /dev/null @@ -1,5 +0,0 @@ - -1. downloaded all the obj files -2. for i in in-*obj ; do o=$( echo ${i} | cut -f2- -d- ) ; ../../meshin-around.sh ${i} ${o} ; done -3. for i in ../*png ; do o=$(basename ${i} | sed 's,-[^.]*\.,.,' ) ; cp -i ${i} ${o} ; done - diff --git a/spaces/video-p2p-library/Video-P2P-Demo/app.py b/spaces/video-p2p-library/Video-P2P-Demo/app.py deleted file mode 100644 index 220dddd4d6557bdd57d58ffe7361a3e9dc3e4063..0000000000000000000000000000000000000000 --- a/spaces/video-p2p-library/Video-P2P-Demo/app.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python - -from __future__ import annotations - -import os -from subprocess import getoutput - -import gradio as gr -import torch - -from app_inference import create_inference_demo -from app_training import create_training_demo -from app_upload import create_upload_demo -from inference import InferencePipeline -from trainer import Trainer - -TITLE = '# [Video-P2P](https://video-p2p.github.io/) UI' - -ORIGINAL_SPACE_ID = 'video-p2p-library/Video-P2P-Demo' -SPACE_ID = os.getenv('SPACE_ID', ORIGINAL_SPACE_ID) -GPU_DATA = getoutput('nvidia-smi') -SHARED_UI_WARNING = f'''## Attention - Training doesn't work in this shared UI. You can duplicate and use it with a paid private T4 GPU. - -
          Duplicate Space
          -''' - -if os.getenv('SYSTEM') == 'spaces' and SPACE_ID != ORIGINAL_SPACE_ID: - SETTINGS = f'Settings' -else: - SETTINGS = 'Settings' - -INVALID_GPU_WARNING = f'''## Attention - the specified GPU is invalid. Training may not work. Make sure you have selected a `T4 GPU` for this task.''' - -CUDA_NOT_AVAILABLE_WARNING = f'''## Attention - Running on CPU. -
          -You can assign a GPU in the {SETTINGS} tab if you are running this on HF Spaces. -You can use "T4 small/medium" to run this demo. -
          -''' - -HF_TOKEN_NOT_SPECIFIED_WARNING = f'''The environment variable `HF_TOKEN` is not specified. Feel free to specify your Hugging Face token with write permission if you don't want to manually provide it for every run. -
          -You can check and create your Hugging Face tokens here. -You can specify environment variables in the "Repository secrets" section of the {SETTINGS} tab. -
          -''' - -HF_TOKEN = os.getenv('HF_TOKEN') - - -def show_warning(warning_text: str) -> gr.Blocks: - with gr.Blocks() as demo: - with gr.Box(): - gr.Markdown(warning_text) - return demo - - -pipe = InferencePipeline(HF_TOKEN) -trainer = Trainer(HF_TOKEN) - -with gr.Blocks(css='style.css') as demo: - if SPACE_ID == ORIGINAL_SPACE_ID: - show_warning(SHARED_UI_WARNING) - elif not torch.cuda.is_available(): - show_warning(CUDA_NOT_AVAILABLE_WARNING) - elif (not 'T4' in GPU_DATA): - show_warning(INVALID_GPU_WARNING) - - gr.Markdown(TITLE) - with gr.Tabs(): - with gr.TabItem('Train'): - create_training_demo(trainer, pipe) - # with gr.TabItem('Run'): - # create_inference_demo(pipe, HF_TOKEN) - # with gr.TabItem('Upload'): - # gr.Markdown(''' - # - You can use this tab to upload models later if you choose not to upload models in training time or if upload in training time failed. - # ''') - # create_upload_demo(HF_TOKEN) - - if not HF_TOKEN: - show_warning(HF_TOKEN_NOT_SPECIFIED_WARNING) - -demo.queue(max_size=1).launch(share=False) diff --git a/spaces/vonewman/ner_app/README.md b/spaces/vonewman/ner_app/README.md deleted file mode 100644 index c0658f20b5a6533311bc25ba18e8773d0298b6ea..0000000000000000000000000000000000000000 --- a/spaces/vonewman/ner_app/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Ner App -emoji: 🏆 -colorFrom: purple -colorTo: gray -sdk: streamlit -sdk_version: 1.27.2 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/vpsrikanth/FaceSimilarity/app/templates/face_recognition.html b/spaces/vpsrikanth/FaceSimilarity/app/templates/face_recognition.html deleted file mode 100644 index 415e8deb0ed5e694df75477163c87e1f47752e90..0000000000000000000000000000000000000000 --- a/spaces/vpsrikanth/FaceSimilarity/app/templates/face_recognition.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - Index - - -
          -

          -
          Face Recognition
          -

          -
          -
          -
          -
            - -
            -
            - Upload Image:

            - -


            - -
            - -

            -
            - -
            -
          -
          -
          - - diff --git a/spaces/vslasor/VLS1-ASRLiveSpeechRecognition-GR/app.py b/spaces/vslasor/VLS1-ASRLiveSpeechRecognition-GR/app.py deleted file mode 100644 index 140f6f0a04ec368cd560dcc02026a6e8a2b54725..0000000000000000000000000000000000000000 --- a/spaces/vslasor/VLS1-ASRLiveSpeechRecognition-GR/app.py +++ /dev/null @@ -1,168 +0,0 @@ -import gradio as gr -import torch -import time -import librosa -import soundfile -import nemo.collections.asr as nemo_asr -import tempfile -import os -import uuid - -from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration -import torch - -# PersistDataset ----- -import os -import csv -import gradio as gr -from gradio import inputs, outputs -import huggingface_hub -from huggingface_hub import Repository, hf_hub_download, upload_file -from datetime import datetime - -# --------------------------------------------- -# Dataset and Token links - change awacke1 to your own HF id, and add a HF_TOKEN copy to your repo for write permissions -# This should allow you to save your results to your own Dataset hosted on HF. --- -#DATASET_REPO_URL = "https://huggingface.co/datasets/awacke1/Carddata.csv" -#DATASET_REPO_ID = "awacke1/Carddata.csv" -#DATA_FILENAME = "Carddata.csv" -#DATA_FILE = os.path.join("data", DATA_FILENAME) -#HF_TOKEN = os.environ.get("HF_TOKEN") -#SCRIPT = """ - -# -#""" - -#try: -# hf_hub_download( -# repo_id=DATASET_REPO_ID, -# filename=DATA_FILENAME, -# cache_dir=DATA_DIRNAME, -# force_filename=DATA_FILENAME -# ) -#except: -# print("file not found") -#repo = Repository( -# local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN -#) - -#def store_message(name: str, message: str): -# if name and message: -# with open(DATA_FILE, "a") as csvfile: -# writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"]) -# writer.writerow( -# {"name": name.strip(), "message": message.strip(), "time": str(datetime.now())} -# ) -# # uncomment line below to begin saving - -# commit_url = repo.push_to_hub() -# return "" - -#iface = gr.Interface( -# store_message, -# [ -# inputs.Textbox(placeholder="Your name"), -# inputs.Textbox(placeholder="Your message", lines=2), -# ], -# "html", -# css=""" -# .message {background-color:cornflowerblue;color:white; padding:4px;margin:4px;border-radius:4px; } -# """, -# title="Reading/writing to a HuggingFace dataset repo from Spaces", -# description=f"This is a demo of how to do simple *shared data persistence* in a Gradio Space, backed by a dataset repo.", -# article=f"The dataset repo is [{DATASET_REPO_URL}]({DATASET_REPO_URL})", -#) - - -# main ------------------------- -mname = "facebook/blenderbot-400M-distill" -model = BlenderbotForConditionalGeneration.from_pretrained(mname) -tokenizer = BlenderbotTokenizer.from_pretrained(mname) - -def take_last_tokens(inputs, note_history, history): - """Filter the last 128 tokens""" - if inputs['input_ids'].shape[1] > 128: - inputs['input_ids'] = torch.tensor([inputs['input_ids'][0][-128:].tolist()]) - inputs['attention_mask'] = torch.tensor([inputs['attention_mask'][0][-128:].tolist()]) - note_history = [' '.join(note_history[0].split(' ')[2:])] - history = history[1:] - return inputs, note_history, history - -def add_note_to_history(note, note_history): - """Add a note to the historical information""" - note_history.append(note) - note_history = ' '.join(note_history) - return [note_history] - - -def chat(message, history): - history = history or [] - if history: - history_useful = [' '.join([str(a[0])+' '+str(a[1]) for a in history])] - else: - history_useful = [] - history_useful = add_note_to_history(message, history_useful) - inputs = tokenizer(history_useful, return_tensors="pt") - inputs, history_useful, history = take_last_tokens(inputs, history_useful, history) - reply_ids = model.generate(**inputs) - response = tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0] - history_useful = add_note_to_history(response, history_useful) - list_history = history_useful[0].split(' ') - history.append((list_history[-2], list_history[-1])) -# store_message(message, response) # Save to dataset - uncomment if you uncomment above to save inputs and outputs to your dataset - return history, history - - -SAMPLE_RATE = 16000 -model = nemo_asr.models.EncDecRNNTBPEModel.from_pretrained("nvidia/stt_en_conformer_transducer_xlarge") -model.change_decoding_strategy(None) -model.eval() - -def process_audio_file(file): - data, sr = librosa.load(file) - if sr != SAMPLE_RATE: - data = librosa.resample(data, orig_sr=sr, target_sr=SAMPLE_RATE) - # monochannel - data = librosa.to_mono(data) - return data - - -def transcribe(audio, state = ""): - if state is None: - state = "" - audio_data = process_audio_file(audio) - with tempfile.TemporaryDirectory() as tmpdir: - audio_path = os.path.join(tmpdir, f'audio_{uuid.uuid4()}.wav') - soundfile.write(audio_path, audio_data, SAMPLE_RATE) - transcriptions = model.transcribe([audio_path]) - if type(transcriptions) == tuple and len(transcriptions) == 2: - transcriptions = transcriptions[0] - transcriptions = transcriptions[0] -# store_message(transcriptions, state) # Save to dataset - uncomment to store into a dataset - hint you will need your HF_TOKEN - state = state + transcriptions + " " - return state, state - -iface = gr.Interface( - fn=transcribe, - inputs=[ - gr.Audio(source="microphone", type='filepath', streaming=True), - "state", - ], - outputs=[ - "textbox", - "state", - ], - layout="horizontal", - theme="huggingface", - title="🗣️LiveSpeechRecognition🧠Memory💾", - description=f"Live Automatic Speech Recognition (ASR) with Memory💾 Dataset.", - allow_flagging='never', - live=True, -# article=f"Result Output Saved to Memory💾 Dataset: [{DATASET_REPO_URL}]({DATASET_REPO_URL})" -) -iface.launch() diff --git a/spaces/vslasor/VLS7-ClinicalTerminologyUIUX-GR/Readme.md b/spaces/vslasor/VLS7-ClinicalTerminologyUIUX-GR/Readme.md deleted file mode 100644 index 9d494f6d6336624e46e1ca6eb75996bf156099d8..0000000000000000000000000000000000000000 --- a/spaces/vslasor/VLS7-ClinicalTerminologyUIUX-GR/Readme.md +++ /dev/null @@ -1 +0,0 @@ -Files Directory - drop in examples here to ref by app.py \ No newline at end of file diff --git a/spaces/wanghaha13/ChuanhuChatGPT/overwrites.py b/spaces/wanghaha13/ChuanhuChatGPT/overwrites.py deleted file mode 100644 index 436fcf46b5807ca045e77ac762039ba0ffc16f6d..0000000000000000000000000000000000000000 --- a/spaces/wanghaha13/ChuanhuChatGPT/overwrites.py +++ /dev/null @@ -1,38 +0,0 @@ -from __future__ import annotations -import logging - -from llama_index import Prompt -from typing import List, Tuple -import mdtex2html - -from presets import * -from llama_func import * - - -def compact_text_chunks(self, prompt: Prompt, text_chunks: List[str]) -> List[str]: - logging.debug("Compacting text chunks...🚀🚀🚀") - combined_str = [c.strip() for c in text_chunks if c.strip()] - combined_str = [f"[{index+1}] {c}" for index, c in enumerate(combined_str)] - combined_str = "\n\n".join(combined_str) - # resplit based on self.max_chunk_overlap - text_splitter = self.get_text_splitter_given_prompt(prompt, 1, padding=1) - return text_splitter.split_text(combined_str) - - -def postprocess( - self, y: List[Tuple[str | None, str | None]] -) -> List[Tuple[str | None, str | None]]: - """ - Parameters: - y: List of tuples representing the message and response pairs. Each message and response should be a string, which may be in Markdown format. - Returns: - List of tuples representing the message and response. Each message and response will be a string of HTML. - """ - if y is None or y == []: - return [] - tag_regex = re.compile(r"^<\w+>[^<]+") - if tag_regex.search(y[-1][1]): - y[-1] = (y[-1][0].replace("\n", "
          "), y[-1][1]) - else: - y[-1] = (y[-1][0].replace("\n", "
          "), convert_mdtext(y[-1][1])) - return y diff --git a/spaces/whgwd2023/bingo/src/components/user-menu.tsx b/spaces/whgwd2023/bingo/src/components/user-menu.tsx deleted file mode 100644 index 9bd1edc9cf9f39b63629b021f0c1186b1a7c1341..0000000000000000000000000000000000000000 --- a/spaces/whgwd2023/bingo/src/components/user-menu.tsx +++ /dev/null @@ -1,113 +0,0 @@ -'use client' - -import { useEffect, useState } from 'react' -import Image from 'next/image' -import { toast } from 'react-hot-toast' -import { Button } from '@/components/ui/button' -import pkg from '../../package.json' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuTrigger -} from '@/components/ui/dropdown-menu' -import { IconCopy, IconExternalLink, IconGitHub } from '@/components/ui/icons' -import SettingIcon from '@/assets/images/settings.svg' -import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard' - -export function UserMenu() { - const [host, setHost] = useState('') - const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 }) - useEffect(() => { - setHost(location.host) - }, []) - - useEffect(() => { - if (isCopied) { - toast.success('复制成功') - } - }, [isCopied]) - return ( -
          - - - - - - - location.href='#dialog="settings"' - } - className="cursor-pointer" - > - 设置用户 - - - - location.href='#dialog="voice"' - } - className="cursor-pointer" - > - 语音设置 - - - - - 开源地址 - - - - - - - - 托管地址 - 🤗 - - - - - - - 复制站点 - - - - - -
          版本信息 {pkg.version}
          -
          - - -
          站点域名
          -
          copyToClipboard(host)} className="flex gap-1 text-xs text-zinc-500 cursor-pointer"> - {host} -
          -
          -
          -
          -
          - ) -} diff --git a/spaces/whitphx/gradio-static-test/dist/assets/yaml-95012b83.js b/spaces/whitphx/gradio-static-test/dist/assets/yaml-95012b83.js deleted file mode 100644 index 3fef68bd6d3b922eebf9622184021189fa7e8cc2..0000000000000000000000000000000000000000 --- a/spaces/whitphx/gradio-static-test/dist/assets/yaml-95012b83.js +++ /dev/null @@ -1,2 +0,0 @@ -var l=["true","false","on","off","yes","no"],f=new RegExp("\\b(("+l.join(")|(")+"))$","i");const a={name:"yaml",token:function(n,i){var r=n.peek(),e=i.escaped;if(i.escaped=!1,r=="#"&&(n.pos==0||/\s/.test(n.string.charAt(n.pos-1))))return n.skipToEnd(),"comment";if(n.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/))return"string";if(i.literal&&n.indentation()>i.keyCol)return n.skipToEnd(),"string";if(i.literal&&(i.literal=!1),n.sol()){if(i.keyCol=0,i.pair=!1,i.pairStart=!1,n.match("---")||n.match("..."))return"def";if(n.match(/^\s*-\s+/))return"meta"}if(n.match(/^(\{|\}|\[|\])/))return r=="{"?i.inlinePairs++:r=="}"?i.inlinePairs--:r=="["?i.inlineList++:i.inlineList--,"meta";if(i.inlineList>0&&!e&&r==",")return n.next(),"meta";if(i.inlinePairs>0&&!e&&r==",")return i.keyCol=0,i.pair=!1,i.pairStart=!1,n.next(),"meta";if(i.pairStart){if(n.match(/^\s*(\||\>)\s*/))return i.literal=!0,"meta";if(n.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i))return"variable";if(i.inlinePairs==0&&n.match(/^\s*-?[0-9\.\,]+\s?$/)||i.inlinePairs>0&&n.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/))return"number";if(n.match(f))return"keyword"}return!i.pair&&n.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^,\[\]{}#&*!|>'"%@`])[^#]*?(?=\s*:($|\s))/)?(i.pair=!0,i.keyCol=n.indentation(),"atom"):i.pair&&n.match(/^:\s*/)?(i.pairStart=!0,"meta"):(i.pairStart=!1,i.escaped=r=="\\",n.next(),null)},startState:function(){return{pair:!1,pairStart:!1,keyCol:0,inlinePairs:0,inlineList:0,literal:!1,escaped:!1}},languageData:{commentTokens:{line:"#"}}};export{a as yaml}; -//# sourceMappingURL=yaml-95012b83.js.map diff --git a/spaces/xiaogang/res2net/app.py b/spaces/xiaogang/res2net/app.py deleted file mode 100644 index 6a9de6aa9330a764645443198a174cb9751189f2..0000000000000000000000000000000000000000 --- a/spaces/xiaogang/res2net/app.py +++ /dev/null @@ -1,321 +0,0 @@ -import gradio as gr -import torch.nn as nn -import math -import torch.utils.model_zoo as model_zoo -import torch -import torch.nn.functional as F -__all__ = ['Res2Net', 'res2net50_v1b', 'res2net101_v1b'] - -model_urls = { - 'res2net50_v1b_26w_4s': 'https://shanghuagao.oss-cn-beijing.aliyuncs.com/res2net/res2net50_v1b_26w_4s-3cf99910.pth', - 'res2net101_v1b_26w_4s': 'https://shanghuagao.oss-cn-beijing.aliyuncs.com/res2net/res2net101_v1b_26w_4s-0812c246.pth', -} - - - -class Bottle2neck(nn.Module): - expansion = 4 - - def __init__(self, inplanes, planes, stride=1, downsample=None, baseWidth=26, scale = 4, stype='normal'): - """ Constructor - Args: - inplanes: input channel dimensionality - planes: output channel dimensionality - stride: conv stride. Replaces pooling layer. - downsample: None when stride = 1 - baseWidth: basic width of conv3x3 - scale: number of scale. - type: 'normal': normal set. 'stage': first block of a new stage. - """ - super(Bottle2neck, self).__init__() - - width = int(math.floor(planes * (baseWidth/64.0))) - self.conv1 = nn.Conv2d(inplanes, width*scale, kernel_size=1, bias=False) - self.bn1 = nn.BatchNorm2d(width*scale) - - if scale == 1: - self.nums = 1 - else: - self.nums = scale -1 - if stype == 'stage': - self.pool = nn.AvgPool2d(kernel_size=3, stride = stride, padding=1) - convs = [] - bns = [] - for i in range(self.nums): - convs.append(nn.Conv2d(width, width, kernel_size=3, stride = stride, padding=1, bias=False)) - bns.append(nn.BatchNorm2d(width)) - self.convs = nn.ModuleList(convs) - self.bns = nn.ModuleList(bns) - - self.conv3 = nn.Conv2d(width*scale, planes * self.expansion, kernel_size=1, bias=False) - self.bn3 = nn.BatchNorm2d(planes * self.expansion) - - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - self.stype = stype - self.scale = scale - self.width = width - - def forward(self, x): - residual = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - spx = torch.split(out, self.width, 1) - for i in range(self.nums): - if i==0 or self.stype=='stage': - sp = spx[i] - else: - sp = sp + spx[i] - sp = self.convs[i](sp) - sp = self.relu(self.bns[i](sp)) - if i==0: - out = sp - else: - out = torch.cat((out, sp), 1) - if self.scale != 1 and self.stype=='normal': - out = torch.cat((out, spx[self.nums]),1) - elif self.scale != 1 and self.stype=='stage': - out = torch.cat((out, self.pool(spx[self.nums])),1) - - out = self.conv3(out) - out = self.bn3(out) - - if self.downsample is not None: - residual = self.downsample(x) - - out += residual - out = self.relu(out) - - return out - -class Res2Net(nn.Module): - - def __init__(self, block, layers, baseWidth = 26, scale = 4, num_classes=1000): - self.inplanes = 64 - super(Res2Net, self).__init__() - self.baseWidth = baseWidth - self.scale = scale - self.conv1 = nn.Sequential( - nn.Conv2d(3, 32, 3, 2, 1, bias=False), - nn.BatchNorm2d(32), - nn.ReLU(inplace=True), - nn.Conv2d(32, 32, 3, 1, 1, bias=False), - nn.BatchNorm2d(32), - nn.ReLU(inplace=True), - nn.Conv2d(32, 64, 3, 1, 1, bias=False) - ) - self.bn1 = nn.BatchNorm2d(64) - self.relu = nn.ReLU() - self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) - self.layer1 = self._make_layer(block, 64, layers[0]) - self.layer2 = self._make_layer(block, 128, layers[1], stride=2) - self.layer3 = self._make_layer(block, 256, layers[2], stride=2) - self.layer4 = self._make_layer(block, 512, layers[3], stride=2) - self.avgpool = nn.AdaptiveAvgPool2d(1) - self.fc = nn.Linear(512 * block.expansion, num_classes) - - for m in self.modules(): - if isinstance(m, nn.Conv2d): - nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') - elif isinstance(m, nn.BatchNorm2d): - nn.init.constant_(m.weight, 1) - nn.init.constant_(m.bias, 0) - - def _make_layer(self, block, planes, blocks, stride=1): - downsample = None - if stride != 1 or self.inplanes != planes * block.expansion: - downsample = nn.Sequential( - nn.AvgPool2d(kernel_size=stride, stride=stride, - ceil_mode=True, count_include_pad=False), - nn.Conv2d(self.inplanes, planes * block.expansion, - kernel_size=1, stride=1, bias=False), - nn.BatchNorm2d(planes * block.expansion), - ) - - layers = [] - layers.append(block(self.inplanes, planes, stride, downsample=downsample, - stype='stage', baseWidth = self.baseWidth, scale=self.scale)) - self.inplanes = planes * block.expansion - for i in range(1, blocks): - layers.append(block(self.inplanes, planes, baseWidth = self.baseWidth, scale=self.scale)) - - return nn.Sequential(*layers) - - def forward(self, x): - x = self.conv1(x) - x = self.bn1(x) - x = self.relu(x) - x = self.maxpool(x) - - x = self.layer1(x) - x = self.layer2(x) - x = self.layer3(x) - x = self.layer4(x) - - x = self.avgpool(x) - x = x.view(x.size(0), -1) - x = self.fc(x) - - return x - - -def res2net50_v1b(pretrained=False, **kwargs): - """Constructs a Res2Net-50_v1b model. - Res2Net-50 refers to the Res2Net-50_v1b_26w_4s. - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth = 26, scale = 4, **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['res2net50_v1b_26w_4s'])) - return model - -def res2net101_v1b(pretrained=False, **kwargs): - """Constructs a Res2Net-50_v1b_26w_4s model. - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = Res2Net(Bottle2neck, [3, 4, 23, 3], baseWidth = 26, scale = 4, **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['res2net101_v1b_26w_4s'])) - return model - -def res2net50_v1b_26w_4s(pretrained=False, **kwargs): - """Constructs a Res2Net-50_v1b_26w_4s model. - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth = 26, scale = 4, **kwargs) - if pretrained: - model.load_state_dict(torch.load(pthfile,map_location='cpu')) #load model - return model - -def res2net101_v1b_26w_4s(pretrained=False, **kwargs): - """Constructs a Res2Net-50_v1b_26w_4s model. - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = Res2Net(Bottle2neck, [3, 4, 23, 3], baseWidth = 26, scale = 4, **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['res2net101_v1b_26w_4s'])) - return model - -def res2net152_v1b_26w_4s(pretrained=False, **kwargs): - """Constructs a Res2Net-50_v1b_26w_4s model. - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = Res2Net(Bottle2neck, [3, 8, 36, 3], baseWidth = 26, scale = 4, **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['res2net152_v1b_26w_4s'])) - return model - - -class mutil_model(nn.Module): - - def __init__(self,category_num = 8): - super(mutil_model, self).__init__() - self.model1 = res2net50_v1b_26w_4s(pretrained=False) - self.model1.fc = nn.Sequential( - nn.Linear(in_features=2048, out_features=category_num, bias=True), -) - self.model2 = torch.load('./enet_b2_8'+'.pt',map_location=torch.device('cpu')) - self.model2.classifier = nn.Sequential( - nn.Linear(in_features=1408, out_features=category_num, bias=True), -) - self.fc = nn.Linear(in_features=category_num*2, out_features=category_num, bias=True) - def forward(self, x): - x1 = self.model1(x) - x2 = self.model2(x) - x = torch.cat((x1,x2),1) - x = self.fc(x) - return x - -pth_path = './chn.pt' -category_num = 2 - - -# "cuda" only when GPUs are available. -device = "cuda" if torch.cuda.is_available() else "cpu" - -# Initialize a model, and put it on the device specified. -# 导入res2net预训练模型 -#pthfile = '/cbd_lixiaogang_lixianneng/morror_art/pre_train_model/res2net50_v1b.pth' -model = res2net50_v1b_26w_4s(pretrained=False) -#修改全连接层,输出维度为预测 分类 -#num_ftrs = model.fc.in_features -# model.fc = nn.Sequential( -# nn.Linear(in_features=2048, out_features=1000, bias=True), -# nn.Dropout(0.5), -# nn.Linear(1000, out_features=category_num) -# ) -model.fc = nn.Sequential( - nn.Linear(in_features=2048, out_features=category_num, bias=True), -) -model = model.to(device) -model.device = device -model.load_state_dict(torch.load(pth_path,torch.device('cpu'))) -model.eval() - - -#增加人脸识别模型 -#model = mutil_model(category_num = category_num) -#model_state = torch.load('./model_8_addsad.pt',map_location=torch.device('cpu')).state_dict() -#model.load_state_dict(model_state) # 加载模型参数 -#model.eval() - -labels = ['怀旧','伤感','快乐','激励','清新','浪漫','思念','其他'] - -import requests -import torch - -import gradio as gr -import torchvision.transforms as transforms -#import cv2 -#from PIL import Image -# PIL -#from PIL import Image -# inception_net = tf.keras.applications.MobileNetV2() # load the model - -# Download human-readable labels for ImageNet. -# response = requests.get("https://git.io/JJkYN") -# labels = response.text.split("\n") -print(len(labels)) - -def classify_image(inp): - # inp = inp.convert('RGB') - # inp = Image.fromarray(inp.astype('uint8'), 'RGB') - transform_test = transforms.Compose([ - # transforms.ToPILImage(), - transforms.Resize((256, 256)), - transforms.ToTensor(), - transforms.Normalize((0.485, 0.456, 0.406), - (0.229, 0.224, 0.225)), - ]) - inp = transform_test(inp) - print(inp) - with torch.no_grad(): - prediction = model(torch.unsqueeze(inp, 0)).flatten() - print(prediction) - prediction = torch.nn.Softmax(dim=0)(prediction) - print(prediction) - return {labels[i]: float(prediction[i].item()) for i in range(len(labels))} -# print(classify_image("/jj.jpg")) -# image = gr.inputs.Image(shape=(256, 256)) -# image = gr.inputs.Image() -# print(image) -# label = gr.outputs.Label(num_top_classes=6) - -gr.Interface( - classify_image, - # gr.inputs.Image(), - gr.inputs.Image(type='pil'), - outputs = 'label' - # inputs='image', - # outputs='label', - # examples=[["images/cheetah1.jpg"], ["images/lion.jpg"]], -).launch(debug=True) -#share=True \ No newline at end of file diff --git a/spaces/xiaolongbaox/gpt2.0/modules/shared.py b/spaces/xiaolongbaox/gpt2.0/modules/shared.py deleted file mode 100644 index 70f13cbcf84984487b5e4e47e3bcc1dbb082511a..0000000000000000000000000000000000000000 --- a/spaces/xiaolongbaox/gpt2.0/modules/shared.py +++ /dev/null @@ -1,55 +0,0 @@ -from modules.presets import COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST -import os -import queue - -class State: - interrupted = False - multi_api_key = False - completion_url = COMPLETION_URL - balance_api_url = BALANCE_API_URL - usage_api_url = USAGE_API_URL - - def interrupt(self): - self.interrupted = True - - def recover(self): - self.interrupted = False - - def set_api_host(self, api_host): - self.completion_url = f"https://{api_host}/v1/chat/completions" - self.balance_api_url = f"https://{api_host}/dashboard/billing/credit_grants" - self.usage_api_url = f"https://{api_host}/dashboard/billing/usage" - os.environ["OPENAI_API_BASE"] = f"https://{api_host}/v1" - - def reset_api_host(self): - self.completion_url = COMPLETION_URL - self.balance_api_url = BALANCE_API_URL - self.usage_api_url = USAGE_API_URL - os.environ["OPENAI_API_BASE"] = f"https://{API_HOST}/v1" - return API_HOST - - def reset_all(self): - self.interrupted = False - self.completion_url = COMPLETION_URL - - def set_api_key_queue(self, api_key_list): - self.multi_api_key = True - self.api_key_queue = queue.Queue() - for api_key in api_key_list: - self.api_key_queue.put(api_key) - - def switching_api_key(self, func): - if not hasattr(self, "api_key_queue"): - return func - - def wrapped(*args, **kwargs): - api_key = self.api_key_queue.get() - args = list(args)[1:] - ret = func(api_key, *args, **kwargs) - self.api_key_queue.put(api_key) - return ret - - return wrapped - - -state = State() diff --git a/spaces/xp3857/Image_Restoration_Colorization/Global/detection_models/sync_batchnorm/__init__.py b/spaces/xp3857/Image_Restoration_Colorization/Global/detection_models/sync_batchnorm/__init__.py deleted file mode 100644 index 6d9b36c74b1808b56ded68cf080a689db7e0ee4e..0000000000000000000000000000000000000000 --- a/spaces/xp3857/Image_Restoration_Colorization/Global/detection_models/sync_batchnorm/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# -*- coding: utf-8 -*- -# File : __init__.py -# Author : Jiayuan Mao -# Email : maojiayuan@gmail.com -# Date : 27/01/2018 -# -# This file is part of Synchronized-BatchNorm-PyTorch. -# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch -# Distributed under MIT License. - -from .batchnorm import set_sbn_eps_mode -from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d -from .batchnorm import patch_sync_batchnorm, convert_model -from .replicate import DataParallelWithCallback, patch_replication_callback diff --git a/spaces/xwsm/gpt/crazy_functions/test_project/cpp/longcode/jpgd.cpp b/spaces/xwsm/gpt/crazy_functions/test_project/cpp/longcode/jpgd.cpp deleted file mode 100644 index 36d06c8e9068570c3e7624895d474f33dbfe3d29..0000000000000000000000000000000000000000 --- a/spaces/xwsm/gpt/crazy_functions/test_project/cpp/longcode/jpgd.cpp +++ /dev/null @@ -1,3276 +0,0 @@ -// jpgd.cpp - C++ class for JPEG decompression. -// Public domain, Rich Geldreich -// Last updated Apr. 16, 2011 -// Alex Evans: Linear memory allocator (taken from jpge.h). -// -// Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2. -// -// Chroma upsampling quality: H2V2 is upsampled in the frequency domain, H2V1 and H1V2 are upsampled using point sampling. -// Chroma upsampling reference: "Fast Scheme for Image Size Change in the Compressed Domain" -// http://vision.ai.uiuc.edu/~dugad/research/dct/index.html - -#include "jpgd.h" -#include - -#include -// BEGIN EPIC MOD -#define JPGD_ASSERT(x) { assert(x); CA_ASSUME(x); } (void)0 -// END EPIC MOD - -#ifdef _MSC_VER -#pragma warning (disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable -#endif - -// Set to 1 to enable freq. domain chroma upsampling on images using H2V2 subsampling (0=faster nearest neighbor sampling). -// This is slower, but results in higher quality on images with highly saturated colors. -#define JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING 1 - -#define JPGD_TRUE (1) -#define JPGD_FALSE (0) - -#define JPGD_MAX(a,b) (((a)>(b)) ? (a) : (b)) -#define JPGD_MIN(a,b) (((a)<(b)) ? (a) : (b)) - -namespace jpgd { - - static inline void *jpgd_malloc(size_t nSize) { return FMemory::Malloc(nSize); } - static inline void jpgd_free(void *p) { FMemory::Free(p); } - -// BEGIN EPIC MOD -//@UE3 - use UE3 BGRA encoding instead of assuming RGBA - // stolen from IImageWrapper.h - enum ERGBFormatJPG - { - Invalid = -1, - RGBA = 0, - BGRA = 1, - Gray = 2, - }; - static ERGBFormatJPG jpg_format; -// END EPIC MOD - - // DCT coefficients are stored in this sequence. - static int g_ZAG[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 }; - - enum JPEG_MARKER - { - M_SOF0 = 0xC0, M_SOF1 = 0xC1, M_SOF2 = 0xC2, M_SOF3 = 0xC3, M_SOF5 = 0xC5, M_SOF6 = 0xC6, M_SOF7 = 0xC7, M_JPG = 0xC8, - M_SOF9 = 0xC9, M_SOF10 = 0xCA, M_SOF11 = 0xCB, M_SOF13 = 0xCD, M_SOF14 = 0xCE, M_SOF15 = 0xCF, M_DHT = 0xC4, M_DAC = 0xCC, - M_RST0 = 0xD0, M_RST1 = 0xD1, M_RST2 = 0xD2, M_RST3 = 0xD3, M_RST4 = 0xD4, M_RST5 = 0xD5, M_RST6 = 0xD6, M_RST7 = 0xD7, - M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_DNL = 0xDC, M_DRI = 0xDD, M_DHP = 0xDE, M_EXP = 0xDF, - M_APP0 = 0xE0, M_APP15 = 0xEF, M_JPG0 = 0xF0, M_JPG13 = 0xFD, M_COM = 0xFE, M_TEM = 0x01, M_ERROR = 0x100, RST0 = 0xD0 - }; - - enum JPEG_SUBSAMPLING { JPGD_GRAYSCALE = 0, JPGD_YH1V1, JPGD_YH2V1, JPGD_YH1V2, JPGD_YH2V2 }; - -#define CONST_BITS 13 -#define PASS1_BITS 2 -#define SCALEDONE ((int32)1) - -#define FIX_0_298631336 ((int32)2446) /* FIX(0.298631336) */ -#define FIX_0_390180644 ((int32)3196) /* FIX(0.390180644) */ -#define FIX_0_541196100 ((int32)4433) /* FIX(0.541196100) */ -#define FIX_0_765366865 ((int32)6270) /* FIX(0.765366865) */ -#define FIX_0_899976223 ((int32)7373) /* FIX(0.899976223) */ -#define FIX_1_175875602 ((int32)9633) /* FIX(1.175875602) */ -#define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */ -#define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */ -#define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */ -#define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */ -#define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */ -#define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */ - -#define DESCALE(x,n) (((x) + (SCALEDONE << ((n)-1))) >> (n)) -#define DESCALE_ZEROSHIFT(x,n) (((x) + (128 << (n)) + (SCALEDONE << ((n)-1))) >> (n)) - -#define MULTIPLY(var, cnst) ((var) * (cnst)) - -#define CLAMP(i) ((static_cast(i) > 255) ? (((~i) >> 31) & 0xFF) : (i)) - - // Compiler creates a fast path 1D IDCT for X non-zero columns - template - struct Row - { - static void idct(int* pTemp, const jpgd_block_t* pSrc) - { - // ACCESS_COL() will be optimized at compile time to either an array access, or 0. -#define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0) - - const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6); - - const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100); - const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065); - const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865); - - const int tmp0 = (ACCESS_COL(0) + ACCESS_COL(4)) << CONST_BITS; - const int tmp1 = (ACCESS_COL(0) - ACCESS_COL(4)) << CONST_BITS; - - const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2; - - const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1); - - const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3; - const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602); - - const int az1 = MULTIPLY(bz1, - FIX_0_899976223); - const int az2 = MULTIPLY(bz2, - FIX_2_562915447); - const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5; - const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5; - - const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3; - const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4; - const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3; - const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4; - - pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS-PASS1_BITS); - pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS-PASS1_BITS); - pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS-PASS1_BITS); - pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS-PASS1_BITS); - pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS-PASS1_BITS); - pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS-PASS1_BITS); - pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS-PASS1_BITS); - pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS-PASS1_BITS); - } - }; - - template <> - struct Row<0> - { - static void idct(int* pTemp, const jpgd_block_t* pSrc) - { -#ifdef _MSC_VER - pTemp; pSrc; -#endif - } - }; - - template <> - struct Row<1> - { - static void idct(int* pTemp, const jpgd_block_t* pSrc) - { - const int dcval = (pSrc[0] << PASS1_BITS); - - pTemp[0] = dcval; - pTemp[1] = dcval; - pTemp[2] = dcval; - pTemp[3] = dcval; - pTemp[4] = dcval; - pTemp[5] = dcval; - pTemp[6] = dcval; - pTemp[7] = dcval; - } - }; - - // Compiler creates a fast path 1D IDCT for X non-zero rows - template - struct Col - { - static void idct(uint8* pDst_ptr, const int* pTemp) - { - // ACCESS_ROW() will be optimized at compile time to either an array access, or 0. -#define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0) - - const int z2 = ACCESS_ROW(2); - const int z3 = ACCESS_ROW(6); - - const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100); - const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065); - const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865); - - const int tmp0 = (ACCESS_ROW(0) + ACCESS_ROW(4)) << CONST_BITS; - const int tmp1 = (ACCESS_ROW(0) - ACCESS_ROW(4)) << CONST_BITS; - - const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2; - - const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1); - - const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3; - const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602); - - const int az1 = MULTIPLY(bz1, - FIX_0_899976223); - const int az2 = MULTIPLY(bz2, - FIX_2_562915447); - const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5; - const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5; - - const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3; - const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4; - const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3; - const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4; - - int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*0] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*7] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*1] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*6] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*2] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*5] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*3] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*4] = (uint8)CLAMP(i); - } - }; - - template <> - struct Col<1> - { - static void idct(uint8* pDst_ptr, const int* pTemp) - { - int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS+3); - const uint8 dcval_clamped = (uint8)CLAMP(dcval); - pDst_ptr[0*8] = dcval_clamped; - pDst_ptr[1*8] = dcval_clamped; - pDst_ptr[2*8] = dcval_clamped; - pDst_ptr[3*8] = dcval_clamped; - pDst_ptr[4*8] = dcval_clamped; - pDst_ptr[5*8] = dcval_clamped; - pDst_ptr[6*8] = dcval_clamped; - pDst_ptr[7*8] = dcval_clamped; - } - }; - - static const uint8 s_idct_row_table[] = - { - 1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0, 2,1,1,0,0,0,0,0, 2,2,1,0,0,0,0,0, 3,2,1,0,0,0,0,0, 4,2,1,0,0,0,0,0, 4,3,1,0,0,0,0,0, - 4,3,2,0,0,0,0,0, 4,3,2,1,0,0,0,0, 4,3,2,1,1,0,0,0, 4,3,2,2,1,0,0,0, 4,3,3,2,1,0,0,0, 4,4,3,2,1,0,0,0, 5,4,3,2,1,0,0,0, 6,4,3,2,1,0,0,0, - 6,5,3,2,1,0,0,0, 6,5,4,2,1,0,0,0, 6,5,4,3,1,0,0,0, 6,5,4,3,2,0,0,0, 6,5,4,3,2,1,0,0, 6,5,4,3,2,1,1,0, 6,5,4,3,2,2,1,0, 6,5,4,3,3,2,1,0, - 6,5,4,4,3,2,1,0, 6,5,5,4,3,2,1,0, 6,6,5,4,3,2,1,0, 7,6,5,4,3,2,1,0, 8,6,5,4,3,2,1,0, 8,7,5,4,3,2,1,0, 8,7,6,4,3,2,1,0, 8,7,6,5,3,2,1,0, - 8,7,6,5,4,2,1,0, 8,7,6,5,4,3,1,0, 8,7,6,5,4,3,2,0, 8,7,6,5,4,3,2,1, 8,7,6,5,4,3,2,2, 8,7,6,5,4,3,3,2, 8,7,6,5,4,4,3,2, 8,7,6,5,5,4,3,2, - 8,7,6,6,5,4,3,2, 8,7,7,6,5,4,3,2, 8,8,7,6,5,4,3,2, 8,8,8,6,5,4,3,2, 8,8,8,7,5,4,3,2, 8,8,8,7,6,4,3,2, 8,8,8,7,6,5,3,2, 8,8,8,7,6,5,4,2, - 8,8,8,7,6,5,4,3, 8,8,8,7,6,5,4,4, 8,8,8,7,6,5,5,4, 8,8,8,7,6,6,5,4, 8,8,8,7,7,6,5,4, 8,8,8,8,7,6,5,4, 8,8,8,8,8,6,5,4, 8,8,8,8,8,7,5,4, - 8,8,8,8,8,7,6,4, 8,8,8,8,8,7,6,5, 8,8,8,8,8,7,6,6, 8,8,8,8,8,7,7,6, 8,8,8,8,8,8,7,6, 8,8,8,8,8,8,8,6, 8,8,8,8,8,8,8,7, 8,8,8,8,8,8,8,8, - }; - - static const uint8 s_idct_col_table[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; - - void idct(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr, int block_max_zag) - { - JPGD_ASSERT(block_max_zag >= 1); - JPGD_ASSERT(block_max_zag <= 64); - - if (block_max_zag == 1) - { - int k = ((pSrc_ptr[0] + 4) >> 3) + 128; - k = CLAMP(k); - k = k | (k<<8); - k = k | (k<<16); - - for (int i = 8; i > 0; i--) - { - *(int*)&pDst_ptr[0] = k; - *(int*)&pDst_ptr[4] = k; - pDst_ptr += 8; - } - return; - } - - int temp[64]; - - const jpgd_block_t* pSrc = pSrc_ptr; - int* pTemp = temp; - - const uint8* pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8]; - int i; - for (i = 8; i > 0; i--, pRow_tab++) - { - switch (*pRow_tab) - { - case 0: Row<0>::idct(pTemp, pSrc); break; - case 1: Row<1>::idct(pTemp, pSrc); break; - case 2: Row<2>::idct(pTemp, pSrc); break; - case 3: Row<3>::idct(pTemp, pSrc); break; - case 4: Row<4>::idct(pTemp, pSrc); break; - case 5: Row<5>::idct(pTemp, pSrc); break; - case 6: Row<6>::idct(pTemp, pSrc); break; - case 7: Row<7>::idct(pTemp, pSrc); break; - case 8: Row<8>::idct(pTemp, pSrc); break; - } - - pSrc += 8; - pTemp += 8; - } - - pTemp = temp; - - const int nonzero_rows = s_idct_col_table[block_max_zag - 1]; - for (i = 8; i > 0; i--) - { - switch (nonzero_rows) - { - case 1: Col<1>::idct(pDst_ptr, pTemp); break; - case 2: Col<2>::idct(pDst_ptr, pTemp); break; - case 3: Col<3>::idct(pDst_ptr, pTemp); break; - case 4: Col<4>::idct(pDst_ptr, pTemp); break; - case 5: Col<5>::idct(pDst_ptr, pTemp); break; - case 6: Col<6>::idct(pDst_ptr, pTemp); break; - case 7: Col<7>::idct(pDst_ptr, pTemp); break; - case 8: Col<8>::idct(pDst_ptr, pTemp); break; - } - - pTemp++; - pDst_ptr++; - } - } - - void idct_4x4(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr) - { - int temp[64]; - int* pTemp = temp; - const jpgd_block_t* pSrc = pSrc_ptr; - - for (int i = 4; i > 0; i--) - { - Row<4>::idct(pTemp, pSrc); - pSrc += 8; - pTemp += 8; - } - - pTemp = temp; - for (int i = 8; i > 0; i--) - { - Col<4>::idct(pDst_ptr, pTemp); - pTemp++; - pDst_ptr++; - } - } - - // Retrieve one character from the input stream. - inline uint jpeg_decoder::get_char() - { - // Any bytes remaining in buffer? - if (!m_in_buf_left) - { - // Try to get more bytes. - prep_in_buffer(); - // Still nothing to get? - if (!m_in_buf_left) - { - // Pad the end of the stream with 0xFF 0xD9 (EOI marker) - int t = m_tem_flag; - m_tem_flag ^= 1; - if (t) - return 0xD9; - else - return 0xFF; - } - } - - uint c = *m_pIn_buf_ofs++; - m_in_buf_left--; - - return c; - } - - // Same as previous method, except can indicate if the character is a pad character or not. - inline uint jpeg_decoder::get_char(bool *pPadding_flag) - { - if (!m_in_buf_left) - { - prep_in_buffer(); - if (!m_in_buf_left) - { - *pPadding_flag = true; - int t = m_tem_flag; - m_tem_flag ^= 1; - if (t) - return 0xD9; - else - return 0xFF; - } - } - - *pPadding_flag = false; - - uint c = *m_pIn_buf_ofs++; - m_in_buf_left--; - - return c; - } - - // Inserts a previously retrieved character back into the input buffer. - inline void jpeg_decoder::stuff_char(uint8 q) - { - *(--m_pIn_buf_ofs) = q; - m_in_buf_left++; - } - - // Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered. - inline uint8 jpeg_decoder::get_octet() - { - bool padding_flag; - int c = get_char(&padding_flag); - - if (c == 0xFF) - { - if (padding_flag) - return 0xFF; - - c = get_char(&padding_flag); - if (padding_flag) - { - stuff_char(0xFF); - return 0xFF; - } - - if (c == 0x00) - return 0xFF; - else - { - stuff_char(static_cast(c)); - stuff_char(0xFF); - return 0xFF; - } - } - - return static_cast(c); - } - - // Retrieves a variable number of bits from the input stream. Does not recognize markers. - inline uint jpeg_decoder::get_bits(int num_bits) - { - if (!num_bits) - return 0; - - uint i = m_bit_buf >> (32 - num_bits); - - if ((m_bits_left -= num_bits) <= 0) - { - m_bit_buf <<= (num_bits += m_bits_left); - - uint c1 = get_char(); - uint c2 = get_char(); - m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2; - - m_bit_buf <<= -m_bits_left; - - m_bits_left += 16; - - JPGD_ASSERT(m_bits_left >= 0); - } - else - m_bit_buf <<= num_bits; - - return i; - } - - // Retrieves a variable number of bits from the input stream. Markers will not be read into the input bit buffer. Instead, an infinite number of all 1's will be returned when a marker is encountered. - inline uint jpeg_decoder::get_bits_no_markers(int num_bits) - { - if (!num_bits) - return 0; - - uint i = m_bit_buf >> (32 - num_bits); - - if ((m_bits_left -= num_bits) <= 0) - { - m_bit_buf <<= (num_bits += m_bits_left); - - if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF)) - { - uint c1 = get_octet(); - uint c2 = get_octet(); - m_bit_buf |= (c1 << 8) | c2; - } - else - { - m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1]; - m_in_buf_left -= 2; - m_pIn_buf_ofs += 2; - } - - m_bit_buf <<= -m_bits_left; - - m_bits_left += 16; - - JPGD_ASSERT(m_bits_left >= 0); - } - else - m_bit_buf <<= num_bits; - - return i; - } - - // Decodes a Huffman encoded symbol. - inline int jpeg_decoder::huff_decode(huff_tables *pH) - { - int symbol; - - // Check first 8-bits: do we have a complete symbol? - if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0) - { - // Decode more bits, use a tree traversal to find symbol. - int ofs = 23; - do - { - symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))]; - ofs--; - } while (symbol < 0); - - get_bits_no_markers(8 + (23 - ofs)); - } - else - get_bits_no_markers(pH->code_size[symbol]); - - return symbol; - } - - // Decodes a Huffman encoded symbol. - inline int jpeg_decoder::huff_decode(huff_tables *pH, int& extra_bits) - { - int symbol; - - // Check first 8-bits: do we have a complete symbol? - if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0) - { - // Use a tree traversal to find symbol. - int ofs = 23; - do - { - symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))]; - ofs--; - } while (symbol < 0); - - get_bits_no_markers(8 + (23 - ofs)); - - extra_bits = get_bits_no_markers(symbol & 0xF); - } - else - { - JPGD_ASSERT(((symbol >> 8) & 31) == pH->code_size[symbol & 255] + ((symbol & 0x8000) ? (symbol & 15) : 0)); - - if (symbol & 0x8000) - { - get_bits_no_markers((symbol >> 8) & 31); - extra_bits = symbol >> 16; - } - else - { - int code_size = (symbol >> 8) & 31; - int num_extra_bits = symbol & 0xF; - int bits = code_size + num_extra_bits; - if (bits <= (m_bits_left + 16)) - extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1); - else - { - get_bits_no_markers(code_size); - extra_bits = get_bits_no_markers(num_extra_bits); - } - } - - symbol &= 0xFF; - } - - return symbol; - } - - // Tables and macro used to fully decode the DPCM differences. - static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 }; - static const int s_extend_offset[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 }; - static const int s_extend_mask[] = { 0, (1<<0), (1<<1), (1<<2), (1<<3), (1<<4), (1<<5), (1<<6), (1<<7), (1<<8), (1<<9), (1<<10), (1<<11), (1<<12), (1<<13), (1<<14), (1<<15), (1<<16) }; -#define HUFF_EXTEND(x,s) ((x) < s_extend_test[s] ? (x) + s_extend_offset[s] : (x)) - - // Clamps a value between 0-255. - inline uint8 jpeg_decoder::clamp(int i) - { - if (static_cast(i) > 255) - i = (((~i) >> 31) & 0xFF); - - return static_cast(i); - } - - namespace DCT_Upsample - { - struct Matrix44 - { - typedef int Element_Type; - enum { NUM_ROWS = 4, NUM_COLS = 4 }; - - Element_Type v[NUM_ROWS][NUM_COLS]; - - inline int rows() const { return NUM_ROWS; } - inline int cols() const { return NUM_COLS; } - - inline const Element_Type & at(int r, int c) const { return v[r][c]; } - inline Element_Type & at(int r, int c) { return v[r][c]; } - - inline Matrix44() { } - - inline Matrix44& operator += (const Matrix44& a) - { - for (int r = 0; r < NUM_ROWS; r++) - { - at(r, 0) += a.at(r, 0); - at(r, 1) += a.at(r, 1); - at(r, 2) += a.at(r, 2); - at(r, 3) += a.at(r, 3); - } - return *this; - } - - inline Matrix44& operator -= (const Matrix44& a) - { - for (int r = 0; r < NUM_ROWS; r++) - { - at(r, 0) -= a.at(r, 0); - at(r, 1) -= a.at(r, 1); - at(r, 2) -= a.at(r, 2); - at(r, 3) -= a.at(r, 3); - } - return *this; - } - - friend inline Matrix44 operator + (const Matrix44& a, const Matrix44& b) - { - Matrix44 ret; - for (int r = 0; r < NUM_ROWS; r++) - { - ret.at(r, 0) = a.at(r, 0) + b.at(r, 0); - ret.at(r, 1) = a.at(r, 1) + b.at(r, 1); - ret.at(r, 2) = a.at(r, 2) + b.at(r, 2); - ret.at(r, 3) = a.at(r, 3) + b.at(r, 3); - } - return ret; - } - - friend inline Matrix44 operator - (const Matrix44& a, const Matrix44& b) - { - Matrix44 ret; - for (int r = 0; r < NUM_ROWS; r++) - { - ret.at(r, 0) = a.at(r, 0) - b.at(r, 0); - ret.at(r, 1) = a.at(r, 1) - b.at(r, 1); - ret.at(r, 2) = a.at(r, 2) - b.at(r, 2); - ret.at(r, 3) = a.at(r, 3) - b.at(r, 3); - } - return ret; - } - - static inline void add_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b) - { - for (int r = 0; r < 4; r++) - { - pDst[0*8 + r] = static_cast(a.at(r, 0) + b.at(r, 0)); - pDst[1*8 + r] = static_cast(a.at(r, 1) + b.at(r, 1)); - pDst[2*8 + r] = static_cast(a.at(r, 2) + b.at(r, 2)); - pDst[3*8 + r] = static_cast(a.at(r, 3) + b.at(r, 3)); - } - } - - static inline void sub_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b) - { - for (int r = 0; r < 4; r++) - { - pDst[0*8 + r] = static_cast(a.at(r, 0) - b.at(r, 0)); - pDst[1*8 + r] = static_cast(a.at(r, 1) - b.at(r, 1)); - pDst[2*8 + r] = static_cast(a.at(r, 2) - b.at(r, 2)); - pDst[3*8 + r] = static_cast(a.at(r, 3) - b.at(r, 3)); - } - } - }; - - const int FRACT_BITS = 10; - const int SCALE = 1 << FRACT_BITS; - - typedef int Temp_Type; -#define D(i) (((i) + (SCALE >> 1)) >> FRACT_BITS) -#define F(i) ((int)((i) * SCALE + .5f)) - - // Any decent C++ compiler will optimize this at compile time to a 0, or an array access. -#define AT(c, r) ((((c)>=NUM_COLS)||((r)>=NUM_ROWS)) ? 0 : pSrc[(c)+(r)*8]) - - // NUM_ROWS/NUM_COLS = # of non-zero rows/cols in input matrix - template - struct P_Q - { - static void calc(Matrix44& P, Matrix44& Q, const jpgd_block_t* pSrc) - { - // 4x8 = 4x8 times 8x8, matrix 0 is constant - const Temp_Type X000 = AT(0, 0); - const Temp_Type X001 = AT(0, 1); - const Temp_Type X002 = AT(0, 2); - const Temp_Type X003 = AT(0, 3); - const Temp_Type X004 = AT(0, 4); - const Temp_Type X005 = AT(0, 5); - const Temp_Type X006 = AT(0, 6); - const Temp_Type X007 = AT(0, 7); - const Temp_Type X010 = D(F(0.415735f) * AT(1, 0) + F(0.791065f) * AT(3, 0) + F(-0.352443f) * AT(5, 0) + F(0.277785f) * AT(7, 0)); - const Temp_Type X011 = D(F(0.415735f) * AT(1, 1) + F(0.791065f) * AT(3, 1) + F(-0.352443f) * AT(5, 1) + F(0.277785f) * AT(7, 1)); - const Temp_Type X012 = D(F(0.415735f) * AT(1, 2) + F(0.791065f) * AT(3, 2) + F(-0.352443f) * AT(5, 2) + F(0.277785f) * AT(7, 2)); - const Temp_Type X013 = D(F(0.415735f) * AT(1, 3) + F(0.791065f) * AT(3, 3) + F(-0.352443f) * AT(5, 3) + F(0.277785f) * AT(7, 3)); - const Temp_Type X014 = D(F(0.415735f) * AT(1, 4) + F(0.791065f) * AT(3, 4) + F(-0.352443f) * AT(5, 4) + F(0.277785f) * AT(7, 4)); - const Temp_Type X015 = D(F(0.415735f) * AT(1, 5) + F(0.791065f) * AT(3, 5) + F(-0.352443f) * AT(5, 5) + F(0.277785f) * AT(7, 5)); - const Temp_Type X016 = D(F(0.415735f) * AT(1, 6) + F(0.791065f) * AT(3, 6) + F(-0.352443f) * AT(5, 6) + F(0.277785f) * AT(7, 6)); - const Temp_Type X017 = D(F(0.415735f) * AT(1, 7) + F(0.791065f) * AT(3, 7) + F(-0.352443f) * AT(5, 7) + F(0.277785f) * AT(7, 7)); - const Temp_Type X020 = AT(4, 0); - const Temp_Type X021 = AT(4, 1); - const Temp_Type X022 = AT(4, 2); - const Temp_Type X023 = AT(4, 3); - const Temp_Type X024 = AT(4, 4); - const Temp_Type X025 = AT(4, 5); - const Temp_Type X026 = AT(4, 6); - const Temp_Type X027 = AT(4, 7); - const Temp_Type X030 = D(F(0.022887f) * AT(1, 0) + F(-0.097545f) * AT(3, 0) + F(0.490393f) * AT(5, 0) + F(0.865723f) * AT(7, 0)); - const Temp_Type X031 = D(F(0.022887f) * AT(1, 1) + F(-0.097545f) * AT(3, 1) + F(0.490393f) * AT(5, 1) + F(0.865723f) * AT(7, 1)); - const Temp_Type X032 = D(F(0.022887f) * AT(1, 2) + F(-0.097545f) * AT(3, 2) + F(0.490393f) * AT(5, 2) + F(0.865723f) * AT(7, 2)); - const Temp_Type X033 = D(F(0.022887f) * AT(1, 3) + F(-0.097545f) * AT(3, 3) + F(0.490393f) * AT(5, 3) + F(0.865723f) * AT(7, 3)); - const Temp_Type X034 = D(F(0.022887f) * AT(1, 4) + F(-0.097545f) * AT(3, 4) + F(0.490393f) * AT(5, 4) + F(0.865723f) * AT(7, 4)); - const Temp_Type X035 = D(F(0.022887f) * AT(1, 5) + F(-0.097545f) * AT(3, 5) + F(0.490393f) * AT(5, 5) + F(0.865723f) * AT(7, 5)); - const Temp_Type X036 = D(F(0.022887f) * AT(1, 6) + F(-0.097545f) * AT(3, 6) + F(0.490393f) * AT(5, 6) + F(0.865723f) * AT(7, 6)); - const Temp_Type X037 = D(F(0.022887f) * AT(1, 7) + F(-0.097545f) * AT(3, 7) + F(0.490393f) * AT(5, 7) + F(0.865723f) * AT(7, 7)); - - // 4x4 = 4x8 times 8x4, matrix 1 is constant - P.at(0, 0) = X000; - P.at(0, 1) = D(X001 * F(0.415735f) + X003 * F(0.791065f) + X005 * F(-0.352443f) + X007 * F(0.277785f)); - P.at(0, 2) = X004; - P.at(0, 3) = D(X001 * F(0.022887f) + X003 * F(-0.097545f) + X005 * F(0.490393f) + X007 * F(0.865723f)); - P.at(1, 0) = X010; - P.at(1, 1) = D(X011 * F(0.415735f) + X013 * F(0.791065f) + X015 * F(-0.352443f) + X017 * F(0.277785f)); - P.at(1, 2) = X014; - P.at(1, 3) = D(X011 * F(0.022887f) + X013 * F(-0.097545f) + X015 * F(0.490393f) + X017 * F(0.865723f)); - P.at(2, 0) = X020; - P.at(2, 1) = D(X021 * F(0.415735f) + X023 * F(0.791065f) + X025 * F(-0.352443f) + X027 * F(0.277785f)); - P.at(2, 2) = X024; - P.at(2, 3) = D(X021 * F(0.022887f) + X023 * F(-0.097545f) + X025 * F(0.490393f) + X027 * F(0.865723f)); - P.at(3, 0) = X030; - P.at(3, 1) = D(X031 * F(0.415735f) + X033 * F(0.791065f) + X035 * F(-0.352443f) + X037 * F(0.277785f)); - P.at(3, 2) = X034; - P.at(3, 3) = D(X031 * F(0.022887f) + X033 * F(-0.097545f) + X035 * F(0.490393f) + X037 * F(0.865723f)); - // 40 muls 24 adds - - // 4x4 = 4x8 times 8x4, matrix 1 is constant - Q.at(0, 0) = D(X001 * F(0.906127f) + X003 * F(-0.318190f) + X005 * F(0.212608f) + X007 * F(-0.180240f)); - Q.at(0, 1) = X002; - Q.at(0, 2) = D(X001 * F(-0.074658f) + X003 * F(0.513280f) + X005 * F(0.768178f) + X007 * F(-0.375330f)); - Q.at(0, 3) = X006; - Q.at(1, 0) = D(X011 * F(0.906127f) + X013 * F(-0.318190f) + X015 * F(0.212608f) + X017 * F(-0.180240f)); - Q.at(1, 1) = X012; - Q.at(1, 2) = D(X011 * F(-0.074658f) + X013 * F(0.513280f) + X015 * F(0.768178f) + X017 * F(-0.375330f)); - Q.at(1, 3) = X016; - Q.at(2, 0) = D(X021 * F(0.906127f) + X023 * F(-0.318190f) + X025 * F(0.212608f) + X027 * F(-0.180240f)); - Q.at(2, 1) = X022; - Q.at(2, 2) = D(X021 * F(-0.074658f) + X023 * F(0.513280f) + X025 * F(0.768178f) + X027 * F(-0.375330f)); - Q.at(2, 3) = X026; - Q.at(3, 0) = D(X031 * F(0.906127f) + X033 * F(-0.318190f) + X035 * F(0.212608f) + X037 * F(-0.180240f)); - Q.at(3, 1) = X032; - Q.at(3, 2) = D(X031 * F(-0.074658f) + X033 * F(0.513280f) + X035 * F(0.768178f) + X037 * F(-0.375330f)); - Q.at(3, 3) = X036; - // 40 muls 24 adds - } - }; - - template - struct R_S - { - static void calc(Matrix44& R, Matrix44& S, const jpgd_block_t* pSrc) - { - // 4x8 = 4x8 times 8x8, matrix 0 is constant - const Temp_Type X100 = D(F(0.906127f) * AT(1, 0) + F(-0.318190f) * AT(3, 0) + F(0.212608f) * AT(5, 0) + F(-0.180240f) * AT(7, 0)); - const Temp_Type X101 = D(F(0.906127f) * AT(1, 1) + F(-0.318190f) * AT(3, 1) + F(0.212608f) * AT(5, 1) + F(-0.180240f) * AT(7, 1)); - const Temp_Type X102 = D(F(0.906127f) * AT(1, 2) + F(-0.318190f) * AT(3, 2) + F(0.212608f) * AT(5, 2) + F(-0.180240f) * AT(7, 2)); - const Temp_Type X103 = D(F(0.906127f) * AT(1, 3) + F(-0.318190f) * AT(3, 3) + F(0.212608f) * AT(5, 3) + F(-0.180240f) * AT(7, 3)); - const Temp_Type X104 = D(F(0.906127f) * AT(1, 4) + F(-0.318190f) * AT(3, 4) + F(0.212608f) * AT(5, 4) + F(-0.180240f) * AT(7, 4)); - const Temp_Type X105 = D(F(0.906127f) * AT(1, 5) + F(-0.318190f) * AT(3, 5) + F(0.212608f) * AT(5, 5) + F(-0.180240f) * AT(7, 5)); - const Temp_Type X106 = D(F(0.906127f) * AT(1, 6) + F(-0.318190f) * AT(3, 6) + F(0.212608f) * AT(5, 6) + F(-0.180240f) * AT(7, 6)); - const Temp_Type X107 = D(F(0.906127f) * AT(1, 7) + F(-0.318190f) * AT(3, 7) + F(0.212608f) * AT(5, 7) + F(-0.180240f) * AT(7, 7)); - const Temp_Type X110 = AT(2, 0); - const Temp_Type X111 = AT(2, 1); - const Temp_Type X112 = AT(2, 2); - const Temp_Type X113 = AT(2, 3); - const Temp_Type X114 = AT(2, 4); - const Temp_Type X115 = AT(2, 5); - const Temp_Type X116 = AT(2, 6); - const Temp_Type X117 = AT(2, 7); - const Temp_Type X120 = D(F(-0.074658f) * AT(1, 0) + F(0.513280f) * AT(3, 0) + F(0.768178f) * AT(5, 0) + F(-0.375330f) * AT(7, 0)); - const Temp_Type X121 = D(F(-0.074658f) * AT(1, 1) + F(0.513280f) * AT(3, 1) + F(0.768178f) * AT(5, 1) + F(-0.375330f) * AT(7, 1)); - const Temp_Type X122 = D(F(-0.074658f) * AT(1, 2) + F(0.513280f) * AT(3, 2) + F(0.768178f) * AT(5, 2) + F(-0.375330f) * AT(7, 2)); - const Temp_Type X123 = D(F(-0.074658f) * AT(1, 3) + F(0.513280f) * AT(3, 3) + F(0.768178f) * AT(5, 3) + F(-0.375330f) * AT(7, 3)); - const Temp_Type X124 = D(F(-0.074658f) * AT(1, 4) + F(0.513280f) * AT(3, 4) + F(0.768178f) * AT(5, 4) + F(-0.375330f) * AT(7, 4)); - const Temp_Type X125 = D(F(-0.074658f) * AT(1, 5) + F(0.513280f) * AT(3, 5) + F(0.768178f) * AT(5, 5) + F(-0.375330f) * AT(7, 5)); - const Temp_Type X126 = D(F(-0.074658f) * AT(1, 6) + F(0.513280f) * AT(3, 6) + F(0.768178f) * AT(5, 6) + F(-0.375330f) * AT(7, 6)); - const Temp_Type X127 = D(F(-0.074658f) * AT(1, 7) + F(0.513280f) * AT(3, 7) + F(0.768178f) * AT(5, 7) + F(-0.375330f) * AT(7, 7)); - const Temp_Type X130 = AT(6, 0); - const Temp_Type X131 = AT(6, 1); - const Temp_Type X132 = AT(6, 2); - const Temp_Type X133 = AT(6, 3); - const Temp_Type X134 = AT(6, 4); - const Temp_Type X135 = AT(6, 5); - const Temp_Type X136 = AT(6, 6); - const Temp_Type X137 = AT(6, 7); - // 80 muls 48 adds - - // 4x4 = 4x8 times 8x4, matrix 1 is constant - R.at(0, 0) = X100; - R.at(0, 1) = D(X101 * F(0.415735f) + X103 * F(0.791065f) + X105 * F(-0.352443f) + X107 * F(0.277785f)); - R.at(0, 2) = X104; - R.at(0, 3) = D(X101 * F(0.022887f) + X103 * F(-0.097545f) + X105 * F(0.490393f) + X107 * F(0.865723f)); - R.at(1, 0) = X110; - R.at(1, 1) = D(X111 * F(0.415735f) + X113 * F(0.791065f) + X115 * F(-0.352443f) + X117 * F(0.277785f)); - R.at(1, 2) = X114; - R.at(1, 3) = D(X111 * F(0.022887f) + X113 * F(-0.097545f) + X115 * F(0.490393f) + X117 * F(0.865723f)); - R.at(2, 0) = X120; - R.at(2, 1) = D(X121 * F(0.415735f) + X123 * F(0.791065f) + X125 * F(-0.352443f) + X127 * F(0.277785f)); - R.at(2, 2) = X124; - R.at(2, 3) = D(X121 * F(0.022887f) + X123 * F(-0.097545f) + X125 * F(0.490393f) + X127 * F(0.865723f)); - R.at(3, 0) = X130; - R.at(3, 1) = D(X131 * F(0.415735f) + X133 * F(0.791065f) + X135 * F(-0.352443f) + X137 * F(0.277785f)); - R.at(3, 2) = X134; - R.at(3, 3) = D(X131 * F(0.022887f) + X133 * F(-0.097545f) + X135 * F(0.490393f) + X137 * F(0.865723f)); - // 40 muls 24 adds - // 4x4 = 4x8 times 8x4, matrix 1 is constant - S.at(0, 0) = D(X101 * F(0.906127f) + X103 * F(-0.318190f) + X105 * F(0.212608f) + X107 * F(-0.180240f)); - S.at(0, 1) = X102; - S.at(0, 2) = D(X101 * F(-0.074658f) + X103 * F(0.513280f) + X105 * F(0.768178f) + X107 * F(-0.375330f)); - S.at(0, 3) = X106; - S.at(1, 0) = D(X111 * F(0.906127f) + X113 * F(-0.318190f) + X115 * F(0.212608f) + X117 * F(-0.180240f)); - S.at(1, 1) = X112; - S.at(1, 2) = D(X111 * F(-0.074658f) + X113 * F(0.513280f) + X115 * F(0.768178f) + X117 * F(-0.375330f)); - S.at(1, 3) = X116; - S.at(2, 0) = D(X121 * F(0.906127f) + X123 * F(-0.318190f) + X125 * F(0.212608f) + X127 * F(-0.180240f)); - S.at(2, 1) = X122; - S.at(2, 2) = D(X121 * F(-0.074658f) + X123 * F(0.513280f) + X125 * F(0.768178f) + X127 * F(-0.375330f)); - S.at(2, 3) = X126; - S.at(3, 0) = D(X131 * F(0.906127f) + X133 * F(-0.318190f) + X135 * F(0.212608f) + X137 * F(-0.180240f)); - S.at(3, 1) = X132; - S.at(3, 2) = D(X131 * F(-0.074658f) + X133 * F(0.513280f) + X135 * F(0.768178f) + X137 * F(-0.375330f)); - S.at(3, 3) = X136; - // 40 muls 24 adds - } - }; - } // end namespace DCT_Upsample - - // Unconditionally frees all allocated m_blocks. - void jpeg_decoder::free_all_blocks() - { - m_pStream = NULL; - for (mem_block *b = m_pMem_blocks; b; ) - { - mem_block *n = b->m_pNext; - jpgd_free(b); - b = n; - } - m_pMem_blocks = NULL; - } - - // This method handles all errors. - // It could easily be changed to use C++ exceptions. - void jpeg_decoder::stop_decoding(jpgd_status status) - { - m_error_code = status; - free_all_blocks(); - longjmp(m_jmp_state, status); - - // we shouldn't get here as longjmp shouldn't return, but we put it here to make it explicit - // that this function doesn't return, otherwise we get this error: - // - // error : function declared 'noreturn' should not return - exit(1); - } - - void *jpeg_decoder::alloc(size_t nSize, bool zero) - { - nSize = (JPGD_MAX(nSize, 1) + 3) & ~3; - char *rv = NULL; - for (mem_block *b = m_pMem_blocks; b; b = b->m_pNext) - { - if ((b->m_used_count + nSize) <= b->m_size) - { - rv = b->m_data + b->m_used_count; - b->m_used_count += nSize; - break; - } - } - if (!rv) - { - int capacity = JPGD_MAX(32768 - 256, (nSize + 2047) & ~2047); - mem_block *b = (mem_block*)jpgd_malloc(sizeof(mem_block) + capacity); - if (!b) stop_decoding(JPGD_NOTENOUGHMEM); - b->m_pNext = m_pMem_blocks; m_pMem_blocks = b; - b->m_used_count = nSize; - b->m_size = capacity; - rv = b->m_data; - } - if (zero) memset(rv, 0, nSize); - return rv; - } - - void jpeg_decoder::word_clear(void *p, uint16 c, uint n) - { - uint8 *pD = (uint8*)p; - const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF; - while (n) - { - pD[0] = l; pD[1] = h; pD += 2; - n--; - } - } - - // Refill the input buffer. - // This method will sit in a loop until (A) the buffer is full or (B) - // the stream's read() method reports and end of file condition. - void jpeg_decoder::prep_in_buffer() - { - m_in_buf_left = 0; - m_pIn_buf_ofs = m_in_buf; - - if (m_eof_flag) - return; - - do - { - int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag); - if (bytes_read == -1) - stop_decoding(JPGD_STREAM_READ); - - m_in_buf_left += bytes_read; - } while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag)); - - m_total_bytes_read += m_in_buf_left; - - // Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid). - // (This dates way back to when this decompressor was written in C/asm, and the all-asm Huffman decoder did some fancy things to increase perf.) - word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64); - } - - // Read a Huffman code table. - void jpeg_decoder::read_dht_marker() - { - int i, index, count; - uint8 huff_num[17]; - uint8 huff_val[256]; - - uint num_left = get_bits(16); - - if (num_left < 2) - stop_decoding(JPGD_BAD_DHT_MARKER); - - num_left -= 2; - - while (num_left) - { - index = get_bits(8); - - huff_num[0] = 0; - - count = 0; - - for (i = 1; i <= 16; i++) - { - huff_num[i] = static_cast(get_bits(8)); - count += huff_num[i]; - } - - if (count > 255) - stop_decoding(JPGD_BAD_DHT_COUNTS); - - for (i = 0; i < count; i++) - huff_val[i] = static_cast(get_bits(8)); - - i = 1 + 16 + count; - - if (num_left < (uint)i) - stop_decoding(JPGD_BAD_DHT_MARKER); - - num_left -= i; - - if ((index & 0x10) > 0x10) - stop_decoding(JPGD_BAD_DHT_INDEX); - - index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1); - - if (index >= JPGD_MAX_HUFF_TABLES) - stop_decoding(JPGD_BAD_DHT_INDEX); - - if (!m_huff_num[index]) - m_huff_num[index] = (uint8 *)alloc(17); - - if (!m_huff_val[index]) - m_huff_val[index] = (uint8 *)alloc(256); - - m_huff_ac[index] = (index & 0x10) != 0; - memcpy(m_huff_num[index], huff_num, 17); - memcpy(m_huff_val[index], huff_val, 256); - } - } - - // Read a quantization table. - void jpeg_decoder::read_dqt_marker() - { - int n, i, prec; - uint num_left; - uint temp; - - num_left = get_bits(16); - - if (num_left < 2) - stop_decoding(JPGD_BAD_DQT_MARKER); - - num_left -= 2; - - while (num_left) - { - n = get_bits(8); - prec = n >> 4; - n &= 0x0F; - - if (n >= JPGD_MAX_QUANT_TABLES) - stop_decoding(JPGD_BAD_DQT_TABLE); - - if (!m_quant[n]) - m_quant[n] = (jpgd_quant_t *)alloc(64 * sizeof(jpgd_quant_t)); - - // read quantization entries, in zag order - for (i = 0; i < 64; i++) - { - temp = get_bits(8); - - if (prec) - temp = (temp << 8) + get_bits(8); - - m_quant[n][i] = static_cast(temp); - } - - i = 64 + 1; - - if (prec) - i += 64; - - if (num_left < (uint)i) - stop_decoding(JPGD_BAD_DQT_LENGTH); - - num_left -= i; - } - } - - // Read the start of frame (SOF) marker. - void jpeg_decoder::read_sof_marker() - { - int i; - uint num_left; - - num_left = get_bits(16); - - if (get_bits(8) != 8) /* precision: sorry, only 8-bit precision is supported right now */ - stop_decoding(JPGD_BAD_PRECISION); - - m_image_y_size = get_bits(16); - - if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT)) - stop_decoding(JPGD_BAD_HEIGHT); - - m_image_x_size = get_bits(16); - - if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH)) - stop_decoding(JPGD_BAD_WIDTH); - - m_comps_in_frame = get_bits(8); - - if (m_comps_in_frame > JPGD_MAX_COMPONENTS) - stop_decoding(JPGD_TOO_MANY_COMPONENTS); - - if (num_left != (uint)(m_comps_in_frame * 3 + 8)) - stop_decoding(JPGD_BAD_SOF_LENGTH); - - for (i = 0; i < m_comps_in_frame; i++) - { - m_comp_ident[i] = get_bits(8); - m_comp_h_samp[i] = get_bits(4); - m_comp_v_samp[i] = get_bits(4); - m_comp_quant[i] = get_bits(8); - } - } - - // Used to skip unrecognized markers. - void jpeg_decoder::skip_variable_marker() - { - uint num_left; - - num_left = get_bits(16); - - if (num_left < 2) - stop_decoding(JPGD_BAD_VARIABLE_MARKER); - - num_left -= 2; - - while (num_left) - { - get_bits(8); - num_left--; - } - } - - // Read a define restart interval (DRI) marker. - void jpeg_decoder::read_dri_marker() - { - if (get_bits(16) != 4) - stop_decoding(JPGD_BAD_DRI_LENGTH); - - m_restart_interval = get_bits(16); - } - - // Read a start of scan (SOS) marker. - void jpeg_decoder::read_sos_marker() - { - uint num_left; - int i, ci, n, c, cc; - - num_left = get_bits(16); - - n = get_bits(8); - - m_comps_in_scan = n; - - num_left -= 3; - - if ( (num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN) ) - stop_decoding(JPGD_BAD_SOS_LENGTH); - - for (i = 0; i < n; i++) - { - cc = get_bits(8); - c = get_bits(8); - num_left -= 2; - - for (ci = 0; ci < m_comps_in_frame; ci++) - if (cc == m_comp_ident[ci]) - break; - - if (ci >= m_comps_in_frame) - stop_decoding(JPGD_BAD_SOS_COMP_ID); - - m_comp_list[i] = ci; - m_comp_dc_tab[ci] = (c >> 4) & 15; - m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1); - } - - m_spectral_start = get_bits(8); - m_spectral_end = get_bits(8); - m_successive_high = get_bits(4); - m_successive_low = get_bits(4); - - if (!m_progressive_flag) - { - m_spectral_start = 0; - m_spectral_end = 63; - } - - num_left -= 3; - - while (num_left) /* read past whatever is num_left */ - { - get_bits(8); - num_left--; - } - } - - // Finds the next marker. - int jpeg_decoder::next_marker() - { - uint c, bytes; - - bytes = 0; - - do - { - do - { - bytes++; - c = get_bits(8); - } while (c != 0xFF); - - do - { - c = get_bits(8); - } while (c == 0xFF); - - } while (c == 0); - - // If bytes > 0 here, there where extra bytes before the marker (not good). - - return c; - } - - // Process markers. Returns when an SOFx, SOI, EOI, or SOS marker is - // encountered. - int jpeg_decoder::process_markers() - { - int c; - - for ( ; ; ) - { - c = next_marker(); - - switch (c) - { - case M_SOF0: - case M_SOF1: - case M_SOF2: - case M_SOF3: - case M_SOF5: - case M_SOF6: - case M_SOF7: - // case M_JPG: - case M_SOF9: - case M_SOF10: - case M_SOF11: - case M_SOF13: - case M_SOF14: - case M_SOF15: - case M_SOI: - case M_EOI: - case M_SOS: - { - return c; - } - case M_DHT: - { - read_dht_marker(); - break; - } - // No arithmitic support - dumb patents! - case M_DAC: - { - stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT); - break; - } - case M_DQT: - { - read_dqt_marker(); - break; - } - case M_DRI: - { - read_dri_marker(); - break; - } - //case M_APP0: /* no need to read the JFIF marker */ - - case M_JPG: - case M_RST0: /* no parameters */ - case M_RST1: - case M_RST2: - case M_RST3: - case M_RST4: - case M_RST5: - case M_RST6: - case M_RST7: - case M_TEM: - { - stop_decoding(JPGD_UNEXPECTED_MARKER); - break; - } - default: /* must be DNL, DHP, EXP, APPn, JPGn, COM, or RESn or APP0 */ - { - skip_variable_marker(); - break; - } - } - } - } - - // Finds the start of image (SOI) marker. - // This code is rather defensive: it only checks the first 512 bytes to avoid - // false positives. - void jpeg_decoder::locate_soi_marker() - { - uint lastchar, thischar; - uint bytesleft; - - lastchar = get_bits(8); - - thischar = get_bits(8); - - /* ok if it's a normal JPEG file without a special header */ - - if ((lastchar == 0xFF) && (thischar == M_SOI)) - return; - - bytesleft = 4096; //512; - - for ( ; ; ) - { - if (--bytesleft == 0) - stop_decoding(JPGD_NOT_JPEG); - - lastchar = thischar; - - thischar = get_bits(8); - - if (lastchar == 0xFF) - { - if (thischar == M_SOI) - break; - else if (thischar == M_EOI) // get_bits will keep returning M_EOI if we read past the end - stop_decoding(JPGD_NOT_JPEG); - } - } - - // Check the next character after marker: if it's not 0xFF, it can't be the start of the next marker, so the file is bad. - thischar = (m_bit_buf >> 24) & 0xFF; - - if (thischar != 0xFF) - stop_decoding(JPGD_NOT_JPEG); - } - - // Find a start of frame (SOF) marker. - void jpeg_decoder::locate_sof_marker() - { - locate_soi_marker(); - - int c = process_markers(); - - switch (c) - { - case M_SOF2: - m_progressive_flag = JPGD_TRUE; - case M_SOF0: /* baseline DCT */ - case M_SOF1: /* extended sequential DCT */ - { - read_sof_marker(); - break; - } - case M_SOF9: /* Arithmitic coding */ - { - stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT); - break; - } - default: - { - stop_decoding(JPGD_UNSUPPORTED_MARKER); - break; - } - } - } - - // Find a start of scan (SOS) marker. - int jpeg_decoder::locate_sos_marker() - { - int c; - - c = process_markers(); - - if (c == M_EOI) - return JPGD_FALSE; - else if (c != M_SOS) - stop_decoding(JPGD_UNEXPECTED_MARKER); - - read_sos_marker(); - - return JPGD_TRUE; - } - - // Reset everything to default/uninitialized state. - void jpeg_decoder::init(jpeg_decoder_stream *pStream) - { - m_pMem_blocks = NULL; - m_error_code = JPGD_SUCCESS; - m_ready_flag = false; - m_image_x_size = m_image_y_size = 0; - m_pStream = pStream; - m_progressive_flag = JPGD_FALSE; - - memset(m_huff_ac, 0, sizeof(m_huff_ac)); - memset(m_huff_num, 0, sizeof(m_huff_num)); - memset(m_huff_val, 0, sizeof(m_huff_val)); - memset(m_quant, 0, sizeof(m_quant)); - - m_scan_type = 0; - m_comps_in_frame = 0; - - memset(m_comp_h_samp, 0, sizeof(m_comp_h_samp)); - memset(m_comp_v_samp, 0, sizeof(m_comp_v_samp)); - memset(m_comp_quant, 0, sizeof(m_comp_quant)); - memset(m_comp_ident, 0, sizeof(m_comp_ident)); - memset(m_comp_h_blocks, 0, sizeof(m_comp_h_blocks)); - memset(m_comp_v_blocks, 0, sizeof(m_comp_v_blocks)); - - m_comps_in_scan = 0; - memset(m_comp_list, 0, sizeof(m_comp_list)); - memset(m_comp_dc_tab, 0, sizeof(m_comp_dc_tab)); - memset(m_comp_ac_tab, 0, sizeof(m_comp_ac_tab)); - - m_spectral_start = 0; - m_spectral_end = 0; - m_successive_low = 0; - m_successive_high = 0; - m_max_mcu_x_size = 0; - m_max_mcu_y_size = 0; - m_blocks_per_mcu = 0; - m_max_blocks_per_row = 0; - m_mcus_per_row = 0; - m_mcus_per_col = 0; - m_expanded_blocks_per_component = 0; - m_expanded_blocks_per_mcu = 0; - m_expanded_blocks_per_row = 0; - m_freq_domain_chroma_upsample = false; - - memset(m_mcu_org, 0, sizeof(m_mcu_org)); - - m_total_lines_left = 0; - m_mcu_lines_left = 0; - m_real_dest_bytes_per_scan_line = 0; - m_dest_bytes_per_scan_line = 0; - m_dest_bytes_per_pixel = 0; - - memset(m_pHuff_tabs, 0, sizeof(m_pHuff_tabs)); - - memset(m_dc_coeffs, 0, sizeof(m_dc_coeffs)); - memset(m_ac_coeffs, 0, sizeof(m_ac_coeffs)); - memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu)); - - m_eob_run = 0; - - memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu)); - - m_pIn_buf_ofs = m_in_buf; - m_in_buf_left = 0; - m_eof_flag = false; - m_tem_flag = 0; - - memset(m_in_buf_pad_start, 0, sizeof(m_in_buf_pad_start)); - memset(m_in_buf, 0, sizeof(m_in_buf)); - memset(m_in_buf_pad_end, 0, sizeof(m_in_buf_pad_end)); - - m_restart_interval = 0; - m_restarts_left = 0; - m_next_restart_num = 0; - - m_max_mcus_per_row = 0; - m_max_blocks_per_mcu = 0; - m_max_mcus_per_col = 0; - - memset(m_last_dc_val, 0, sizeof(m_last_dc_val)); - m_pMCU_coefficients = NULL; - m_pSample_buf = NULL; - - m_total_bytes_read = 0; - - m_pScan_line_0 = NULL; - m_pScan_line_1 = NULL; - - // Ready the input buffer. - prep_in_buffer(); - - // Prime the bit buffer. - m_bits_left = 16; - m_bit_buf = 0; - - get_bits(16); - get_bits(16); - - for (int i = 0; i < JPGD_MAX_BLOCKS_PER_MCU; i++) - m_mcu_block_max_zag[i] = 64; - } - -#define SCALEBITS 16 -#define ONE_HALF ((int) 1 << (SCALEBITS-1)) -#define FIX(x) ((int) ((x) * (1L<> SCALEBITS; - m_cbb[i] = ( FIX(1.77200f) * k + ONE_HALF) >> SCALEBITS; - m_crg[i] = (-FIX(0.71414f)) * k; - m_cbg[i] = (-FIX(0.34414f)) * k + ONE_HALF; - } - } - - // This method throws back into the stream any bytes that where read - // into the bit buffer during initial marker scanning. - void jpeg_decoder::fix_in_buffer() - { - // In case any 0xFF's where pulled into the buffer during marker scanning. - JPGD_ASSERT((m_bits_left & 7) == 0); - - if (m_bits_left == 16) - stuff_char( (uint8)(m_bit_buf & 0xFF)); - - if (m_bits_left >= 8) - stuff_char( (uint8)((m_bit_buf >> 8) & 0xFF)); - - stuff_char((uint8)((m_bit_buf >> 16) & 0xFF)); - stuff_char((uint8)((m_bit_buf >> 24) & 0xFF)); - - m_bits_left = 16; - get_bits_no_markers(16); - get_bits_no_markers(16); - } - - void jpeg_decoder::transform_mcu(int mcu_row) - { - jpgd_block_t* pSrc_ptr = m_pMCU_coefficients; - uint8* pDst_ptr = m_pSample_buf + mcu_row * m_blocks_per_mcu * 64; - - for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++) - { - idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]); - pSrc_ptr += 64; - pDst_ptr += 64; - } - } - - static const uint8 s_max_rc[64] = - { - 17, 18, 34, 50, 50, 51, 52, 52, 52, 68, 84, 84, 84, 84, 85, 86, 86, 86, 86, 86, - 102, 118, 118, 118, 118, 118, 118, 119, 120, 120, 120, 120, 120, 120, 120, 136, - 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, - 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136 - }; - - void jpeg_decoder::transform_mcu_expand(int mcu_row) - { - jpgd_block_t* pSrc_ptr = m_pMCU_coefficients; - uint8* pDst_ptr = m_pSample_buf + mcu_row * m_expanded_blocks_per_mcu * 64; - - // Y IDCT - int mcu_block; - for (mcu_block = 0; mcu_block < m_expanded_blocks_per_component; mcu_block++) - { - idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]); - pSrc_ptr += 64; - pDst_ptr += 64; - } - - // Chroma IDCT, with upsampling - jpgd_block_t temp_block[64]; - - for (int i = 0; i < 2; i++) - { - DCT_Upsample::Matrix44 P, Q, R, S; - - JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] >= 1); - JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] <= 64); - - switch (s_max_rc[m_mcu_block_max_zag[mcu_block++] - 1]) - { - case 1*16+1: - DCT_Upsample::P_Q<1, 1>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<1, 1>::calc(R, S, pSrc_ptr); - break; - case 1*16+2: - DCT_Upsample::P_Q<1, 2>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<1, 2>::calc(R, S, pSrc_ptr); - break; - case 2*16+2: - DCT_Upsample::P_Q<2, 2>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<2, 2>::calc(R, S, pSrc_ptr); - break; - case 3*16+2: - DCT_Upsample::P_Q<3, 2>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<3, 2>::calc(R, S, pSrc_ptr); - break; - case 3*16+3: - DCT_Upsample::P_Q<3, 3>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<3, 3>::calc(R, S, pSrc_ptr); - break; - case 3*16+4: - DCT_Upsample::P_Q<3, 4>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<3, 4>::calc(R, S, pSrc_ptr); - break; - case 4*16+4: - DCT_Upsample::P_Q<4, 4>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<4, 4>::calc(R, S, pSrc_ptr); - break; - case 5*16+4: - DCT_Upsample::P_Q<5, 4>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<5, 4>::calc(R, S, pSrc_ptr); - break; - case 5*16+5: - DCT_Upsample::P_Q<5, 5>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<5, 5>::calc(R, S, pSrc_ptr); - break; - case 5*16+6: - DCT_Upsample::P_Q<5, 6>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<5, 6>::calc(R, S, pSrc_ptr); - break; - case 6*16+6: - DCT_Upsample::P_Q<6, 6>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<6, 6>::calc(R, S, pSrc_ptr); - break; - case 7*16+6: - DCT_Upsample::P_Q<7, 6>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<7, 6>::calc(R, S, pSrc_ptr); - break; - case 7*16+7: - DCT_Upsample::P_Q<7, 7>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<7, 7>::calc(R, S, pSrc_ptr); - break; - case 7*16+8: - DCT_Upsample::P_Q<7, 8>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<7, 8>::calc(R, S, pSrc_ptr); - break; - case 8*16+8: - DCT_Upsample::P_Q<8, 8>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<8, 8>::calc(R, S, pSrc_ptr); - break; - default: - JPGD_ASSERT(false); - } - - DCT_Upsample::Matrix44 a(P + Q); P -= Q; - DCT_Upsample::Matrix44& b = P; - DCT_Upsample::Matrix44 c(R + S); R -= S; - DCT_Upsample::Matrix44& d = R; - - DCT_Upsample::Matrix44::add_and_store(temp_block, a, c); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - DCT_Upsample::Matrix44::sub_and_store(temp_block, a, c); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - DCT_Upsample::Matrix44::add_and_store(temp_block, b, d); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - DCT_Upsample::Matrix44::sub_and_store(temp_block, b, d); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - pSrc_ptr += 64; - } - } - - // Loads and dequantizes the next row of (already decoded) coefficients. - // Progressive images only. - void jpeg_decoder::load_next_row() - { - int i; - jpgd_block_t *p; - jpgd_quant_t *q; - int mcu_row, mcu_block, row_block = 0; - int component_num, component_id; - int block_x_mcu[JPGD_MAX_COMPONENTS]; - - memset(block_x_mcu, 0, JPGD_MAX_COMPONENTS * sizeof(int)); - - for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++) - { - int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0; - - for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++) - { - component_id = m_mcu_org[mcu_block]; - q = m_quant[m_comp_quant[component_id]]; - - p = m_pMCU_coefficients + 64 * mcu_block; - - jpgd_block_t* pAC = coeff_buf_getp(m_ac_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs); - jpgd_block_t* pDC = coeff_buf_getp(m_dc_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs); - p[0] = pDC[0]; - memcpy(&p[1], &pAC[1], 63 * sizeof(jpgd_block_t)); - - for (i = 63; i > 0; i--) - if (p[g_ZAG[i]]) - break; - - m_mcu_block_max_zag[mcu_block] = i + 1; - - for ( ; i >= 0; i--) - if (p[g_ZAG[i]]) - p[g_ZAG[i]] = static_cast(p[g_ZAG[i]] * q[i]); - - row_block++; - - if (m_comps_in_scan == 1) - block_x_mcu[component_id]++; - else - { - if (++block_x_mcu_ofs == m_comp_h_samp[component_id]) - { - block_x_mcu_ofs = 0; - - if (++block_y_mcu_ofs == m_comp_v_samp[component_id]) - { - block_y_mcu_ofs = 0; - - block_x_mcu[component_id] += m_comp_h_samp[component_id]; - } - } - } - } - - if (m_freq_domain_chroma_upsample) - transform_mcu_expand(mcu_row); - else - transform_mcu(mcu_row); - } - - if (m_comps_in_scan == 1) - m_block_y_mcu[m_comp_list[0]]++; - else - { - for (component_num = 0; component_num < m_comps_in_scan; component_num++) - { - component_id = m_comp_list[component_num]; - - m_block_y_mcu[component_id] += m_comp_v_samp[component_id]; - } - } - } - - // Restart interval processing. - void jpeg_decoder::process_restart() - { - int i; - int c = 0; - - // Align to a byte boundry - // FIXME: Is this really necessary? get_bits_no_markers() never reads in markers! - //get_bits_no_markers(m_bits_left & 7); - - // Let's scan a little bit to find the marker, but not _too_ far. - // 1536 is a "fudge factor" that determines how much to scan. - for (i = 1536; i > 0; i--) - if (get_char() == 0xFF) - break; - - if (i == 0) - stop_decoding(JPGD_BAD_RESTART_MARKER); - - for ( ; i > 0; i--) - if ((c = get_char()) != 0xFF) - break; - - if (i == 0) - stop_decoding(JPGD_BAD_RESTART_MARKER); - - // Is it the expected marker? If not, something bad happened. - if (c != (m_next_restart_num + M_RST0)) - stop_decoding(JPGD_BAD_RESTART_MARKER); - - // Reset each component's DC prediction values. - memset(&m_last_dc_val, 0, m_comps_in_frame * sizeof(uint)); - - m_eob_run = 0; - - m_restarts_left = m_restart_interval; - - m_next_restart_num = (m_next_restart_num + 1) & 7; - - // Get the bit buffer going again... - - m_bits_left = 16; - get_bits_no_markers(16); - get_bits_no_markers(16); - } - - static inline int dequantize_ac(int c, int q) { c *= q; return c; } - - // Decodes and dequantizes the next row of coefficients. - void jpeg_decoder::decode_next_row() - { - int row_block = 0; - - for (int mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++) - { - if ((m_restart_interval) && (m_restarts_left == 0)) - process_restart(); - - jpgd_block_t* p = m_pMCU_coefficients; - for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++, p += 64) - { - int component_id = m_mcu_org[mcu_block]; - jpgd_quant_t* q = m_quant[m_comp_quant[component_id]]; - - int r, s; - s = huff_decode(m_pHuff_tabs[m_comp_dc_tab[component_id]], r); - s = HUFF_EXTEND(r, s); - - m_last_dc_val[component_id] = (s += m_last_dc_val[component_id]); - - p[0] = static_cast(s * q[0]); - - int prev_num_set = m_mcu_block_max_zag[mcu_block]; - - huff_tables *pH = m_pHuff_tabs[m_comp_ac_tab[component_id]]; - - int k; - for (k = 1; k < 64; k++) - { - int extra_bits; - s = huff_decode(pH, extra_bits); - - r = s >> 4; - s &= 15; - - if (s) - { - if (r) - { - if ((k + r) > 63) - stop_decoding(JPGD_DECODE_ERROR); - - if (k < prev_num_set) - { - int n = JPGD_MIN(r, prev_num_set - k); - int kt = k; - while (n--) - p[g_ZAG[kt++]] = 0; - } - - k += r; - } - - s = HUFF_EXTEND(extra_bits, s); - - JPGD_ASSERT(k < 64); - - p[g_ZAG[k]] = static_cast(dequantize_ac(s, q[k])); //s * q[k]; - } - else - { - if (r == 15) - { - if ((k + 16) > 64) - stop_decoding(JPGD_DECODE_ERROR); - - if (k < prev_num_set) - { - int n = JPGD_MIN(16, prev_num_set - k); - int kt = k; - while (n--) - { - JPGD_ASSERT(kt <= 63); - p[g_ZAG[kt++]] = 0; - } - } - - k += 16 - 1; // - 1 because the loop counter is k - // BEGIN EPIC MOD - JPGD_ASSERT(k < 64 && p[g_ZAG[k]] == 0); - // END EPIC MOD - } - else - break; - } - } - - if (k < prev_num_set) - { - int kt = k; - while (kt < prev_num_set) - p[g_ZAG[kt++]] = 0; - } - - m_mcu_block_max_zag[mcu_block] = k; - - row_block++; - } - - if (m_freq_domain_chroma_upsample) - transform_mcu_expand(mcu_row); - else - transform_mcu(mcu_row); - - m_restarts_left--; - } - } - - // YCbCr H1V1 (1x1:1:1, 3 m_blocks per MCU) to RGB - void jpeg_decoder::H1V1Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d = m_pScan_line_0; - uint8 *s = m_pSample_buf + row * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int j = 0; j < 8; j++) - { - int y = s[j]; - int cb = s[64+j]; - int cr = s[128+j]; - - if (jpg_format == ERGBFormatJPG::BGRA) - { - d[0] = clamp(y + m_cbb[cb]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_crr[cr]); - d[3] = 255; - } - else - { - d[0] = clamp(y + m_crr[cr]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_cbb[cb]); - d[3] = 255; - } - d += 4; - } - - s += 64*3; - } - } - - // YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB - void jpeg_decoder::H2V1Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d0 = m_pScan_line_0; - uint8 *y = m_pSample_buf + row * 8; - uint8 *c = m_pSample_buf + 2*64 + row * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int l = 0; l < 2; l++) - { - for (int j = 0; j < 4; j++) - { - int cb = c[0]; - int cr = c[64]; - - int rc = m_crr[cr]; - int gc = ((m_crg[cr] + m_cbg[cb]) >> 16); - int bc = m_cbb[cb]; - - int yy = y[j<<1]; - if (jpg_format == ERGBFormatJPG::BGRA) - { - d0[0] = clamp(yy+bc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+rc); - d0[3] = 255; - yy = y[(j<<1)+1]; - d0[4] = clamp(yy+bc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+rc); - d0[7] = 255; - } - else - { - d0[0] = clamp(yy+rc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+bc); - d0[3] = 255; - yy = y[(j<<1)+1]; - d0[4] = clamp(yy+rc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+bc); - d0[7] = 255; - } - - d0 += 8; - - c++; - } - y += 64; - } - - y += 64*4 - 64*2; - c += 64*4 - 8; - } - } - - // YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB - void jpeg_decoder::H1V2Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d0 = m_pScan_line_0; - uint8 *d1 = m_pScan_line_1; - uint8 *y; - uint8 *c; - - if (row < 8) - y = m_pSample_buf + row * 8; - else - y = m_pSample_buf + 64*1 + (row & 7) * 8; - - c = m_pSample_buf + 64*2 + (row >> 1) * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int j = 0; j < 8; j++) - { - int cb = c[0+j]; - int cr = c[64+j]; - - int rc = m_crr[cr]; - int gc = ((m_crg[cr] + m_cbg[cb]) >> 16); - int bc = m_cbb[cb]; - - int yy = y[j]; - if (jpg_format == ERGBFormatJPG::BGRA) - { - d0[0] = clamp(yy+bc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+rc); - d0[3] = 255; - yy = y[8+j]; - d1[0] = clamp(yy+bc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+rc); - d1[3] = 255; - } - else - { - d0[0] = clamp(yy+rc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+bc); - d0[3] = 255; - yy = y[8+j]; - d1[0] = clamp(yy+rc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+bc); - d1[3] = 255; - } - - d0 += 4; - d1 += 4; - } - - y += 64*4; - c += 64*4; - } - } - - // YCbCr H2V2 (2x2:1:1, 6 m_blocks per MCU) to RGB - void jpeg_decoder::H2V2Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d0 = m_pScan_line_0; - uint8 *d1 = m_pScan_line_1; - uint8 *y; - uint8 *c; - - if (row < 8) - y = m_pSample_buf + row * 8; - else - y = m_pSample_buf + 64*2 + (row & 7) * 8; - - c = m_pSample_buf + 64*4 + (row >> 1) * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int l = 0; l < 2; l++) - { - for (int j = 0; j < 8; j += 2) - { - int cb = c[0]; - int cr = c[64]; - - int rc = m_crr[cr]; - int gc = ((m_crg[cr] + m_cbg[cb]) >> 16); - int bc = m_cbb[cb]; - - int yy = y[j]; - if (jpg_format == ERGBFormatJPG::BGRA) - { - d0[0] = clamp(yy+bc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+rc); - d0[3] = 255; - yy = y[j+1]; - d0[4] = clamp(yy+bc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+rc); - d0[7] = 255; - yy = y[j+8]; - d1[0] = clamp(yy+bc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+rc); - d1[3] = 255; - yy = y[j+8+1]; - d1[4] = clamp(yy+bc); - d1[5] = clamp(yy+gc); - d1[6] = clamp(yy+rc); - d1[7] = 255; - } - else - { - d0[0] = clamp(yy+rc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+bc); - d0[3] = 255; - yy = y[j+1]; - d0[4] = clamp(yy+rc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+bc); - d0[7] = 255; - yy = y[j+8]; - d1[0] = clamp(yy+rc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+bc); - d1[3] = 255; - yy = y[j+8+1]; - d1[4] = clamp(yy+rc); - d1[5] = clamp(yy+gc); - d1[6] = clamp(yy+bc); - d1[7] = 255; - } - - d0 += 8; - d1 += 8; - - c++; - } - y += 64; - } - - y += 64*6 - 64*2; - c += 64*6 - 8; - } - } - - // Y (1 block per MCU) to 8-bit grayscale - void jpeg_decoder::gray_convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d = m_pScan_line_0; - uint8 *s = m_pSample_buf + row * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - *(uint *)d = *(uint *)s; - *(uint *)(&d[4]) = *(uint *)(&s[4]); - - s += 64; - d += 8; - } - } - - void jpeg_decoder::expanded_convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - - uint8* Py = m_pSample_buf + (row / 8) * 64 * m_comp_h_samp[0] + (row & 7) * 8; - - uint8* d = m_pScan_line_0; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int k = 0; k < m_max_mcu_x_size; k += 8) - { - const int Y_ofs = k * 8; - const int Cb_ofs = Y_ofs + 64 * m_expanded_blocks_per_component; - const int Cr_ofs = Y_ofs + 64 * m_expanded_blocks_per_component * 2; - for (int j = 0; j < 8; j++) - { - int y = Py[Y_ofs + j]; - int cb = Py[Cb_ofs + j]; - int cr = Py[Cr_ofs + j]; - - if (jpg_format == ERGBFormatJPG::BGRA) - { - d[0] = clamp(y + m_cbb[cb]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_crr[cr]); - d[3] = 255; - } - else - { - d[0] = clamp(y + m_crr[cr]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_cbb[cb]); - d[3] = 255; - } - - d += 4; - } - } - - Py += 64 * m_expanded_blocks_per_mcu; - } - } - - // Find end of image (EOI) marker, so we can return to the user the exact size of the input stream. - void jpeg_decoder::find_eoi() - { - if (!m_progressive_flag) - { - // Attempt to read the EOI marker. - //get_bits_no_markers(m_bits_left & 7); - - // Prime the bit buffer - m_bits_left = 16; - get_bits(16); - get_bits(16); - - // The next marker _should_ be EOI - process_markers(); - } - - m_total_bytes_read -= m_in_buf_left; - } - - int jpeg_decoder::decode(const void** pScan_line, uint* pScan_line_len) - { - if ((m_error_code) || (!m_ready_flag)) - return JPGD_FAILED; - - if (m_total_lines_left == 0) - return JPGD_DONE; - - if (m_mcu_lines_left == 0) - { - if (setjmp(m_jmp_state)) - return JPGD_FAILED; - - if (m_progressive_flag) - load_next_row(); - else - decode_next_row(); - - // Find the EOI marker if that was the last row. - if (m_total_lines_left <= m_max_mcu_y_size) - find_eoi(); - - m_mcu_lines_left = m_max_mcu_y_size; - } - - if (m_freq_domain_chroma_upsample) - { - expanded_convert(); - *pScan_line = m_pScan_line_0; - } - else - { - switch (m_scan_type) - { - case JPGD_YH2V2: - { - if ((m_mcu_lines_left & 1) == 0) - { - H2V2Convert(); - *pScan_line = m_pScan_line_0; - } - else - *pScan_line = m_pScan_line_1; - - break; - } - case JPGD_YH2V1: - { - H2V1Convert(); - *pScan_line = m_pScan_line_0; - break; - } - case JPGD_YH1V2: - { - if ((m_mcu_lines_left & 1) == 0) - { - H1V2Convert(); - *pScan_line = m_pScan_line_0; - } - else - *pScan_line = m_pScan_line_1; - - break; - } - case JPGD_YH1V1: - { - H1V1Convert(); - *pScan_line = m_pScan_line_0; - break; - } - case JPGD_GRAYSCALE: - { - gray_convert(); - *pScan_line = m_pScan_line_0; - - break; - } - } - } - - *pScan_line_len = m_real_dest_bytes_per_scan_line; - - m_mcu_lines_left--; - m_total_lines_left--; - - return JPGD_SUCCESS; - } - - // Creates the tables needed for efficient Huffman decoding. - void jpeg_decoder::make_huff_table(int index, huff_tables *pH) - { - int p, i, l, si; - uint8 huffsize[257]; - uint huffcode[257]; - uint code; - uint subtree; - int code_size; - int lastp; - int nextfreeentry; - int currententry; - - pH->ac_table = m_huff_ac[index] != 0; - - p = 0; - - for (l = 1; l <= 16; l++) - { - for (i = 1; i <= m_huff_num[index][l]; i++) - huffsize[p++] = static_cast(l); - } - - huffsize[p] = 0; - - lastp = p; - - code = 0; - si = huffsize[0]; - p = 0; - - while (huffsize[p]) - { - while (huffsize[p] == si) - { - huffcode[p++] = code; - code++; - } - - code <<= 1; - si++; - } - - memset(pH->look_up, 0, sizeof(pH->look_up)); - memset(pH->look_up2, 0, sizeof(pH->look_up2)); - memset(pH->tree, 0, sizeof(pH->tree)); - memset(pH->code_size, 0, sizeof(pH->code_size)); - - nextfreeentry = -1; - - p = 0; - - while (p < lastp) - { - i = m_huff_val[index][p]; - code = huffcode[p]; - code_size = huffsize[p]; - - pH->code_size[i] = static_cast(code_size); - - if (code_size <= 8) - { - code <<= (8 - code_size); - - for (l = 1 << (8 - code_size); l > 0; l--) - { - JPGD_ASSERT(i < 256); - - pH->look_up[code] = i; - - bool has_extrabits = false; - int extra_bits = 0; - int num_extra_bits = i & 15; - - int bits_to_fetch = code_size; - if (num_extra_bits) - { - int total_codesize = code_size + num_extra_bits; - if (total_codesize <= 8) - { - has_extrabits = true; - extra_bits = ((1 << num_extra_bits) - 1) & (code >> (8 - total_codesize)); - JPGD_ASSERT(extra_bits <= 0x7FFF); - bits_to_fetch += num_extra_bits; - } - } - - if (!has_extrabits) - pH->look_up2[code] = i | (bits_to_fetch << 8); - else - pH->look_up2[code] = i | 0x8000 | (extra_bits << 16) | (bits_to_fetch << 8); - - code++; - } - } - else - { - subtree = (code >> (code_size - 8)) & 0xFF; - - currententry = pH->look_up[subtree]; - - if (currententry == 0) - { - pH->look_up[subtree] = currententry = nextfreeentry; - pH->look_up2[subtree] = currententry = nextfreeentry; - - nextfreeentry -= 2; - } - - code <<= (16 - (code_size - 8)); - - for (l = code_size; l > 9; l--) - { - if ((code & 0x8000) == 0) - currententry--; - - if (pH->tree[-currententry - 1] == 0) - { - pH->tree[-currententry - 1] = nextfreeentry; - - currententry = nextfreeentry; - - nextfreeentry -= 2; - } - else - currententry = pH->tree[-currententry - 1]; - - code <<= 1; - } - - if ((code & 0x8000) == 0) - currententry--; - - pH->tree[-currententry - 1] = i; - } - - p++; - } - } - - // Verifies the quantization tables needed for this scan are available. - void jpeg_decoder::check_quant_tables() - { - for (int i = 0; i < m_comps_in_scan; i++) - if (m_quant[m_comp_quant[m_comp_list[i]]] == NULL) - stop_decoding(JPGD_UNDEFINED_QUANT_TABLE); - } - - // Verifies that all the Huffman tables needed for this scan are available. - void jpeg_decoder::check_huff_tables() - { - for (int i = 0; i < m_comps_in_scan; i++) - { - if ((m_spectral_start == 0) && (m_huff_num[m_comp_dc_tab[m_comp_list[i]]] == NULL)) - stop_decoding(JPGD_UNDEFINED_HUFF_TABLE); - - if ((m_spectral_end > 0) && (m_huff_num[m_comp_ac_tab[m_comp_list[i]]] == NULL)) - stop_decoding(JPGD_UNDEFINED_HUFF_TABLE); - } - - for (int i = 0; i < JPGD_MAX_HUFF_TABLES; i++) - if (m_huff_num[i]) - { - if (!m_pHuff_tabs[i]) - m_pHuff_tabs[i] = (huff_tables *)alloc(sizeof(huff_tables)); - - make_huff_table(i, m_pHuff_tabs[i]); - } - } - - // Determines the component order inside each MCU. - // Also calcs how many MCU's are on each row, etc. - void jpeg_decoder::calc_mcu_block_order() - { - int component_num, component_id; - int max_h_samp = 0, max_v_samp = 0; - - for (component_id = 0; component_id < m_comps_in_frame; component_id++) - { - if (m_comp_h_samp[component_id] > max_h_samp) - max_h_samp = m_comp_h_samp[component_id]; - - if (m_comp_v_samp[component_id] > max_v_samp) - max_v_samp = m_comp_v_samp[component_id]; - } - - for (component_id = 0; component_id < m_comps_in_frame; component_id++) - { - m_comp_h_blocks[component_id] = ((((m_image_x_size * m_comp_h_samp[component_id]) + (max_h_samp - 1)) / max_h_samp) + 7) / 8; - m_comp_v_blocks[component_id] = ((((m_image_y_size * m_comp_v_samp[component_id]) + (max_v_samp - 1)) / max_v_samp) + 7) / 8; - } - - if (m_comps_in_scan == 1) - { - m_mcus_per_row = m_comp_h_blocks[m_comp_list[0]]; - m_mcus_per_col = m_comp_v_blocks[m_comp_list[0]]; - } - else - { - m_mcus_per_row = (((m_image_x_size + 7) / 8) + (max_h_samp - 1)) / max_h_samp; - m_mcus_per_col = (((m_image_y_size + 7) / 8) + (max_v_samp - 1)) / max_v_samp; - } - - if (m_comps_in_scan == 1) - { - m_mcu_org[0] = m_comp_list[0]; - - m_blocks_per_mcu = 1; - } - else - { - m_blocks_per_mcu = 0; - - for (component_num = 0; component_num < m_comps_in_scan; component_num++) - { - int num_blocks; - - component_id = m_comp_list[component_num]; - - num_blocks = m_comp_h_samp[component_id] * m_comp_v_samp[component_id]; - - while (num_blocks--) - m_mcu_org[m_blocks_per_mcu++] = component_id; - } - } - } - - // Starts a new scan. - int jpeg_decoder::init_scan() - { - if (!locate_sos_marker()) - return JPGD_FALSE; - - calc_mcu_block_order(); - - check_huff_tables(); - - check_quant_tables(); - - memset(m_last_dc_val, 0, m_comps_in_frame * sizeof(uint)); - - m_eob_run = 0; - - if (m_restart_interval) - { - m_restarts_left = m_restart_interval; - m_next_restart_num = 0; - } - - fix_in_buffer(); - - return JPGD_TRUE; - } - - // Starts a frame. Determines if the number of components or sampling factors - // are supported. - void jpeg_decoder::init_frame() - { - int i; - - if (m_comps_in_frame == 1) - { - if ((m_comp_h_samp[0] != 1) || (m_comp_v_samp[0] != 1)) - stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS); - - m_scan_type = JPGD_GRAYSCALE; - m_max_blocks_per_mcu = 1; - m_max_mcu_x_size = 8; - m_max_mcu_y_size = 8; - } - else if (m_comps_in_frame == 3) - { - if ( ((m_comp_h_samp[1] != 1) || (m_comp_v_samp[1] != 1)) || - ((m_comp_h_samp[2] != 1) || (m_comp_v_samp[2] != 1)) ) - stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS); - - if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1)) - { - m_scan_type = JPGD_YH1V1; - - m_max_blocks_per_mcu = 3; - m_max_mcu_x_size = 8; - m_max_mcu_y_size = 8; - } - else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1)) - { - m_scan_type = JPGD_YH2V1; - m_max_blocks_per_mcu = 4; - m_max_mcu_x_size = 16; - m_max_mcu_y_size = 8; - } - else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 2)) - { - m_scan_type = JPGD_YH1V2; - m_max_blocks_per_mcu = 4; - m_max_mcu_x_size = 8; - m_max_mcu_y_size = 16; - } - else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2)) - { - m_scan_type = JPGD_YH2V2; - m_max_blocks_per_mcu = 6; - m_max_mcu_x_size = 16; - m_max_mcu_y_size = 16; - } - else - stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS); - } - else - stop_decoding(JPGD_UNSUPPORTED_COLORSPACE); - - m_max_mcus_per_row = (m_image_x_size + (m_max_mcu_x_size - 1)) / m_max_mcu_x_size; - m_max_mcus_per_col = (m_image_y_size + (m_max_mcu_y_size - 1)) / m_max_mcu_y_size; - - // These values are for the *destination* pixels: after conversion. - if (m_scan_type == JPGD_GRAYSCALE) - m_dest_bytes_per_pixel = 1; - else - m_dest_bytes_per_pixel = 4; - - m_dest_bytes_per_scan_line = ((m_image_x_size + 15) & 0xFFF0) * m_dest_bytes_per_pixel; - - m_real_dest_bytes_per_scan_line = (m_image_x_size * m_dest_bytes_per_pixel); - - // Initialize two scan line buffers. - m_pScan_line_0 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true); - if ((m_scan_type == JPGD_YH1V2) || (m_scan_type == JPGD_YH2V2)) - m_pScan_line_1 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true); - - m_max_blocks_per_row = m_max_mcus_per_row * m_max_blocks_per_mcu; - - // Should never happen - if (m_max_blocks_per_row > JPGD_MAX_BLOCKS_PER_ROW) - stop_decoding(JPGD_ASSERTION_ERROR); - - // Allocate the coefficient buffer, enough for one MCU - m_pMCU_coefficients = (jpgd_block_t*)alloc(m_max_blocks_per_mcu * 64 * sizeof(jpgd_block_t)); - - for (i = 0; i < m_max_blocks_per_mcu; i++) - m_mcu_block_max_zag[i] = 64; - - m_expanded_blocks_per_component = m_comp_h_samp[0] * m_comp_v_samp[0]; - m_expanded_blocks_per_mcu = m_expanded_blocks_per_component * m_comps_in_frame; - m_expanded_blocks_per_row = m_max_mcus_per_row * m_expanded_blocks_per_mcu; - // Freq. domain chroma upsampling is only supported for H2V2 subsampling factor. -// BEGIN EPIC MOD -#if JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING - m_freq_domain_chroma_upsample = (m_expanded_blocks_per_mcu == 4*3); -#else - m_freq_domain_chroma_upsample = 0; -#endif -// END EPIC MOD - - if (m_freq_domain_chroma_upsample) - m_pSample_buf = (uint8 *)alloc(m_expanded_blocks_per_row * 64); - else - m_pSample_buf = (uint8 *)alloc(m_max_blocks_per_row * 64); - - m_total_lines_left = m_image_y_size; - - m_mcu_lines_left = 0; - - create_look_ups(); - } - - // The coeff_buf series of methods originally stored the coefficients - // into a "virtual" file which was located in EMS, XMS, or a disk file. A cache - // was used to make this process more efficient. Now, we can store the entire - // thing in RAM. - jpeg_decoder::coeff_buf* jpeg_decoder::coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y) - { - coeff_buf* cb = (coeff_buf*)alloc(sizeof(coeff_buf)); - - cb->block_num_x = block_num_x; - cb->block_num_y = block_num_y; - cb->block_len_x = block_len_x; - cb->block_len_y = block_len_y; - cb->block_size = (block_len_x * block_len_y) * sizeof(jpgd_block_t); - cb->pData = (uint8 *)alloc(cb->block_size * block_num_x * block_num_y, true); - return cb; - } - - inline jpgd_block_t *jpeg_decoder::coeff_buf_getp(coeff_buf *cb, int block_x, int block_y) - { - JPGD_ASSERT((block_x < cb->block_num_x) && (block_y < cb->block_num_y)); - return (jpgd_block_t *)(cb->pData + block_x * cb->block_size + block_y * (cb->block_size * cb->block_num_x)); - } - - // The following methods decode the various types of m_blocks encountered - // in progressively encoded images. - void jpeg_decoder::decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - int s, r; - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y); - - if ((s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_dc_tab[component_id]])) != 0) - { - r = pD->get_bits_no_markers(s); - s = HUFF_EXTEND(r, s); - } - - pD->m_last_dc_val[component_id] = (s += pD->m_last_dc_val[component_id]); - - p[0] = static_cast(s << pD->m_successive_low); - } - - void jpeg_decoder::decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - if (pD->get_bits_no_markers(1)) - { - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y); - - p[0] |= (1 << pD->m_successive_low); - } - } - - void jpeg_decoder::decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - int k, s, r; - - if (pD->m_eob_run) - { - pD->m_eob_run--; - return; - } - - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y); - - for (k = pD->m_spectral_start; k <= pD->m_spectral_end; k++) - { - s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]); - - r = s >> 4; - s &= 15; - - if (s) - { - if ((k += r) > 63) - pD->stop_decoding(JPGD_DECODE_ERROR); - - r = pD->get_bits_no_markers(s); - s = HUFF_EXTEND(r, s); - - p[g_ZAG[k]] = static_cast(s << pD->m_successive_low); - } - else - { - if (r == 15) - { - if ((k += 15) > 63) - pD->stop_decoding(JPGD_DECODE_ERROR); - } - else - { - pD->m_eob_run = 1 << r; - - if (r) - pD->m_eob_run += pD->get_bits_no_markers(r); - - pD->m_eob_run--; - - break; - } - } - } - } - - void jpeg_decoder::decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - int s, k, r; - int p1 = 1 << pD->m_successive_low; - int m1 = (-1) << pD->m_successive_low; - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y); - - k = pD->m_spectral_start; - - if (pD->m_eob_run == 0) - { - for ( ; k <= pD->m_spectral_end; k++) - { - s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]); - - r = s >> 4; - s &= 15; - - if (s) - { - if (s != 1) - pD->stop_decoding(JPGD_DECODE_ERROR); - - if (pD->get_bits_no_markers(1)) - s = p1; - else - s = m1; - } - else - { - if (r != 15) - { - pD->m_eob_run = 1 << r; - - if (r) - pD->m_eob_run += pD->get_bits_no_markers(r); - - break; - } - } - - do - { - // BEGIN EPIC MOD - JPGD_ASSERT(k < 64); - // END EPIC MOD - - jpgd_block_t *this_coef = p + g_ZAG[k]; - - if (*this_coef != 0) - { - if (pD->get_bits_no_markers(1)) - { - if ((*this_coef & p1) == 0) - { - if (*this_coef >= 0) - *this_coef = static_cast(*this_coef + p1); - else - *this_coef = static_cast(*this_coef + m1); - } - } - } - else - { - if (--r < 0) - break; - } - - k++; - - } while (k <= pD->m_spectral_end); - - if ((s) && (k < 64)) - { - p[g_ZAG[k]] = static_cast(s); - } - } - } - - if (pD->m_eob_run > 0) - { - for ( ; k <= pD->m_spectral_end; k++) - { - // BEGIN EPIC MOD - JPGD_ASSERT(k < 64); - // END EPIC MOD - - jpgd_block_t *this_coef = p + g_ZAG[k]; - - if (*this_coef != 0) - { - if (pD->get_bits_no_markers(1)) - { - if ((*this_coef & p1) == 0) - { - if (*this_coef >= 0) - *this_coef = static_cast(*this_coef + p1); - else - *this_coef = static_cast(*this_coef + m1); - } - } - } - } - - pD->m_eob_run--; - } - } - - // Decode a scan in a progressively encoded image. - void jpeg_decoder::decode_scan(pDecode_block_func decode_block_func) - { - int mcu_row, mcu_col, mcu_block; - int block_x_mcu[JPGD_MAX_COMPONENTS], m_block_y_mcu[JPGD_MAX_COMPONENTS]; - - memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu)); - - for (mcu_col = 0; mcu_col < m_mcus_per_col; mcu_col++) - { - int component_num, component_id; - - memset(block_x_mcu, 0, sizeof(block_x_mcu)); - - for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++) - { - int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0; - - if ((m_restart_interval) && (m_restarts_left == 0)) - process_restart(); - - for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++) - { - component_id = m_mcu_org[mcu_block]; - - decode_block_func(this, component_id, block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs); - - if (m_comps_in_scan == 1) - block_x_mcu[component_id]++; - else - { - if (++block_x_mcu_ofs == m_comp_h_samp[component_id]) - { - block_x_mcu_ofs = 0; - - if (++block_y_mcu_ofs == m_comp_v_samp[component_id]) - { - block_y_mcu_ofs = 0; - block_x_mcu[component_id] += m_comp_h_samp[component_id]; - } - } - } - } - - m_restarts_left--; - } - - if (m_comps_in_scan == 1) - m_block_y_mcu[m_comp_list[0]]++; - else - { - for (component_num = 0; component_num < m_comps_in_scan; component_num++) - { - component_id = m_comp_list[component_num]; - m_block_y_mcu[component_id] += m_comp_v_samp[component_id]; - } - } - } - } - - // Decode a progressively encoded image. - void jpeg_decoder::init_progressive() - { - int i; - - if (m_comps_in_frame == 4) - stop_decoding(JPGD_UNSUPPORTED_COLORSPACE); - - // Allocate the coefficient buffers. - for (i = 0; i < m_comps_in_frame; i++) - { - m_dc_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 1, 1); - m_ac_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 8, 8); - } - - for ( ; ; ) - { - int dc_only_scan, refinement_scan; - pDecode_block_func decode_block_func; - - if (!init_scan()) - break; - - dc_only_scan = (m_spectral_start == 0); - refinement_scan = (m_successive_high != 0); - - if ((m_spectral_start > m_spectral_end) || (m_spectral_end > 63)) - stop_decoding(JPGD_BAD_SOS_SPECTRAL); - - if (dc_only_scan) - { - if (m_spectral_end) - stop_decoding(JPGD_BAD_SOS_SPECTRAL); - } - else if (m_comps_in_scan != 1) /* AC scans can only contain one component */ - stop_decoding(JPGD_BAD_SOS_SPECTRAL); - - if ((refinement_scan) && (m_successive_low != m_successive_high - 1)) - stop_decoding(JPGD_BAD_SOS_SUCCESSIVE); - - if (dc_only_scan) - { - if (refinement_scan) - decode_block_func = decode_block_dc_refine; - else - decode_block_func = decode_block_dc_first; - } - else - { - if (refinement_scan) - decode_block_func = decode_block_ac_refine; - else - decode_block_func = decode_block_ac_first; - } - - decode_scan(decode_block_func); - - m_bits_left = 16; - get_bits(16); - get_bits(16); - } - - m_comps_in_scan = m_comps_in_frame; - - for (i = 0; i < m_comps_in_frame; i++) - m_comp_list[i] = i; - - calc_mcu_block_order(); - } - - void jpeg_decoder::init_sequential() - { - if (!init_scan()) - stop_decoding(JPGD_UNEXPECTED_MARKER); - } - - void jpeg_decoder::decode_start() - { - init_frame(); - - if (m_progressive_flag) - init_progressive(); - else - init_sequential(); - } - - void jpeg_decoder::decode_init(jpeg_decoder_stream *pStream) - { - init(pStream); - locate_sof_marker(); - } - - jpeg_decoder::jpeg_decoder(jpeg_decoder_stream *pStream) - { - if (setjmp(m_jmp_state)) - return; - decode_init(pStream); - } - - int jpeg_decoder::begin_decoding() - { - if (m_ready_flag) - return JPGD_SUCCESS; - - if (m_error_code) - return JPGD_FAILED; - - if (setjmp(m_jmp_state)) - return JPGD_FAILED; - - decode_start(); - - m_ready_flag = true; - - return JPGD_SUCCESS; - } - - jpeg_decoder::~jpeg_decoder() - { - free_all_blocks(); - } - - jpeg_decoder_file_stream::jpeg_decoder_file_stream() - { - m_pFile = NULL; - m_eof_flag = false; - m_error_flag = false; - } - - void jpeg_decoder_file_stream::close() - { - if (m_pFile) - { - fclose(m_pFile); - m_pFile = NULL; - } - - m_eof_flag = false; - m_error_flag = false; - } - - jpeg_decoder_file_stream::~jpeg_decoder_file_stream() - { - close(); - } - - bool jpeg_decoder_file_stream::open(const char *Pfilename) - { - close(); - - m_eof_flag = false; - m_error_flag = false; - -#if defined(_MSC_VER) - m_pFile = NULL; - fopen_s(&m_pFile, Pfilename, "rb"); -#else - m_pFile = fopen(Pfilename, "rb"); -#endif - return m_pFile != NULL; - } - - int jpeg_decoder_file_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) - { - if (!m_pFile) - return -1; - - if (m_eof_flag) - { - *pEOF_flag = true; - return 0; - } - - if (m_error_flag) - return -1; - - int bytes_read = static_cast(fread(pBuf, 1, max_bytes_to_read, m_pFile)); - if (bytes_read < max_bytes_to_read) - { - if (ferror(m_pFile)) - { - m_error_flag = true; - return -1; - } - - m_eof_flag = true; - *pEOF_flag = true; - } - - return bytes_read; - } - - bool jpeg_decoder_mem_stream::open(const uint8 *pSrc_data, uint size) - { - close(); - m_pSrc_data = pSrc_data; - m_ofs = 0; - m_size = size; - return true; - } - - int jpeg_decoder_mem_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) - { - *pEOF_flag = false; - - if (!m_pSrc_data) - return -1; - - uint bytes_remaining = m_size - m_ofs; - if ((uint)max_bytes_to_read > bytes_remaining) - { - max_bytes_to_read = bytes_remaining; - *pEOF_flag = true; - } - - memcpy(pBuf, m_pSrc_data + m_ofs, max_bytes_to_read); - m_ofs += max_bytes_to_read; - - return max_bytes_to_read; - } - - unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps) - { - if (!actual_comps) - return NULL; - *actual_comps = 0; - - if ((!pStream) || (!width) || (!height) || (!req_comps)) - return NULL; - - if ((req_comps != 1) && (req_comps != 3) && (req_comps != 4)) - return NULL; - - jpeg_decoder decoder(pStream); - if (decoder.get_error_code() != JPGD_SUCCESS) - return NULL; - - const int image_width = decoder.get_width(), image_height = decoder.get_height(); - *width = image_width; - *height = image_height; - *actual_comps = decoder.get_num_components(); - - if (decoder.begin_decoding() != JPGD_SUCCESS) - return NULL; - - const int dst_bpl = image_width * req_comps; - - uint8 *pImage_data = (uint8*)jpgd_malloc(dst_bpl * image_height); - if (!pImage_data) - return NULL; - - for (int y = 0; y < image_height; y++) - { - const uint8* pScan_line = 0; - uint scan_line_len; - if (decoder.decode((const void**)&pScan_line, &scan_line_len) != JPGD_SUCCESS) - { - jpgd_free(pImage_data); - return NULL; - } - - uint8 *pDst = pImage_data + y * dst_bpl; - - if (((req_comps == 4) && (decoder.get_num_components() == 3)) || - ((req_comps == 1) && (decoder.get_num_components() == 1))) - { - memcpy(pDst, pScan_line, dst_bpl); - } - else if (decoder.get_num_components() == 1) - { - if (req_comps == 3) - { - for (int x = 0; x < image_width; x++) - { - uint8 luma = pScan_line[x]; - pDst[0] = luma; - pDst[1] = luma; - pDst[2] = luma; - pDst += 3; - } - } - else - { - for (int x = 0; x < image_width; x++) - { - uint8 luma = pScan_line[x]; - pDst[0] = luma; - pDst[1] = luma; - pDst[2] = luma; - pDst[3] = 255; - pDst += 4; - } - } - } - else if (decoder.get_num_components() == 3) - { - if (req_comps == 1) - { - const int YR = 19595, YG = 38470, YB = 7471; - for (int x = 0; x < image_width; x++) - { - int r = pScan_line[x*4+0]; - int g = pScan_line[x*4+1]; - int b = pScan_line[x*4+2]; - *pDst++ = static_cast((r * YR + g * YG + b * YB + 32768) >> 16); - } - } - else - { - for (int x = 0; x < image_width; x++) - { - pDst[0] = pScan_line[x*4+0]; - pDst[1] = pScan_line[x*4+1]; - pDst[2] = pScan_line[x*4+2]; - pDst += 3; - } - } - } - } - - return pImage_data; - } - -// BEGIN EPIC MOD - unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps, int format) - { - jpg_format = (ERGBFormatJPG)format; -// EMD EPIC MOD - jpgd::jpeg_decoder_mem_stream mem_stream(pSrc_data, src_data_size); - return decompress_jpeg_image_from_stream(&mem_stream, width, height, actual_comps, req_comps); - } - - unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps) - { - jpgd::jpeg_decoder_file_stream file_stream; - if (!file_stream.open(pSrc_filename)) - return NULL; - return decompress_jpeg_image_from_stream(&file_stream, width, height, actual_comps, req_comps); - } - -} // namespace jpgd diff --git a/spaces/yderre-aubay/midi-player-demo/src/components/Dialog.tsx b/spaces/yderre-aubay/midi-player-demo/src/components/Dialog.tsx deleted file mode 100644 index 104d414558b3f389c629f5492f9f5cf467386e80..0000000000000000000000000000000000000000 --- a/spaces/yderre-aubay/midi-player-demo/src/components/Dialog.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { keyframes } from "@emotion/react" -import styled from "@emotion/styled" -import { - Content, - DialogProps as Props, - Overlay, - Portal, - Root, -} from "@radix-ui/react-dialog" -import { FC } from "react" - -const overlayShow = keyframes` - from { - opacity: 0; - } - to { - opacity: 1; - } -` - -const contentShow = keyframes` - from { - opacity: 0; - transform: translate(-50%, -48%) scale(0.96); - } - to { - opacity: 1; - transform: translate(-50%, -50%) scale(1); - } -` - -const StyledOverlay = styled(Overlay)` - background-color: rgba(0, 0, 0, 0.3); - position: fixed; - inset: 0; - animation: ${overlayShow} 150ms cubic-bezier(0.16, 1, 0.3, 1); -` - -const StyledContent = styled(Content)` - background-color: ${({ theme }) => theme.backgroundColor}; - border-radius: 0.5rem; - box-shadow: 0 0.5rem 3rem ${({ theme }) => theme.shadowColor}; - position: fixed; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - margin-bottom: 1rem; - max-width: 30rem; - max-height: 85vh; - padding: 1rem; - animation: ${contentShow} 150ms cubic-bezier(0.16, 1, 0.3, 1); - display: flex; - flex-direction: column; - pointer-events: auto; - overflow: hidden; - - &:focus { - outline: none; - } -` - -export type DialogProps = Props & { - style?: React.CSSProperties -} - -export const Dialog: FC = ({ children, style, ...props }) => ( - - - - {children} - - -) - -export const DialogTitle = styled.div` - font-size: 1.25rem; - color: ${({ theme }) => theme.textColor}; - margin-bottom: 1.5rem; -` - -export const DialogContent = styled.div` - overflow-x: hidden; - overflow-y: auto; - margin-bottom: 1rem; -` - -export const DialogActions = styled.div` - display: flex; - justify-content: flex-end; - - & > *:not(:last-child) { - margin-right: 1rem; - } -` diff --git a/spaces/yeshpanovrustem/ner-kazakh/style.css b/spaces/yeshpanovrustem/ner-kazakh/style.css deleted file mode 100644 index b660137f0861c56df54fe868cf2799f1c8b2bf9d..0000000000000000000000000000000000000000 --- a/spaces/yeshpanovrustem/ner-kazakh/style.css +++ /dev/null @@ -1,21 +0,0 @@ -h1 { - text-align: center; - color: black; -} - -h2 { - text-align: center; - color: black; -} - -p#warning { - text-align: center; - font-weight: bold; - color: red; -} - -.stRadio [role = radiogroup]{ - align-items: center; - justify-content: center; - font-size: 3rem !important; -} \ No newline at end of file diff --git a/spaces/ygtxr1997/ReliableSwap_Demo/third_party/GPEN/distributed.py b/spaces/ygtxr1997/ReliableSwap_Demo/third_party/GPEN/distributed.py deleted file mode 100644 index 51fa243257ef302e2015d5ff36ac531b86a9a0ce..0000000000000000000000000000000000000000 --- a/spaces/ygtxr1997/ReliableSwap_Demo/third_party/GPEN/distributed.py +++ /dev/null @@ -1,126 +0,0 @@ -import math -import pickle - -import torch -from torch import distributed as dist -from torch.utils.data.sampler import Sampler - - -def get_rank(): - if not dist.is_available(): - return 0 - - if not dist.is_initialized(): - return 0 - - return dist.get_rank() - - -def synchronize(): - if not dist.is_available(): - return - - if not dist.is_initialized(): - return - - world_size = dist.get_world_size() - - if world_size == 1: - return - - dist.barrier() - - -def get_world_size(): - if not dist.is_available(): - return 1 - - if not dist.is_initialized(): - return 1 - - return dist.get_world_size() - - -def reduce_sum(tensor): - if not dist.is_available(): - return tensor - - if not dist.is_initialized(): - return tensor - - tensor = tensor.clone() - dist.all_reduce(tensor, op=dist.ReduceOp.SUM) - - return tensor - - -def gather_grad(params): - world_size = get_world_size() - - if world_size == 1: - return - - for param in params: - if param.grad is not None: - dist.all_reduce(param.grad.data, op=dist.ReduceOp.SUM) - param.grad.data.div_(world_size) - - -def all_gather(data): - world_size = get_world_size() - - if world_size == 1: - return [data] - - buffer = pickle.dumps(data) - storage = torch.ByteStorage.from_buffer(buffer) - tensor = torch.ByteTensor(storage).to('cuda') - - local_size = torch.IntTensor([tensor.numel()]).to('cuda') - size_list = [torch.IntTensor([0]).to('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) - - tensor_list = [] - for _ in size_list: - tensor_list.append(torch.ByteTensor(size=(max_size,)).to('cuda')) - - if local_size != max_size: - padding = torch.ByteTensor(size=(max_size - local_size,)).to('cuda') - tensor = torch.cat((tensor, padding), 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_loss_dict(loss_dict): - world_size = get_world_size() - - if world_size < 2: - return loss_dict - - with torch.no_grad(): - keys = [] - losses = [] - - for k in sorted(loss_dict.keys()): - keys.append(k) - losses.append(loss_dict[k]) - - losses = torch.stack(losses, 0) - dist.reduce(losses, dst=0) - - if dist.get_rank() == 0: - losses /= world_size - - reduced_losses = {k: v for k, v in zip(keys, losses)} - - return reduced_losses diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/modeling_flax_outputs.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/modeling_flax_outputs.py deleted file mode 100644 index 179a0b787936960c118bbb5ad34f73d00469d481..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/modeling_flax_outputs.py +++ /dev/null @@ -1,700 +0,0 @@ -# Copyright 2021 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 Dict, Optional, Tuple - -import flax -import jax.numpy as jnp - -from .utils import ModelOutput - - -@flax.struct.dataclass -class FlaxBaseModelOutput(ModelOutput): - """ - Base class for model's outputs, with potential hidden states and attentions. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): - Sequence of hidden-states at the output of the last layer of the model. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - last_hidden_state: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxBaseModelOutputWithNoAttention(ModelOutput): - """ - Base class for model's outputs, with potential hidden states. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): - Sequence of hidden-states at the output of the last layer of the model. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings, if the model has an embedding layer, + one - for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the - model at the output of each layer plus the optional initial embedding outputs. - """ - - last_hidden_state: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxBaseModelOutputWithPoolingAndNoAttention(ModelOutput): - """ - Base class for model's outputs that also contains a pooling of the last hidden states. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): - Sequence of hidden-states at the output of the last layer of the model. - pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`): - Last layer hidden-state after a pooling operation on the spatial dimensions. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings, if the model has an embedding layer, + one - for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the - model at the output of each layer plus the optional initial embedding outputs. - """ - - last_hidden_state: jnp.ndarray = None - pooler_output: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxImageClassifierOutputWithNoAttention(ModelOutput): - """ - Base class for outputs of image classification models. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): - Classification (or regression if config.num_labels==1) scores (before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when - `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings, if the model has an embedding layer, + one - for the output of each stage) of shape `(batch_size, num_channels, height, width)`. Hidden-states (also - called feature maps) of the model at the output of each stage. - """ - - logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxBaseModelOutputWithPast(ModelOutput): - """ - Base class for model's outputs, with potential hidden states and attentions. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): - Sequence of hidden-states at the output of the last layer of the model. - past_key_values (`Dict[str, jnp.ndarray]`): - Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast - auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - last_hidden_state: jnp.ndarray = None - past_key_values: Optional[Dict[str, jnp.ndarray]] = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxBaseModelOutputWithPooling(ModelOutput): - """ - Base class for model's outputs that also contains a pooling of the last hidden states. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): - Sequence of hidden-states at the output of the last layer of the model. - pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`): - Last layer hidden-state of the first token of the sequence (classification token) further processed by a - Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence - prediction (classification) objective during pretraining. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - last_hidden_state: jnp.ndarray = None - pooler_output: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxBaseModelOutputWithPoolingAndCrossAttentions(ModelOutput): - """ - Base class for model's outputs that also contains a pooling of the last hidden states. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): - Sequence of hidden-states at the output of the last layer of the model. - pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`): - Last layer hidden-state of the first token of the sequence (classification token) after further processing - through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns - the classification token after processing through a linear layer and a tanh activation function. The linear - layer weights are trained from the next sentence prediction (classification) objective during pretraining. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings, if the model has an embedding layer, + one - for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the - weighted average in the cross-attention heads. - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if - `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads, - encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if - `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` - input) to speed up sequential decoding. - """ - - last_hidden_state: jnp.ndarray = None - pooler_output: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxBaseModelOutputWithPastAndCrossAttentions(ModelOutput): - """ - Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): - Sequence of hidden-states at the output of the last layer of the model. - - If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, - hidden_size)` is output. - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if - `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads, - encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if - `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` - input) to speed up sequential decoding. - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the - weighted average in the cross-attention heads. - """ - - last_hidden_state: jnp.ndarray = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxSeq2SeqModelOutput(ModelOutput): - """ - Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential - decoding. - - Args: - last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): - Sequence of hidden-states at the output of the last layer of the decoder of the model. - - If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, - hidden_size)` is output. - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape - `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention - blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. - decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. - decoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the - weighted average in the cross-attention heads. - encoder_last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): - Sequence of hidden-states at the output of the last layer of the encoder of the model. - encoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. - encoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - """ - - last_hidden_state: jnp.ndarray = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - decoder_attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - encoder_last_hidden_state: Optional[jnp.ndarray] = None - encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - encoder_attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxCausalLMOutputWithCrossAttentions(ModelOutput): - """ - Base class for causal language model (or autoregressive) outputs. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): - Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Cross attentions weights after the attention softmax, used to compute the weighted average in the - cross-attention heads. - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `jnp.ndarray` tuples of length `config.n_layers`, with each tuple containing the cached key, value - states of the self-attention and the cross-attention layers if model is used in encoder-decoder setting. - Only relevant if `config.is_decoder = True`. - - Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see - `past_key_values` input) to speed up sequential decoding. - """ - - logits: jnp.ndarray = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxMaskedLMOutput(ModelOutput): - """ - Base class for masked language models outputs. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): - Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -FlaxCausalLMOutput = FlaxMaskedLMOutput - - -@flax.struct.dataclass -class FlaxSeq2SeqLMOutput(ModelOutput): - """ - Base class for sequence-to-sequence language models outputs. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): - Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape - `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention - blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. - decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. - decoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the - weighted average in the cross-attention heads. - encoder_last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): - Sequence of hidden-states at the output of the last layer of the encoder of the model. - encoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. - encoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - """ - - logits: jnp.ndarray = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - decoder_attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - encoder_last_hidden_state: Optional[jnp.ndarray] = None - encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - encoder_attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxNextSentencePredictorOutput(ModelOutput): - """ - Base class for outputs of models predicting if two sentences are consecutive or not. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, 2)`): - Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation - before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxSequenceClassifierOutput(ModelOutput): - """ - Base class for outputs of sentence classification models. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): - Classification (or regression if config.num_labels==1) scores (before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxSeq2SeqSequenceClassifierOutput(ModelOutput): - """ - Base class for outputs of sequence-to-sequence sentence classification models. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): - Classification (or regression if config.num_labels==1) scores (before SoftMax). - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape - `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention - blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. - decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. - decoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the - weighted average in the cross-attention heads. - encoder_last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): - Sequence of hidden-states at the output of the last layer of the encoder of the model. - encoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. - encoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - """ - - logits: jnp.ndarray = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - decoder_attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - encoder_last_hidden_state: Optional[jnp.ndarray] = None - encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - encoder_attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxMultipleChoiceModelOutput(ModelOutput): - """ - Base class for outputs of multiple choice models. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, num_choices)`): - *num_choices* is the second dimension of the input tensors. (see *input_ids* above). - - Classification scores (before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxTokenClassifierOutput(ModelOutput): - """ - Base class for outputs of token classification models. - - Args: - logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.num_labels)`): - Classification scores (before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxQuestionAnsweringModelOutput(ModelOutput): - """ - Base class for outputs of question answering models. - - Args: - start_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): - Span-start scores (before SoftMax). - end_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): - Span-end scores (before SoftMax). - hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention - heads. - """ - - start_logits: jnp.ndarray = None - end_logits: jnp.ndarray = None - hidden_states: Optional[Tuple[jnp.ndarray]] = None - attentions: Optional[Tuple[jnp.ndarray]] = None - - -@flax.struct.dataclass -class FlaxSeq2SeqQuestionAnsweringModelOutput(ModelOutput): - """ - Base class for outputs of sequence-to-sequence question answering models. - - Args: - start_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): - Span-start scores (before SoftMax). - end_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): - Span-end scores (before SoftMax). - past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape - `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention - blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. - decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. - decoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the - weighted average in the cross-attention heads. - encoder_last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): - Sequence of hidden-states at the output of the last layer of the encoder of the model. - encoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): - Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape - `(batch_size, sequence_length, hidden_size)`. - - Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. - encoder_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): - Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, - sequence_length)`. - - Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the - self-attention heads. - """ - - start_logits: jnp.ndarray = None - end_logits: jnp.ndarray = None - past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None - decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - decoder_attentions: Optional[Tuple[jnp.ndarray]] = None - cross_attentions: Optional[Tuple[jnp.ndarray]] = None - encoder_last_hidden_state: Optional[jnp.ndarray] = None - encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None - encoder_attentions: Optional[Tuple[jnp.ndarray]] = None diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/funnel/configuration_funnel.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/funnel/configuration_funnel.py deleted file mode 100644 index d049b15911b04c3180c1255dc5e424d77743de1d..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/funnel/configuration_funnel.py +++ /dev/null @@ -1,179 +0,0 @@ -# coding=utf-8 -# Copyright 2020, Hugging Face -# -# 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. -""" Funnel Transformer model configuration""" - -from ...configuration_utils import PretrainedConfig -from ...utils import logging - - -logger = logging.get_logger(__name__) - -FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP = { - "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", - "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", - "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", - "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", - "funnel-transformer/intermediate": ( - "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" - ), - "funnel-transformer/intermediate-base": ( - "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" - ), - "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", - "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", - "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", - "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", -} - - -class FunnelConfig(PretrainedConfig): - r""" - This is the configuration class to store the configuration of a [`FunnelModel`] or a [`TFBertModel`]. It is used to - instantiate a Funnel Transformer model according to the specified arguments, defining the model architecture. - Instantiating a configuration with the defaults will yield a similar configuration to that of the Funnel - Transformer [funnel-transformer/small](https://huggingface.co/funnel-transformer/small) architecture. - - Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the - documentation from [`PretrainedConfig`] for more information. - - Args: - vocab_size (`int`, *optional*, defaults to 30522): - Vocabulary size of the Funnel transformer. Defines the number of different tokens that can be represented - by the `inputs_ids` passed when calling [`FunnelModel`] or [`TFFunnelModel`]. - block_sizes (`List[int]`, *optional*, defaults to `[4, 4, 4]`): - The sizes of the blocks used in the model. - block_repeats (`List[int]`, *optional*): - If passed along, each layer of each block is repeated the number of times indicated. - num_decoder_layers (`int`, *optional*, defaults to 2): - The number of layers in the decoder (when not using the base model). - d_model (`int`, *optional*, defaults to 768): - Dimensionality of the model's hidden states. - n_head (`int`, *optional*, defaults to 12): - Number of attention heads for each attention layer in the Transformer encoder. - d_head (`int`, *optional*, defaults to 64): - Dimensionality of the model's heads. - d_inner (`int`, *optional*, defaults to 3072): - Inner dimension in the feed-forward blocks. - hidden_act (`str` or `callable`, *optional*, defaults to `"gelu_new"`): - The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, - `"relu"`, `"silu"` and `"gelu_new"` are supported. - hidden_dropout (`float`, *optional*, defaults to 0.1): - The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. - attention_dropout (`float`, *optional*, defaults to 0.1): - The dropout probability for the attention probabilities. - activation_dropout (`float`, *optional*, defaults to 0.0): - The dropout probability used between the two layers of the feed-forward blocks. - initializer_range (`float`, *optional*, defaults to 0.1): - The upper bound of the *uniform initializer* for initializing all weight matrices in attention layers. - initializer_std (`float`, *optional*): - The standard deviation of the *normal initializer* for initializing the embedding matrix and the weight of - linear layers. Will default to 1 for the embedding matrix and the value given by Xavier initialization for - linear layers. - layer_norm_eps (`float`, *optional*, defaults to 1e-09): - The epsilon used by the layer normalization layers. - pooling_type (`str`, *optional*, defaults to `"mean"`): - Possible values are `"mean"` or `"max"`. The way pooling is performed at the beginning of each block. - attention_type (`str`, *optional*, defaults to `"relative_shift"`): - Possible values are `"relative_shift"` or `"factorized"`. The former is faster on CPU/GPU while the latter - is faster on TPU. - separate_cls (`bool`, *optional*, defaults to `True`): - Whether or not to separate the cls token when applying pooling. - truncate_seq (`bool`, *optional*, defaults to `True`): - When using `separate_cls`, whether or not to truncate the last token when pooling, to avoid getting a - sequence length that is not a multiple of 2. - pool_q_only (`bool`, *optional*, defaults to `True`): - Whether or not to apply the pooling only to the query or to query, key and values for the attention layers. - """ - model_type = "funnel" - attribute_map = { - "hidden_size": "d_model", - "num_attention_heads": "n_head", - } - - def __init__( - self, - vocab_size=30522, - block_sizes=[4, 4, 4], - block_repeats=None, - num_decoder_layers=2, - d_model=768, - n_head=12, - d_head=64, - d_inner=3072, - hidden_act="gelu_new", - hidden_dropout=0.1, - attention_dropout=0.1, - activation_dropout=0.0, - initializer_range=0.1, - initializer_std=None, - layer_norm_eps=1e-9, - pooling_type="mean", - attention_type="relative_shift", - separate_cls=True, - truncate_seq=True, - pool_q_only=True, - **kwargs, - ): - self.vocab_size = vocab_size - self.block_sizes = block_sizes - self.block_repeats = [1] * len(block_sizes) if block_repeats is None else block_repeats - assert len(block_sizes) == len( - self.block_repeats - ), "`block_sizes` and `block_repeats` should have the same length." - self.num_decoder_layers = num_decoder_layers - self.d_model = d_model - self.n_head = n_head - self.d_head = d_head - self.d_inner = d_inner - self.hidden_act = hidden_act - self.hidden_dropout = hidden_dropout - self.attention_dropout = attention_dropout - self.activation_dropout = activation_dropout - self.initializer_range = initializer_range - self.initializer_std = initializer_std - self.layer_norm_eps = layer_norm_eps - assert pooling_type in [ - "mean", - "max", - ], f"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported." - self.pooling_type = pooling_type - assert attention_type in [ - "relative_shift", - "factorized", - ], f"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported." - self.attention_type = attention_type - self.separate_cls = separate_cls - self.truncate_seq = truncate_seq - self.pool_q_only = pool_q_only - - super().__init__(**kwargs) - - @property - def num_hidden_layers(self): - return sum(self.block_sizes) - - @num_hidden_layers.setter - def num_hidden_layers(self, value): - raise NotImplementedError( - "This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`." - ) - - @property - def num_blocks(self): - return len(self.block_sizes) - - @num_blocks.setter - def num_blocks(self, value): - raise NotImplementedError("This model does not support the setting of `num_blocks`. Please set `block_sizes`.") diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/mbart50/tokenization_mbart50.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/mbart50/tokenization_mbart50.py deleted file mode 100644 index e2cffc57ad3380b499bced2cb06a937e1e6cfe05..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/mbart50/tokenization_mbart50.py +++ /dev/null @@ -1,368 +0,0 @@ -# coding=utf-8 -# Copyright 2021 The Facebook AI Research Team Authors and The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from shutil import copyfile -from typing import Any, Dict, List, Optional, Tuple - -import sentencepiece as spm - -from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer -from ...utils import logging - - -logger = logging.get_logger(__name__) - -SPIECE_UNDERLINE = "▁" - -VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"} - -PRETRAINED_VOCAB_FILES_MAP = { - "vocab_file": { - "facebook/mbart-large-50-one-to-many-mmt": ( - "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" - ), - } -} - -PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { - "facebook/mbart-large-50-one-to-many-mmt": 1024, -} - -# fmt: off -FAIRSEQ_LANGUAGE_CODES = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] -# fmt: on - - -class MBart50Tokenizer(PreTrainedTokenizer): - """ - Construct a MBart50 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece). - - This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to - this superclass for more information regarding those methods. - - Args: - vocab_file (`str`): - Path to the vocabulary file. - src_lang (`str`, *optional*): - A string representing the source language. - tgt_lang (`str`, *optional*): - A string representing the target language. - eos_token (`str`, *optional*, defaults to `"
          "`): - The end of sequence token. - sep_token (`str`, *optional*, defaults to `""`): - The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for - sequence classification or for a text and a question for question answering. It is also used as the last - token of a sequence built with special tokens. - cls_token (`str`, *optional*, defaults to `""`): - The classifier token which is used when doing sequence classification (classification of the whole sequence - instead of per-token classification). It is the first token of the sequence when built with special tokens. - unk_token (`str`, *optional*, defaults to `""`): - The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this - token instead. - pad_token (`str`, *optional*, defaults to `""`): - The token used for padding, for example when batching sequences of different lengths. - mask_token (`str`, *optional*, defaults to `""`): - The token used for masking values. This is the token used when training this model with masked language - modeling. This is the token which the model will try to predict. - sp_model_kwargs (`dict`, *optional*): - Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for - SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things, - to set: - - - `enable_sampling`: Enable subword regularization. - - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout. - - - `nbest_size = {0,1}`: No sampling is performed. - - `nbest_size > 1`: samples from the nbest_size results. - - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) - using forward-filtering-and-backward-sampling algorithm. - - - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for - BPE-dropout. - - Examples: - - ```python - >>> from transformers import MBart50Tokenizer - - >>> tokenizer = MBart50Tokenizer.from_pretrained("facebook/mbart-large-50", src_lang="en_XX", tgt_lang="ro_RO") - >>> src_text = " UN Chief Says There Is No Military Solution in Syria" - >>> tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria" - >>> model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt") - >>> # model(**model_inputs) should work - ```""" - - vocab_files_names = VOCAB_FILES_NAMES - max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES - pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP - model_input_names = ["input_ids", "attention_mask"] - - prefix_tokens: List[int] = [] - suffix_tokens: List[int] = [] - - def __init__( - self, - vocab_file, - src_lang=None, - tgt_lang=None, - eos_token="", - sep_token="", - cls_token="", - unk_token="", - pad_token="", - mask_token="", - sp_model_kwargs: Optional[Dict[str, Any]] = None, - **kwargs, - ) -> None: - # Mask token behave like a normal word, i.e. include the space before it - mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token - - self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs - - kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) - kwargs["additional_special_tokens"] += [ - code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] - ] - - self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) - self.sp_model.Load(str(vocab_file)) - self.vocab_file = vocab_file - - # Original fairseq vocab and spm vocab must be "aligned": - # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 - # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- - # fairseq | '' | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-' - # spm | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' - - # Mimic fairseq token-to-id alignment for the first 4 token - self.fairseq_tokens_to_ids = {"": 0, "": 1, "": 2, "": 3} - - # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab - self.fairseq_offset = 1 - - self.sp_model_size = len(self.sp_model) - self.lang_code_to_id = { - code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(FAIRSEQ_LANGUAGE_CODES) - } - self.id_to_lang_code = {v: k for k, v in self.lang_code_to_id.items()} - self.fairseq_tokens_to_ids[""] = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset - - self.fairseq_tokens_to_ids.update(self.lang_code_to_id) - self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()} - - super().__init__( - src_lang=src_lang, - tgt_lang=tgt_lang, - eos_token=eos_token, - unk_token=unk_token, - sep_token=sep_token, - cls_token=cls_token, - pad_token=pad_token, - mask_token=mask_token, - sp_model_kwargs=self.sp_model_kwargs, - **kwargs, - ) - - self._src_lang = src_lang if src_lang is not None else "en_XX" - self.cur_lang_code_id = self.lang_code_to_id[self._src_lang] - self.tgt_lang = tgt_lang - self.set_src_lang_special_tokens(self._src_lang) - - @property - def vocab_size(self) -> int: - return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1 # Plus 1 for the mask token - - @property - def src_lang(self) -> str: - return self._src_lang - - @src_lang.setter - def src_lang(self, new_src_lang: str) -> None: - self._src_lang = new_src_lang - self.set_src_lang_special_tokens(self._src_lang) - - def __getstate__(self) -> Dict: - state = self.__dict__.copy() - state["sp_model"] = None - return state - - def __setstate__(self, d: Dict) -> None: - self.__dict__ = d - - # for backward compatibility - if not hasattr(self, "sp_model_kwargs"): - self.sp_model_kwargs = {} - - self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) - self.sp_model.Load(self.vocab_file) - - def get_vocab(self) -> Dict: - vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} - vocab.update(self.added_tokens_encoder) - return vocab - - def _tokenize(self, text: str) -> List[str]: - return self.sp_model.encode(text, out_type=str) - - def _convert_token_to_id(self, token: str) -> int: - """Converts a token (str) in an id using the vocab.""" - if token in self.fairseq_tokens_to_ids: - return self.fairseq_tokens_to_ids[token] - spm_id = self.sp_model.PieceToId(token) - - # Need to return unknown token if the SP model returned 0 - return spm_id + self.fairseq_offset if spm_id else self.unk_token_id - - def _convert_id_to_token(self, index: int) -> str: - """Converts an index (integer) in a token (str) using the vocab.""" - if index in self.fairseq_ids_to_tokens: - return self.fairseq_ids_to_tokens[index] - return self.sp_model.IdToPiece(index - self.fairseq_offset) - - def convert_tokens_to_string(self, tokens): - """Converts a sequence of tokens (string) in a single string.""" - current_sub_tokens = [] - out_string = "" - prev_is_special = False - for token in tokens: - # make sure that special tokens are not decoded using sentencepiece model - if token in self.all_special_tokens: - if not prev_is_special: - out_string += " " - out_string += self.sp_model.decode(current_sub_tokens) + token - prev_is_special = True - current_sub_tokens = [] - else: - current_sub_tokens.append(token) - prev_is_special = False - out_string += self.sp_model.decode(current_sub_tokens) - return out_string.strip() - - def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: - if not os.path.isdir(save_directory): - logger.error(f"Vocabulary path ({save_directory}) should be a directory") - return - out_vocab_file = os.path.join( - save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] - ) - - if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): - copyfile(self.vocab_file, out_vocab_file) - elif not os.path.isfile(self.vocab_file): - with open(out_vocab_file, "wb") as fi: - content_spiece_model = self.sp_model.serialized_model_proto() - fi.write(content_spiece_model) - - return (out_vocab_file,) - - def get_special_tokens_mask( - self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False - ) -> List[int]: - """ - Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding - special tokens using the tokenizer `prepare_for_model` method. - - Args: - token_ids_0 (`List[int]`): - List of IDs. - token_ids_1 (`List[int]`, *optional*): - Optional second list of IDs for sequence pairs. - already_has_special_tokens (`bool`, *optional*, defaults to `False`): - Whether or not the token list is already formatted with special tokens for the model. - - Returns: - `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. - """ - - if already_has_special_tokens: - return super().get_special_tokens_mask( - token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True - ) - - prefix_ones = [1] * len(self.prefix_tokens) - suffix_ones = [1] * len(self.suffix_tokens) - if token_ids_1 is None: - return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones - return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones - - def build_inputs_with_special_tokens( - self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None - ) -> List[int]: - """ - Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and - adding special tokens. An MBART-50 sequence has the following format, where `X` represents the sequence: - - - `input_ids` (for encoder) `[src_lang_code] X [eos]` - - `labels`: (for decoder) `[tgt_lang_code] X [eos]` - - BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a - separator. - - Args: - token_ids_0 (`List[int]`): - List of IDs to which the special tokens will be added. - token_ids_1 (`List[int]`, *optional*): - Optional second list of IDs for sequence pairs. - - Returns: - `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. - """ - if token_ids_1 is None: - return self.prefix_tokens + token_ids_0 + self.suffix_tokens - # We don't expect to process pairs, but leave the pair logic for API consistency - return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens - - def _build_translation_inputs( - self, raw_inputs, return_tensors: str, src_lang: Optional[str], tgt_lang: Optional[str], **extra_kwargs - ): - """Used by translation pipeline, to prepare inputs for the generate function""" - if src_lang is None or tgt_lang is None: - raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model") - self.src_lang = src_lang - inputs = self(raw_inputs, add_special_tokens=True, return_tensors=return_tensors, **extra_kwargs) - tgt_lang_id = self.convert_tokens_to_ids(tgt_lang) - inputs["forced_bos_token_id"] = tgt_lang_id - return inputs - - def prepare_seq2seq_batch( - self, - src_texts: List[str], - src_lang: str = "en_XX", - tgt_texts: Optional[List[str]] = None, - tgt_lang: str = "ro_RO", - **kwargs, - ) -> BatchEncoding: - self.src_lang = src_lang - self.tgt_lang = tgt_lang - return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs) - - def _switch_to_input_mode(self): - return self.set_src_lang_special_tokens(self.src_lang) - - def _switch_to_target_mode(self): - return self.set_tgt_lang_special_tokens(self.tgt_lang) - - def set_src_lang_special_tokens(self, src_lang: str) -> None: - """Reset the special tokens to the source lang setting. prefix=[src_lang_code] and suffix=[eos].""" - self.cur_lang_code_id = self.lang_code_to_id[src_lang] - self.prefix_tokens = [self.cur_lang_code_id] - self.suffix_tokens = [self.eos_token_id] - - def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None: - """Reset the special tokens to the target language setting. prefix=[tgt_lang_code] and suffix=[eos].""" - self.cur_lang_code_id = self.lang_code_to_id[tgt_lang] - self.prefix_tokens = [self.cur_lang_code_id] - self.suffix_tokens = [self.eos_token_id] diff --git a/spaces/yizhangliu/ImgCleaner/share_btn.py b/spaces/yizhangliu/ImgCleaner/share_btn.py deleted file mode 100644 index c0b8b741622103ce9b57f10021da6a8f6539f7bb..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/ImgCleaner/share_btn.py +++ /dev/null @@ -1,78 +0,0 @@ -community_icon_html = """""" - -loading_icon_html = """""" - -share_js = """async () => { - function isMobile() { - try { - document.createEvent("TouchEvent"); return true; - } catch(e) { - return false; - } - } - async function uploadFile(file){ - const UPLOAD_URL = 'https://huggingface.co/uploads'; - const response = await fetch(UPLOAD_URL, { - method: 'POST', - headers: { - 'Content-Type': file.type, - 'X-Requested-With': 'XMLHttpRequest', - }, - body: file, /// <- File inherits from Blob - }); - const url = await response.text(); - return url; - } - var gradioEl = document.querySelector('body > gradio-app').shadowRoot; - if (!gradioEl) { - gradioEl = document.querySelector('body > gradio-app'); - } - - const imgEls = gradioEl.querySelectorAll('#gallery .overflow-hidden'); - const promptTxt = 'my perfect work'; - const shareBtnEl = gradioEl.querySelector('#share-btn'); - const shareIconEl = gradioEl.querySelector('#share-btn-share-icon'); - const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon'); - if(!imgEls.length){ - return; - }; - shareBtnEl.style.pointerEvents = 'none'; - shareIconEl.style.display = 'none'; - loadingIconEl.style.removeProperty('display'); - if (isMobile()) { - gradioEl.querySelector('#platform_radio').querySelectorAll('input')[1].checked = true; - } - var files = []; - var nowTime = Date.now(); - var imgCount = 0; - await Promise.all( - [...imgEls].map(async (imgEl) => { - if (imgEl.offsetWidth > 50 && imgEl.offsetHeight > 50) { - const res = await fetch(imgEl.src); - const blob = await res.blob(); - const fileName = `img-cleaner-${nowTime}-${imgCount}.png`; - imgCount += 1; - files.push(new File([blob], fileName, { type: 'image/png'})); - } - }) - ); - const urls = await Promise.all(files.map((f) => uploadFile(f))); - const htmlImgs = urls.map(url => ``); - const descriptionMd = `
          - ${htmlImgs.join(`\n`)} -
          `; - const params = new URLSearchParams({ - title: promptTxt, - description: descriptionMd, - }); - const paramsStr = params.toString(); - window.open(`https://huggingface.co/spaces/yizhangliu/ImgCleaner/discussions/new?${paramsStr}`, '_blank'); - shareBtnEl.style.removeProperty('pointer-events'); - shareIconEl.style.removeProperty('display'); - loadingIconEl.style.display = 'none'; -}""" diff --git a/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/diffusion/logger/__init__.py b/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/diffusion/logger/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/vdecoder/__init__.py b/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/vdecoder/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/yuan2023/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/controlnet/controlnet_pose.py b/spaces/yuan2023/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/controlnet/controlnet_pose.py deleted file mode 100644 index b8ba5f4ee06f4b651a94cda0cee75f6e578c216a..0000000000000000000000000000000000000000 --- a/spaces/yuan2023/Stable-Diffusion-ControlNet-WebUI/diffusion_webui/controlnet/controlnet_pose.py +++ /dev/null @@ -1,170 +0,0 @@ -import gradio as gr -import torch -from controlnet_aux import OpenposeDetector -from diffusers import ( - ControlNetModel, - StableDiffusionControlNetPipeline, - UniPCMultistepScheduler, -) -from PIL import Image - -stable_model_list = [ - "runwayml/stable-diffusion-v1-5", - "stabilityai/stable-diffusion-2-1", -] - -controlnet_pose_model_list = [ - "lllyasviel/sd-controlnet-openpose", - "thibaud/controlnet-sd21-openpose-diffusers", -] - -stable_prompt_list = ["a photo of a man.", "a photo of a girl."] - -stable_negative_prompt_list = ["bad, ugly", "deformed"] - -data_list = [ - "data/test.png", -] - - -def controlnet_pose(image_path: str, controlnet_pose_model_path: str): - openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet") - - image = Image.open(image_path) - image = openpose(image) - - controlnet = ControlNetModel.from_pretrained( - controlnet_pose_model_path, torch_dtype=torch.float16 - ) - - return controlnet, image - - -def stable_diffusion_controlnet_pose( - image_path: str, - stable_model_path: str, - controlnet_pose_model_path: str, - prompt: str, - negative_prompt: str, - guidance_scale: int, - num_inference_step: int, -): - - controlnet, image = controlnet_pose( - image_path=image_path, - controlnet_pose_model_path=controlnet_pose_model_path, - ) - - pipe = StableDiffusionControlNetPipeline.from_pretrained( - pretrained_model_name_or_path=-stable_model_path, - controlnet=controlnet, - safety_checker=None, - torch_dtype=torch.float16, - ) - - pipe.to("cuda") - pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config) - pipe.enable_xformers_memory_efficient_attention() - - output = pipe( - prompt=prompt, - image=image, - negative_prompt=negative_prompt, - num_inference_steps=num_inference_step, - guidance_scale=guidance_scale, - ).images - - return output[0] - - -def stable_diffusion_controlnet_pose_app(): - with gr.Blocks(): - with gr.Row(): - with gr.Column(): - controlnet_pose_image_file = gr.Image( - type="filepath", label="Image" - ) - - controlnet_pose_stable_model_id = gr.Dropdown( - choices=stable_model_list, - value=stable_model_list[0], - label="Stable Model Id", - ) - - controlnet_pose_model_id = gr.Dropdown( - choices=controlnet_pose_model_list, - value=controlnet_pose_model_list[0], - label="ControlNet Model Id", - ) - - controlnet_pose_prompt = gr.Textbox( - lines=1, value=stable_prompt_list[0], label="Prompt" - ) - - controlnet_pose_negative_prompt = gr.Textbox( - lines=1, - value=stable_negative_prompt_list[0], - label="Negative Prompt", - ) - - with gr.Accordion("Advanced Options", open=False): - controlnet_pose_guidance_scale = gr.Slider( - minimum=0.1, - maximum=15, - step=0.1, - value=7.5, - label="Guidance Scale", - ) - - controlnet_pose_num_inference_step = gr.Slider( - minimum=1, - maximum=100, - step=1, - value=50, - label="Num Inference Step", - ) - - controlnet_pose_predict = gr.Button(value="Generator") - - with gr.Column(): - output_image = gr.Image(label="Output") - - gr.Examples( - fn=stable_diffusion_controlnet_pose, - examples=[ - [ - data_list[0], - stable_model_list[0], - controlnet_pose_model_list[0], - stable_prompt_list[0], - stable_negative_prompt_list[0], - 7.5, - 50, - ] - ], - inputs=[ - controlnet_pose_image_file, - controlnet_pose_stable_model_id, - controlnet_pose_model_id, - controlnet_pose_prompt, - controlnet_pose_negative_prompt, - controlnet_pose_guidance_scale, - controlnet_pose_num_inference_step, - ], - outputs=[output_image], - label="ControlNet Pose Example", - cache_examples=False, - ) - controlnet_pose_predict.click( - fn=stable_diffusion_controlnet_pose, - inputs=[ - controlnet_pose_image_file, - controlnet_pose_stable_model_id, - controlnet_pose_model_id, - controlnet_pose_prompt, - controlnet_pose_negative_prompt, - controlnet_pose_guidance_scale, - controlnet_pose_num_inference_step, - ], - outputs=output_image, - ) diff --git a/spaces/yuhangzang/ContextDet-Demo/models/transformer.py b/spaces/yuhangzang/ContextDet-Demo/models/transformer.py deleted file mode 100644 index a8d711741d979d96e3b598a45386795f7c6589d1..0000000000000000000000000000000000000000 --- a/spaces/yuhangzang/ContextDet-Demo/models/transformer.py +++ /dev/null @@ -1,179 +0,0 @@ -import torch -from torchvision.ops.boxes import batched_nms - -from util.box_ops import box_cxcywh_to_xyxy - -from .deformable_detr.deformable_transformer import DeformableTransformer - - -class OVTransformer(DeformableTransformer): - def __init__(self, d_model=256, nhead=8, - num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.1, - activation="relu", return_intermediate_dec=False, - num_feature_levels=4, dec_n_points=4, enc_n_points=4, - two_stage=False, two_stage_num_proposals=300, - assign_first_stage=False): - super().__init__(d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout, - activation, return_intermediate_dec, num_feature_levels, dec_n_points, enc_n_points, - two_stage, two_stage_num_proposals, assign_first_stage) - - def forward(self, srcs, masks, pos_embeds, query_embed=None, llm_feat=None, num_patch=1): - assert self.two_stage or query_embed is not None - - # 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) - mask = mask.flatten(1) - pos_embed = pos_embed.flatten(2).transpose(1, 2) - lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) - lvl_pos_embed_flatten.append(lvl_pos_embed) - src_flatten.append(src) - mask_flatten.append(mask) - src_flatten = torch.cat(src_flatten, 1) - mask_flatten = torch.cat(mask_flatten, 1) - lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) - 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) - - # encoder - memory = self.encoder(src_flatten, spatial_shapes, level_start_index, valid_ratios, - lvl_pos_embed_flatten, mask_flatten) - - # prepare input for decoder - bs, _, c = memory.shape - if self.two_stage: - output_memory, output_proposals, level_ids = \ - self.gen_encoder_output_proposals(memory, mask_flatten, spatial_shapes) - - # hack implementation for two-stage Deformable DETR - enc_outputs_class = self.decoder.class_embed[self.decoder.num_layers](output_memory) - enc_outputs_coord_unact = self.decoder.bbox_embed[self.decoder.num_layers](output_memory) + output_proposals - - topk = self.two_stage_num_proposals - proposal_logit = enc_outputs_class[..., 0] - - if self.assign_first_stage: - proposal_boxes = box_cxcywh_to_xyxy(enc_outputs_coord_unact.sigmoid().float()).clamp(0, 1) - topk_proposals = [] - for b in range(bs): - prop_boxes_b = proposal_boxes[b] - prop_logits_b = proposal_logit[b] - - # pre-nms per-level topk - pre_nms_topk = 1000 - pre_nms_inds = [] - for lvl in range(len(spatial_shapes)): - lvl_mask = level_ids == lvl - pre_nms_inds.append(torch.topk(prop_logits_b.sigmoid() * lvl_mask, pre_nms_topk)[1]) - pre_nms_inds = torch.cat(pre_nms_inds) - - # nms on topk indices - post_nms_inds = batched_nms(prop_boxes_b[pre_nms_inds], - prop_logits_b[pre_nms_inds], - level_ids[pre_nms_inds], 0.9) - keep_inds = pre_nms_inds[post_nms_inds] - - if len(keep_inds) < self.two_stage_num_proposals: - print(f'[WARNING] nms proposals ({len(keep_inds)}) < {self.two_stage_num_proposals}') - keep_inds = torch.topk(proposal_logit[b], topk)[1] - - # keep top Q/L indices for L levels - q_per_l = topk // len(spatial_shapes) - level_shapes = torch.arange(len(spatial_shapes), device=level_ids.device)[:, None] - is_level_ordered = level_ids[keep_inds][None] == level_shapes - keep_inds_mask = is_level_ordered & (is_level_ordered.cumsum(1) <= q_per_l) # LS - keep_inds_mask = keep_inds_mask.any(0) # S - - # pad to Q indices (might let ones filtered from pre-nms sneak by... - # unlikely because we pick high conf anyways) - if keep_inds_mask.sum() < topk: - num_to_add = topk - keep_inds_mask.sum() - pad_inds = (~keep_inds_mask).nonzero()[:num_to_add] - keep_inds_mask[pad_inds] = True - - # index - keep_inds_topk = keep_inds[keep_inds_mask] - topk_proposals.append(keep_inds_topk) - topk_proposals = torch.stack(topk_proposals) - else: - topk_proposals = torch.topk(proposal_logit, topk, dim=1)[1] - - topk_coords_unact = torch.gather(enc_outputs_coord_unact, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)) - topk_coords_unact = topk_coords_unact.detach() - reference_points = topk_coords_unact.sigmoid() - init_reference_out = reference_points - pos_trans_out = self.pos_trans_norm(self.pos_trans(self.get_proposal_pos_embed(topk_coords_unact))) - query_embed, tgt = torch.split(pos_trans_out, c, dim=2) - - num_queries = query_embed.shape[1] - query_embed = query_embed.repeat(1, num_patch, 1) - tgt = tgt.repeat(1, num_patch, 1) - topk_feats = torch.stack([output_memory[b][topk_proposals[b]] for b in range(bs)]).detach() - topk_feats = topk_feats.repeat(1, num_patch, 1) - tgt = tgt + self.pix_trans_norm(self.pix_trans(topk_feats)) - reference_points = reference_points.repeat(1, num_patch, 1) - init_reference_out = init_reference_out.repeat(1, num_patch, 1) - - llm_feat = llm_feat.repeat_interleave(num_queries, 1) - tgt = tgt + llm_feat - else: - raise NotImplementedError - query_embed, tgt = torch.split(query_embed, c, dim=1) - query_embed = query_embed.unsqueeze(0).expand(bs, -1, -1) - tgt = tgt.unsqueeze(0).expand(bs, -1, -1) - reference_points = self.reference_points(query_embed).sigmoid() - init_reference_out = reference_points - # decoder mask - decoder_mask = ( - torch.ones( - num_queries * num_patch, - num_queries * num_patch, - device=query_embed.device, - ) * float("-inf") - ) - for i in range(num_patch): - decoder_mask[ - i * num_queries : (i + 1) * num_queries, - i * num_queries : (i + 1) * num_queries, - ] = 0 - - # decoder - hs, inter_references = self.decoder(tgt, reference_points, memory, - spatial_shapes, level_start_index, valid_ratios, - query_embed, mask_flatten, tgt_mask=decoder_mask) - - inter_references_out = inter_references - if self.two_stage: - return (hs, - init_reference_out, - inter_references_out, - enc_outputs_class, - enc_outputs_coord_unact, - output_proposals.sigmoid()) - return hs, init_reference_out, inter_references_out, None, None, None - - -def build_ov_transformer(args): - return OVTransformer( - d_model=args.hidden_dim, - nhead=args.nheads, - num_encoder_layers=args.enc_layers, - num_decoder_layers=args.dec_layers, - dim_feedforward=args.dim_feedforward, - dropout=args.dropout, - activation="relu", - return_intermediate_dec=True, - num_feature_levels=args.num_feature_levels, - dec_n_points=args.dec_n_points, - enc_n_points=args.enc_n_points, - two_stage=args.two_stage, - two_stage_num_proposals=args.num_queries, - assign_first_stage=args.assign_first_stage) diff --git a/spaces/zdxiaoda/sovits-4.0-V1-anime-character-model/so-vits-svc/modules/mel_processing.py b/spaces/zdxiaoda/sovits-4.0-V1-anime-character-model/so-vits-svc/modules/mel_processing.py deleted file mode 100644 index 99c5b35beb83f3b288af0fac5b49ebf2c69f062c..0000000000000000000000000000000000000000 --- a/spaces/zdxiaoda/sovits-4.0-V1-anime-character-model/so-vits-svc/modules/mel_processing.py +++ /dev/null @@ -1,112 +0,0 @@ -import math -import os -import random -import torch -from torch import nn -import torch.nn.functional as F -import torch.utils.data -import numpy as np -import librosa -import librosa.util as librosa_util -from librosa.util import normalize, pad_center, tiny -from scipy.signal import get_window -from scipy.io.wavfile import read -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(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=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(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=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, return_complex=False) - - 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/zhangyd/bingo/src/components/tone-selector.tsx b/spaces/zhangyd/bingo/src/components/tone-selector.tsx deleted file mode 100644 index 5c6e464c91f564b895acd121f0a4a79ed9c5c356..0000000000000000000000000000000000000000 --- a/spaces/zhangyd/bingo/src/components/tone-selector.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import React from 'react' -import { BingConversationStyle } from '@/lib/bots/bing/types' -import { cn } from '@/lib/utils' - -type ToneItem = { - type: BingConversationStyle, - name: string -} - -const ToneList: ToneItem[] = [ - { name: '有创造力', type: BingConversationStyle.Creative }, - { name: '更平衡', type: BingConversationStyle.Balanced }, - { name: '更精确', type: BingConversationStyle.Precise } -] - -interface ToneSelectorProps { - type: BingConversationStyle | '' - onChange?: (type: BingConversationStyle) => void -} - -export function ToneSelector({ type, onChange }: ToneSelectorProps) { - return ( -
          -
          - 选择对话样式 -
          -
          -
            - { - ToneList.map(tone => ( -
          • onChange?.(tone.type)}> - -
          • - )) - } -
          -
          -
          - ) -} diff --git a/spaces/zomehwh/sovits-models/inference/infer_tool_grad.py b/spaces/zomehwh/sovits-models/inference/infer_tool_grad.py deleted file mode 100644 index b75af49c08e2e724839828bc419792ed580809bb..0000000000000000000000000000000000000000 --- a/spaces/zomehwh/sovits-models/inference/infer_tool_grad.py +++ /dev/null @@ -1,160 +0,0 @@ -import hashlib -import json -import logging -import os -import time -from pathlib import Path -import io -import librosa -import maad -import numpy as np -from inference import slicer -import parselmouth -import soundfile -import torch -import torchaudio - -from hubert import hubert_model -import utils -from models import SynthesizerTrn -logging.getLogger('numba').setLevel(logging.WARNING) -logging.getLogger('matplotlib').setLevel(logging.WARNING) - -def resize2d_f0(x, target_len): - source = np.array(x) - source[source < 0.001] = np.nan - target = np.interp(np.arange(0, len(source) * target_len, len(source)) / target_len, np.arange(0, len(source)), - source) - res = np.nan_to_num(target) - return res - -def get_f0(x, p_len,f0_up_key=0): - - time_step = 160 / 16000 * 1000 - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - - f0 = parselmouth.Sound(x, 16000).to_pitch_ac( - time_step=time_step / 1000, voicing_threshold=0.6, - pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency'] - - pad_size=(p_len - len(f0) + 1) // 2 - if(pad_size>0 or p_len - len(f0) - pad_size>0): - f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant') - - f0 *= pow(2, f0_up_key / 12) - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (f0_mel_max - f0_mel_min) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - f0_coarse = np.rint(f0_mel).astype(np.int) - return f0_coarse, f0 - -def clean_pitch(input_pitch): - num_nan = np.sum(input_pitch == 1) - if num_nan / len(input_pitch) > 0.9: - input_pitch[input_pitch != 1] = 1 - return input_pitch - - -def plt_pitch(input_pitch): - input_pitch = input_pitch.astype(float) - input_pitch[input_pitch == 1] = np.nan - return input_pitch - - -def f0_to_pitch(ff): - f0_pitch = 69 + 12 * np.log2(ff / 440) - return f0_pitch - - -def fill_a_to_b(a, b): - if len(a) < len(b): - for _ in range(0, len(b) - len(a)): - a.append(a[0]) - - -def mkdir(paths: list): - for path in paths: - if not os.path.exists(path): - os.mkdir(path) - - -class VitsSvc(object): - def __init__(self): - self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - self.SVCVITS = None - self.hps = None - self.speakers = None - self.hubert_soft = utils.get_hubert_model() - - def set_device(self, device): - self.device = torch.device(device) - self.hubert_soft.to(self.device) - if self.SVCVITS != None: - self.SVCVITS.to(self.device) - - def loadCheckpoint(self, path): - self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json") - self.SVCVITS = SynthesizerTrn( - self.hps.data.filter_length // 2 + 1, - self.hps.train.segment_size // self.hps.data.hop_length, - **self.hps.model) - _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", self.SVCVITS, None) - _ = self.SVCVITS.eval().to(self.device) - self.speakers = self.hps.spk - - def get_units(self, source, sr): - source = source.unsqueeze(0).to(self.device) - with torch.inference_mode(): - units = self.hubert_soft.units(source) - return units - - - def get_unit_pitch(self, in_path, tran): - source, sr = torchaudio.load(in_path) - source = torchaudio.functional.resample(source, sr, 16000) - if len(source.shape) == 2 and source.shape[1] >= 2: - source = torch.mean(source, dim=0).unsqueeze(0) - soft = self.get_units(source, sr).squeeze(0).cpu().numpy() - f0_coarse, f0 = get_f0(source.cpu().numpy()[0], soft.shape[0]*2, tran) - return soft, f0 - - def infer(self, speaker_id, tran, raw_path): - speaker_id = self.speakers[speaker_id] - sid = torch.LongTensor([int(speaker_id)]).to(self.device).unsqueeze(0) - soft, pitch = self.get_unit_pitch(raw_path, tran) - f0 = torch.FloatTensor(clean_pitch(pitch)).unsqueeze(0).to(self.device) - stn_tst = torch.FloatTensor(soft) - with torch.no_grad(): - x_tst = stn_tst.unsqueeze(0).to(self.device) - x_tst = torch.repeat_interleave(x_tst, repeats=2, dim=1).transpose(1, 2) - audio = self.SVCVITS.infer(x_tst, f0=f0, g=sid)[0,0].data.float() - return audio, audio.shape[-1] - - def inference(self,srcaudio,chara,tran,slice_db): - sampling_rate, audio = srcaudio - 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) - soundfile.write("tmpwav.wav", audio, 16000, format="wav") - chunks = slicer.cut("tmpwav.wav", db_thresh=slice_db) - audio_data, audio_sr = slicer.chunks2audio("tmpwav.wav", chunks) - audio = [] - for (slice_tag, data) in audio_data: - length = int(np.ceil(len(data) / audio_sr * self.hps.data.sampling_rate)) - raw_path = io.BytesIO() - soundfile.write(raw_path, data, audio_sr, format="wav") - raw_path.seek(0) - if slice_tag: - _audio = np.zeros(length) - else: - out_audio, out_sr = self.infer(chara, tran, raw_path) - _audio = out_audio.cpu().numpy() - audio.extend(list(_audio)) - audio = (np.array(audio) * 32768.0).astype('int16') - return (self.hps.data.sampling_rate,audio) diff --git a/spaces/zomehwh/sovits-teio/vdecoder/hifigan/nvSTFT.py b/spaces/zomehwh/sovits-teio/vdecoder/hifigan/nvSTFT.py deleted file mode 100644 index 88597d62a505715091f9ba62d38bf0a85a31b95a..0000000000000000000000000000000000000000 --- a/spaces/zomehwh/sovits-teio/vdecoder/hifigan/nvSTFT.py +++ /dev/null @@ -1,111 +0,0 @@ -import math -import os -os.environ["LRU_CACHE_CAPACITY"] = "3" -import random -import torch -import torch.utils.data -import numpy as np -import librosa -from librosa.util import normalize -from librosa.filters import mel as librosa_mel_fn -from scipy.io.wavfile import read -import soundfile as sf - -def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False): - sampling_rate = None - try: - data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile. - except Exception as ex: - print(f"'{full_path}' failed to load.\nException:") - print(ex) - if return_empty_on_exception: - return [], sampling_rate or target_sr or 32000 - else: - raise Exception(ex) - - if len(data.shape) > 1: - data = data[:, 0] - assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension) - - if np.issubdtype(data.dtype, np.integer): # if audio data is type int - max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX - else: # if audio data is type fp32 - max_mag = max(np.amax(data), -np.amin(data)) - max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32 - - data = torch.FloatTensor(data.astype(np.float32))/max_mag - - if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except - return [], sampling_rate or target_sr or 32000 - if target_sr is not None and sampling_rate != target_sr: - data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr)) - sampling_rate = target_sr - - return data, sampling_rate - -def dynamic_range_compression(x, C=1, clip_val=1e-5): - return np.log(np.clip(x, a_min=clip_val, a_max=None) * C) - -def dynamic_range_decompression(x, C=1): - return np.exp(x) / C - -def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): - return torch.log(torch.clamp(x, min=clip_val) * C) - -def dynamic_range_decompression_torch(x, C=1): - return torch.exp(x) / C - -class STFT(): - def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5): - self.target_sr = sr - - self.n_mels = n_mels - self.n_fft = n_fft - self.win_size = win_size - self.hop_length = hop_length - self.fmin = fmin - self.fmax = fmax - self.clip_val = clip_val - self.mel_basis = {} - self.hann_window = {} - - def get_mel(self, y, center=False): - sampling_rate = self.target_sr - n_mels = self.n_mels - n_fft = self.n_fft - win_size = self.win_size - hop_length = self.hop_length - fmin = self.fmin - fmax = self.fmax - clip_val = self.clip_val - - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - if fmax not in self.mel_basis: - mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax) - self.mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device) - self.hann_window[str(y.device)] = torch.hann_window(self.win_size).to(y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_length)/2), int((n_fft-hop_length)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_length, win_length=win_size, window=self.hann_window[str(y.device)], - center=center, pad_mode='reflect', normalized=False, onesided=True) - # print(111,spec) - spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9)) - # print(222,spec) - spec = torch.matmul(self.mel_basis[str(fmax)+'_'+str(y.device)], spec) - # print(333,spec) - spec = dynamic_range_compression_torch(spec, clip_val=clip_val) - # print(444,spec) - return spec - - def __call__(self, audiopath): - audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr) - spect = self.get_mel(audio.unsqueeze(0)).squeeze(0) - return spect - -stft = STFT() diff --git a/spaces/zxy666/bingo-chatai666/src/lib/isomorphic/node.ts b/spaces/zxy666/bingo-chatai666/src/lib/isomorphic/node.ts deleted file mode 100644 index da213ad6a86181979f098309c374da02835db5a0..0000000000000000000000000000000000000000 --- a/spaces/zxy666/bingo-chatai666/src/lib/isomorphic/node.ts +++ /dev/null @@ -1,26 +0,0 @@ -import Debug from 'debug' - -const { fetch, setGlobalDispatcher, ProxyAgent } = require('undici') -const { HttpsProxyAgent } = require('https-proxy-agent') -const ws = require('ws') - -const debug = Debug('bingo') - -const httpProxy = process.env.http_proxy || process.env.HTTP_PROXY || process.env.https_proxy || process.env.HTTPS_PROXY; -let WebSocket = ws.WebSocket - -if (httpProxy) { - setGlobalDispatcher(new ProxyAgent(httpProxy)) - const agent = new HttpsProxyAgent(httpProxy) - // @ts-ignore - WebSocket = class extends ws.WebSocket { - constructor(address: string | URL, options: typeof ws.WebSocket) { - super(address, { - ...options, - agent, - }) - } - } -} - -export default { fetch, WebSocket, debug }