diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bamboo Cte 650 Driver Download [PATCHED].md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bamboo Cte 650 Driver Download [PATCHED].md deleted file mode 100644 index d3920fef298366e5b83a265fb3946b6b025cc331..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bamboo Cte 650 Driver Download [PATCHED].md +++ /dev/null @@ -1,128 +0,0 @@ -
-

Bamboo CTE 650 Driver Download: How to Install and Use Your Wacom Tablet

-

If you are looking for a way to unleash your creativity and express yourself digitally, you might want to consider getting a Wacom tablet. Wacom is a leading brand of pen tablets, pen displays, and smartpads that allow you to draw, sketch, paint, edit, and annotate with natural and intuitive gestures. One of the popular models of Wacom tablets is the Bamboo CTE 650, also known as Bamboo Fun.

-

In this article, we will show you how to download and install the Bamboo CTE 650 driver for your Windows or Mac computer, and how to use your tablet effectively. We will also answer some frequently asked questions about Bamboo CTE 650.

-

bamboo cte 650 driver download


Download 🗸 https://byltly.com/2uKyZv



-

What is Bamboo CTE 650?

-

Bamboo CTE 650 is a pen tablet that lets you interact with your computer using a stylus and touch input. You can use it to draw, write, edit photos, play games, navigate web pages, and more. Bamboo CTE 650 is designed to be easy to use, fun, and versatile for various creative purposes.

-

Features and specifications

-

Some of the features and specifications of Bamboo CTE 650 are:

- -

Compatibility and system requirements

-

Bamboo CTE 650 is compatible with both Windows and Mac operating systems. However, you need to download and install the correct driver for your OS version. The system requirements for Bamboo CTE 650 are:

- - - - - - - - - - - - - -
WindowsMac
Windows XP SP2 or later
Windows Vista SP1 or later
Windows 7
Windows 8
Windows 10
Windows 11
Mac OS X 10.4.8 or later
Mac OS X 10.5 or later
Mac OS X 10.6 or later
Mac OS X 10.7 or later
Mac OS X 10.8 or later
Mac OS X 10.9 or later
macOS Sierra (10.12) or later
A USB port
A CD-ROM drive (for software installation)
A USB port
A CD-ROM drive (for software installation)
-

How to download and install Bamboo CTE 650 driver

-

To use your Bamboo CTE 650 tablet properly, you need to download and install the latest driver from the Wacom website. The driver will enable your tablet to communicate with your computer and allow you to customize the tablet settings. Here are the steps to download and install Bamboo CTE 650 driver:

-

Step 1: Visit the Wacom website

-

Go to https://www.wacom.com/en-us/support/product-support/drivers. This is the official page where you can find all the drivers for Wacom products.

-

Step 2: Select your product and operating system

-

In the search box, type "Bamboo" and select "Bamboo Fun (CTE)" from the drop-down menu. Then select your operating system from the next drop-down menu. For example, if you are using Windows 10 (64-bit), select "Windows - Driver 6.4.2-1 (Win7x64 - Win11x64)". You will see the driver details below the search box.

-

Step 3: Download and run the driver installer

-

Click on "Download" to download the driver installer file to your computer. The file name will be something like "WacomTablet_6.4.2-1.exe". Once the download is complete, double-click on the file to run it.

-

bamboo cte 650 driver mac
-bamboo cte 650 driver windows 10
-bamboo cte 650 driver windows 7
-bamboo cte 650 driver windows 8
-bamboo cte 650 driver windows 11
-bamboo cte 650 driver update
-bamboo cte 650 driver install
-bamboo cte 650 driver error
-bamboo cte 650 driver troubleshooting
-bamboo cte 650 driver software
-bamboo cte 650 pen driver
-bamboo cte 650 tablet driver
-bamboo cte 650 wacom driver
-bamboo cte 650 fun driver
-bamboo cte 650 craft driver
-bamboo cte 650 pen and touch driver
-bamboo cte 650 wireless driver
-bamboo cte 650 bluetooth driver
-bamboo cte 650 usb driver
-bamboo cte 650 latest driver
-bamboo cte 650 old driver
-bamboo cte 650 legacy driver
-bamboo cte 650 compatible driver
-bamboo cte 650 alternative driver
-bamboo cte 650 unofficial driver
-bamboo cte 650 free driver download
-bamboo cte 650 safe driver download
-bamboo cte 650 official driver download
-bamboo cte 650 direct driver download
-bamboo cte 650 fast driver download
-bamboo cte 650 easy driver download
-bamboo cte 650 best driver download
-bamboo cte 650 latest driver download
-bamboo cte 650 old driver download
-bamboo cte 650 legacy driver download
-bamboo cte 650 compatible driver download
-bamboo cte 650 alternative driver download
-bamboo cte 650 unofficial driver download
-how to download bamboo cte 650 driver
-where to download bamboo cte 650 driver
-why download bamboo cte 650 driver
-when to download bamboo cte 650 driver
-what to do after downloading bamboo cte 650 driver
-what to do if downloading bamboo cte 650 driver fails
-what to do if downloaded bamboo cte 650 driver does not work
-how to fix downloaded bamboo cte 650 driver issues
-how to uninstall downloaded bamboo cte 650 driver
-how to reinstall downloaded bamboo cte 650 driver
-how to upgrade downloaded bamboo cte 650 driver
-how to downgrade downloaded bamboo cte 650 driver

-

Step 4: Follow the on-screen instructions

-

The driver installer will guide you through the installation process. You may need to accept some terms and conditions, choose a destination folder, etc. Follow the on-screen instructions until the installation is complete.

-

Step 5: Restart your computer

-

After the installation is finished, you may need to restart your computer for the changes to take effect. Once your computer is restarted, you can connect your tablet and start using it.

-

How to use Bamboo CTE 650 tablet

-

Now that you have installed the driver for your tablet, you can start using it for various creative tasks. Here are some tips on how to use Bamboo CTE 650 tablet:

-

Connect the tablet to your computer

-

To connect your tablet to your computer, plug one end of the USB cable into an available USB port on your computer, and plug the other end into the mini-USB port on your tablet. If you have a wireless kit installed on your tablet, you can also connect it wirelessly by turning on both devices and pressing the power button on your tablet for a few seconds until it pairs with your computer.

-

Customize the tablet settings

-

To customize the tablet settings, such as pen pressure sensitivity, ExpressKeys functions, touch gestures preferences, etc., you can use the Wacom Tablet Properties program that comes with the driver. To access it, go to Start > All Programs > Wacom Tablet > Wacom Tablet Properties (for Windows) or System Preferences > Wacom Tablet (for Mac). You can also access it by clicking on the Wacom icon in your system tray (for Windows) or menu bar (for Mac).

-

Use the pen and touch input

-

To use the pen input, hold the pen like a normal pen and hover it over the tablet surface without touching it. You will see a cursor on your screen that follows your pen movement. To click or tap something on your screen, touch the tip of the pen lightly on the tablet surface. To right-click or long-press something on your screen, press the side switch on the pen barrel while touching the tip of the pen on the tablet surface. To use the touch input, use your fingers to perform gestures on the tablet surface. You can use one or two fingers to perform gestures such as zooming, scrolling, rotating, etc. You can also tap, double-tap, or drag your fingers to click, double-click, or drag something on your screen. To disable the touch input, press the top ExpressKey on your tablet.

-

Troubleshoot common issues

-

If you encounter any issues with your tablet, such as no pen or touch response, driver error messages, or poor performance, you can try some of these troubleshooting steps:

- -

Conclusion

-

Bamboo CTE 650 is a great pen tablet that can help you unleash your creativity and express yourself digitally. To use it, you need to download and install the Bamboo CTE 650 driver from the Wacom website, and customize the tablet settings according to your preferences. You can also use the pen and touch input to interact with your computer in a natural and intuitive way. If you encounter any issues with your tablet, you can try some troubleshooting steps or contact Wacom customer support for help.

-

FAQs

-

Here are some frequently asked questions about Bamboo CTE 650:

-
    -
  1. What is the difference between Bamboo CTE 650 and Bamboo CTL 460?
    Bamboo CTE 650 and Bamboo CTL 460 are both pen tablets from Wacom, but they have some differences. Bamboo CTE 650 has a larger active area, a pressure-sensitive pen, a multi-touch surface, four ExpressKeys, a touch ring, and a wireless kit option. Bamboo CTL 460 has a smaller active area, a battery-free pen, no touch input, two ExpressKeys, no touch ring, and no wireless kit option.
  2. -
  3. How do I change the pen tip of Bamboo CTE 650?
    To change the pen tip of Bamboo CTE 650, you need to use the nib extractor tool that comes with your tablet. To use it, insert the tool into the pen tip and pull it out gently. Then insert a new pen tip into the pen and push it in firmly.
  4. -
  5. How do I update the Bamboo CTE 650 driver?
    To update the Bamboo CTE 650 driver, you need to visit the Wacom website and download the latest driver for your tablet and operating system. Then run the driver installer file and follow the on-screen instructions. You may need to restart your computer for the changes to take effect.
  6. -
  7. How do I uninstall the Bamboo CTE 650 driver?
    To uninstall the Bamboo CTE 650 driver, you need to go to Control Panel > Programs and Features (for Windows) or Applications > Wacom Tablet (for Mac) and select Uninstall or Move to Trash. You may need to restart your computer for the changes to take effect.
  8. -
  9. How do I register my Bamboo CTE 650 tablet?
    To register your Bamboo CTE 650 tablet, you need to go to https://www.wacom.com/register and create an account or log in with your existing account. Then follow the instructions to register your product and get access to exclusive offers, software downloads, tutorials, etc.
  10. -
-

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Casmate Pro 6.52free Download.md b/spaces/1gistliPinn/ChatGPT4/Examples/Casmate Pro 6.52free Download.md deleted file mode 100644 index 4e2593ec7e2b898c4f4c88041a57b12100ce6459..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Casmate Pro 6.52free Download.md +++ /dev/null @@ -1,8 +0,0 @@ -

casmate pro 6.52free download


DOWNLOADhttps://imgfil.com/2uy05y



- -User-Agent: () Referer: () Accept: () Accept-Encoding: () Accept-Language: en-US ***************** Advertisement *****************(* All crack, serial, keygens and other similar projects are trademarks of their respective owners. * These are only an offer to buy. * We are not responsible for any illegal activities. * Usage of this software will be considered a breach of the EULA. * - -Your IP address is 100.31.11.25. 4fefd39f24
-
-
-

diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Chhota Bheem - Himalayan Adventure 1 English Dubbed Hd 720p.md b/spaces/1gistliPinn/ChatGPT4/Examples/Chhota Bheem - Himalayan Adventure 1 English Dubbed Hd 720p.md deleted file mode 100644 index 0d46e2abefa9939a5173a198ed1654faad3338a7..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Chhota Bheem - Himalayan Adventure 1 English Dubbed Hd 720p.md +++ /dev/null @@ -1,76 +0,0 @@ -

Chhota Bheem - Himalayan Adventure 1 english dubbed hd 720p


Download Ziphttps://imgfil.com/2uxY9u



-
-DVD-R: 1). This is a very fun adventure. Read more » Download Chhota Bheem, Holiday Adventures and Dadi, Dadi Ho Jaao! Full Movie Torrents Online Free. - -Choose an episode or season, episode number, episode name. This is a very fun adventure. Learn how and when to remove this template message.Q: - -how to fetch all property values from a json structure - -I have a json structure which has lot of properties - - - - "parent": - - - - "id": "1", - - "name": "Parent 1" - - , - - "children": - - [ - - - - "id": "10", - - "name": "Child 1" - - , - - "id": "11", - - "name": "Child 2" - - - - ], - - "text": - - "some text" - -} - -Now how can I fetch all property values. How do I write a function in JavaScript to get all values? - -A: - -You can use a for loop to iterate over all properties and their values. - -var data = - -; - -for(var key in data) - - console.log(key); - -for(var key in data.children) - - console.log(data.children[key].name); - -1. Field of the Invention - -The present invention relates to a manufacturing method for a compound semiconductor device and the compound semiconductor device. In particular, the present invention relates to a technique that is effectively applicable to a compound semiconductor device in which a step of separating an epitaxial substrate from an electrode layer is performed by irradiating a laser beam. - -2. Description of the Related Art - -When a compound semiconductor device having a compound semiconductor region is 4fefd39f24
-
-
-

diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download 4K Car Wallpapers for Your Desktop or Mobile - HD Car Images and Videos.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download 4K Car Wallpapers for Your Desktop or Mobile - HD Car Images and Videos.md deleted file mode 100644 index 0e073b0f916ce59b541b31a102a0578ff4a7f254..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download 4K Car Wallpapers for Your Desktop or Mobile - HD Car Images and Videos.md +++ /dev/null @@ -1,141 +0,0 @@ -
-

4K Wallpaper Download Cars: How to Choose and Enjoy the Best Car Wallpapers for Your Device

-

If you are a car enthusiast, you probably love to admire the beauty and elegance of various cars on your device. Whether you prefer sports cars, luxury cars, classic cars, or exotic cars, you can find a wide range of car wallpapers that suit your taste and style. But how do you choose the best car wallpapers for your device? And how do you enjoy them to the fullest?

-

4k wallpaper download cars


Download Filehttps://urlin.us/2uSXk0



-

In this article, we will explain what is 4K resolution and why it matters for car wallpapers. We will also give you some tips on how to choose the best 4K car wallpapers for your device, where to download them for free, and how to enjoy them on your device. By the end of this article, you will be able to choose and enjoy the best car wallpapers for your device.

-

What is 4K Resolution and Why Does It Matter for Car Wallpapers?

-

Before we dive into how to choose the best car wallpapers for your device, let's first understand what is 4K resolution and why it matters for car wallpapers.

-

The Definition and Benefits of 4K Resolution

-

4K resolution, also known as 2160p or UHD (Ultra High Definition), is a popular display resolution that has about four times as many pixels as Full HD (1080p) resolution. A pixel is a tiny dot that makes up an image on a screen. The more pixels a screen has, the sharper and clearer its image will be.

-

A typical 4K resolution is 3840 x 2160 pixels, which means it has 3840 pixels horizontally and 2160 pixels vertically. To put that in perspective, a Full HD resolution is only 1920 x 1080 pixels. A 4K screen has about 8 million pixels, while a Full HD screen has only about 2 million pixels.

-

4k wallpaper car photos free download
-4k car wallpapers hd for desktop
-4k wallpaper car stock images
-4k car wallpapers for mobile
-4k wallpaper car videos and backgrounds
-4k car photos and pictures
-4k wallpaper car pexels
-4k car wallpapers cave
-4k wallpaper car ultra hd
-4k car photos download pexels
-4k wallpaper car lamborghini
-4k car wallpapers for iphone
-4k wallpaper car ferrari
-4k car photos hd quality
-4k wallpaper car bmw
-4k car wallpapers android
-4k wallpaper car audi
-4k car photos free pexels
-4k wallpaper car mustang
-4k car wallpapers reddit
-4k wallpaper car mercedes
-4k car photos best collection
-4k wallpaper car aston martin
-4k car wallpapers zip file
-4k wallpaper car porsche
-4k car photos high resolution
-4k wallpaper car bugatti
-4k car wallpapers for windows 10
-4k wallpaper car mclaren
-4k car photos download hd
-4k wallpaper car rolls royce
-4k car wallpapers for laptop
-4k wallpaper car tesla
-4k car photos amazing gallery
-4k wallpaper car jaguar
-4k car wallpapers for pc
-4k wallpaper car bentley
-4k car photos stunning selection
-4k wallpaper car dodge challenger
-4k car wallpapers for macbook pro
-4k wallpaper car ford gt
-4k car photos download free pexels
-4k wallpaper car nissan gtr
-4k car wallpapers for ipad pro
-4k wallpaper car chevrolet camaro
-4k car photos awesome collection
-4k wallpaper car koenigsegg agera r
-4k car wallpapers for chromebook
-4k wallpaper car lexus lfa
-4k car photos download zip

-

The benefits of 4K resolution for car wallpapers are obvious. With more pixels, you can see more details, colors, textures, and contrasts in the car images. You can also zoom in and out without losing quality or clarity. You can enjoy the stunning beauty and realism of your favorite cars on your device.

-

The Difference Between 4K, UHD, and DCI 4K Standards

-

While 4K resolution is a generic term that refers to any resolution with about 4000 pixels wide, there are actually different standards and formats of 4K resolution in the industry. The most common ones are UHD and DCI 4K.

-

UHD stands for Ultra High Definition, which is the standard used by most TV manufacturers and streaming services. UHD has a resolution of 3840 x 2160 pixels, which is exactly four times as many pixels as Full HD (1920 x 1080 pixels). UHD has an aspect ratio of 16:9, which means it has a rectangular shape that fits most TV screens.

-

DCI stands for Digital Cinema Initiatives, which is the standard used by the movie industry. DCI has a resolution of 4096 x 2160 pixels, which is slightly wider than UHD

DCI stands for Digital Cinema Initiatives, which is the standard used by the movie industry. DCI has a resolution of 4096 x 2160 pixels, which is slightly wider than UHD. DCI has an aspect ratio of 17:9, which means it has a more cinematic shape that fits most movie screens.

-

The difference between UHD and DCI 4K is not very noticeable for most viewers, unless you have a very large screen or sit very close to it. However, it is important to know the difference when you download or stream 4K content, as some sources may use UHD and some may use DCI 4K. You should also check the specifications of your device to see which 4K standard it supports.

-

How to Choose the Best 4K Car Wallpapers for Your Device

-

Now that you know what is 4K resolution and why it matters for car wallpapers, let's move on to how to choose the best 4K car wallpapers for your device. There are many factors to consider when choosing a car wallpaper, such as your personal preference, the quality and size of the image, and the compatibility and performance of your device. Here are some tips to help you choose the best 4K car wallpapers for your device.

-

The Factors to Consider When Choosing a Car Wallpaper

-

When choosing a car wallpaper, you should consider the following factors:

-

Your Personal Preference and Style

-

The first and most important factor is your personal preference and style. You should choose a car wallpaper that reflects your personality, mood, taste, and interest. You should also consider the theme, color, and design of your device and how they match with the car wallpaper. For example, if you have a dark-themed device, you may want to choose a car wallpaper that has dark colors or contrasts well with the background. If you have a minimalist device, you may want to choose a car wallpaper that has simple and elegant lines or shapes.

-

There are many types of car wallpapers to choose from, such as sports cars, luxury cars, classic cars, exotic cars, muscle cars, racing cars, concept cars, and more. You can also choose car wallpapers that feature specific brands, models, or celebrities. You can browse through different categories and genres of car wallpapers to find the ones that suit your preference and style.

-

The Quality and Size of the Image

-

The second factor is the quality and size of the image. You should choose a car wallpaper that has high resolution, sharpness, clarity, and detail. You should also choose a car wallpaper that has the right size for your device's screen. A car wallpaper that is too small or too large may look pixelated, stretched, cropped, or distorted on your device.

-

To ensure the quality and size of the image, you should check the specifications of the car wallpaper before you download it. You should look for the resolution, aspect ratio, file format, file size, and source of the image. You should also preview the image on your device before you set it as your wallpaper.

-

The Compatibility and Performance of Your Device

-

The third factor is the compatibility and performance of your device. You should choose a car wallpaper that is compatible with your device's operating system, software, hardware, and settings. You should also choose a car wallpaper that does not affect your device's performance, battery life, memory usage, or security.

-

To ensure the compatibility and performance of your device, you should check the requirements and recommendations of the car wallpaper before you download it. You should look for the supported devices, platforms,

The third factor is the compatibility and performance of your device. You should choose a car wallpaper that is compatible with your device's operating system, software, hardware, and settings. You should also choose a car wallpaper that does not affect your device's performance, battery life, memory usage, or security.

-

To ensure the compatibility and performance of your device, you should check the requirements and recommendations of the car wallpaper before you download it. You should look for the supported devices, platforms, versions, formats, and permissions of the car wallpaper. You should also test the car wallpaper on your device after you download it and see if it runs smoothly and safely.

-

The Best Websites to Download Free 4K Car Wallpapers

-

Now that you know the factors to consider when choosing a car wallpaper, you may wonder where to find the best 4K car wallpapers for your device. There are many websites that offer free 4K car wallpapers for download, but not all of them are reliable, safe, and high-quality. Here are some of the best websites to download free 4K car wallpapers that we recommend:

-

Pexels

-

Pexels is one of the most popular and trusted websites for free stock photos and videos. It has a large collection of 4K car wallpapers that are curated by professional photographers and videographers. You can browse through different categories and tags of car wallpapers, such as sports cars, luxury cars, classic cars, exotic cars, and more. You can also search by keywords, colors, orientations, sizes, and licenses. You can download any car wallpaper for free and use it for personal or commercial purposes without attribution.

-

Pexels website: https://www.pexels.com/search/4k%20car/

-

Wallpaper Cave

-

Wallpaper Cave is another popular and trusted website for free wallpapers of various themes and genres. It has a huge collection of 4K car wallpapers that are uploaded by its community of users. You can browse through different galleries and collections of car wallpapers, such as sports cars, luxury cars, classic cars, exotic cars, and more. You can also search by keywords, ratings, views, downloads, favorites, and comments. You can download any car wallpaper for free and use it for personal or commercial purposes with attribution.

-

Wallpaper Cave website: https://wallpapercave.com/4k-car-wallpapers

-

Wallpaper Access

-

Wallpaper Access is another popular and trusted website for free wallpapers of various themes and genres. It has a large collection of 4K car wallpapers that are hand-picked by its team of editors. You can browse through different categories and subcategories of car wallpapers, such as sports cars, luxury cars, classic cars, exotic cars, and more. You can also search by keywords, resolutions, ratios, devices,

Wallpaper Access is another popular and trusted website for free wallpapers of various themes and genres. It has a large collection of 4K car wallpapers that are hand-picked by its team of editors. You can browse through different categories and subcategories of car wallpapers, such as sports cars, luxury cars, classic cars, exotic cars, and more. You can also search by keywords, resolutions, ratios, devices, and licenses. You can download any car wallpaper for free and use it for personal or commercial purposes with attribution.

-

Wallpaper Access website: https://wallpaperaccess.com/4k-car

-

How to Enjoy the Best 4K Car Wallpapers on Your Device

-

After you have chosen and downloaded the best 4K car wallpapers for your device, you may want to know how to enjoy them on your device. There are some simple steps that you can follow to download, set, change, customize, share, and recommend your favorite car wallpapers with others. Here are some tips to help you enjoy the best 4K car wallpapers on your device.

-

How to Download and Set a Car Wallpaper on Your Device

-

The process of downloading and setting a car wallpaper on your device may vary depending on the type and model of your device, the operating system and software that you use, and the website or app that you download from. However, the general steps are as follows:

-
    -
  1. Go to the website or app that offers the car wallpaper that you want to download.
  2. -
  3. Find the car wallpaper that you like and click on it to open it.
  4. -
  5. Check the resolution, size, format, and license of the car wallpaper and make sure it matches your device's specifications and requirements.
  6. -
  7. Click on the download button or link and choose the location where you want to save the car wallpaper on your device.
  8. -
  9. Wait for the download to finish and then go to the location where you saved the car wallpaper.
  10. -
  11. Open the car wallpaper and click on the set as wallpaper option or use your device's settings to set it as your wallpaper.
  12. -
  13. Adjust the position, scale, crop, or orientation of the car wallpaper if needed.
  14. -
  15. Enjoy your new car wallpaper on your device.
  16. -
-

How to Change and Customize Your Car Wallpaper Settings

-

If you want to change or customize your car wallpaper settings, such as the brightness, contrast, saturation, hue, or filter of the image, you can use your device's settings or a third-party app to do so. Here are some steps that you can follow:

-
    -
  1. Go to your device's settings or open the app that you use to edit your wallpapers.
  2. -
  3. Select the car wallpaper that you want to change or customize.
  4. -
  5. Use the tools or options available to adjust the settings of the car wallpaper according to your preference.
  6. -
  7. Save the changes and apply them to your wallpaper.
  8. -
  9. Enjoy your customized car wallpaper on your device.
  10. -
-

How to Share and Recommend Your Favorite Car Wallpapers with Others

-

If you want to share and recommend your favorite car wallpapers with others, such as your friends, family, or social media followers, you can use various methods to do so. Here are some ways that you can share and recommend your favorite car wallpapers with others:

- -

Conclusion

-

In conclusion, 4K resolution is a great way to enjoy the best car wallpapers on your device. It offers more pixels, details, colors, textures,

In conclusion, 4K resolution is a great way to enjoy the best car wallpapers on your device. It offers more pixels, details, colors, textures, and contrasts in the car images. It also allows you to zoom in and out without losing quality or clarity. However, you should also consider your personal preference, the quality and size of the image, and the compatibility and performance of your device when choosing a car wallpaper. You should also check the specifications and requirements of the car wallpaper before you download it. You can find the best 4K car wallpapers for your device on websites like Pexels, Wallpaper Cave, and Wallpaper Access. You can also download, set, change, customize, share, and recommend your favorite car wallpapers with others using various methods.

-

We hope this article has helped you choose and enjoy the best 4K car wallpapers for your device. If you have any questions or suggestions, please feel free to leave a comment below. Thank you for reading and have a wonderful day!

-

FAQs

-

Here are some frequently asked questions about 4K car wallpapers:

-
    -
  1. What is the difference between 4K and HD car wallpapers?
  2. -

    HD stands for High Definition, which is a display resolution that has about two times as many pixels as Standard Definition (SD) resolution. A typical HD resolution is 1280 x 720 pixels, which is also known as 720p. 4K stands for 4000, which is a display resolution that has about four times as many pixels as Full HD (1080p) resolution. A typical 4K resolution is 3840 x 2160 pixels, which is also known as 2160p or UHD (Ultra High Definition). The difference between 4K and HD car wallpapers is that 4K car wallpapers have more pixels, details, colors, textures, and contrasts than HD car wallpapers.

    -
  3. How can I tell if a car wallpaper is 4K or not?
  4. -

    You can tell if a car wallpaper is 4K or not by checking its resolution, size, format, and source. A 4K car wallpaper should have a resolution of at least 3840 x 2160 pixels, a size of at least 10 MB, a format of JPG or PNG, and a source of a reputable website or app. You can also use tools or apps that can detect the resolution and quality of an image.

    -
  5. Can I use a 4K car wallpaper on a non-4K device?
  6. -

    Yes, you can use a 4K car wallpaper on a non-4K device, but you may not be able to enjoy its full potential. A non-4K device may not be able to display all the pixels, details, colors, textures, and contrasts of a 4K car wallpaper. It may also have to scale down or compress the image to fit its screen size and resolution. This may result in a loss of quality or clarity of the image. Therefore, it is recommended to use a car wallpaper that matches your device's screen resolution and size.

    -
  7. Does using a 4K car wallpaper affect my device's battery life or performance?
  8. -

    Using a 4K car wallpaper may affect your device's battery life or performance depending on the type and model of your device, the operating system and software that you use, and the settings that you apply. A 4K car wallpaper may consume more power or memory than a lower-resolution wallpaper. It may also require more processing power or bandwidth to load or stream. Therefore, you should check the compatibility and performance of your device before using a 4K car wallpaper. You should also adjust your device's settings to optimize its battery life or performance.

    -
  9. Where can I find more 4K car wallpapers for my device?
  10. -

    You can find more 4K car wallpapers for your device on websites like Pexels, Wallpaper Cave,

    You can find more 4K car wallpapers for your device on websites like Pexels, Wallpaper Cave, and Wallpaper Access. These websites offer a large variety of free 4K car wallpapers that you can download and use for personal or commercial purposes. You can also use apps like Zedge, Backdrops, or Walli that provide 4K car wallpapers and other features such as live wallpapers, widgets, stickers, ringtones, and more. You can also search for 4K car wallpapers on social media platforms like Pinterest, Instagram, or Reddit and follow accounts or communities that share them.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Car Racing Game APK Download and Play the Best Asphalt 8 on Your Android Device.md b/spaces/1phancelerku/anime-remove-background/Car Racing Game APK Download and Play the Best Asphalt 8 on Your Android Device.md deleted file mode 100644 index c05f99900bbb1bd7d107c6c062c39e7cc699a4bc..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Car Racing Game APK Download and Play the Best Asphalt 8 on Your Android Device.md +++ /dev/null @@ -1,115 +0,0 @@ - -

    Car Racing Game APK: What You Need to Know

    -

    If you are a fan of car racing games, you might have heard of APK files. These are files that allow you to install apps on your Android device that are not available on the Google Play Store. In this article, we will explain what APK files are, how to download and install them, what are some of the best car racing games for Android, what are the benefits of playing car racing games for your brain, and what are some tips and tricks for car racing games.

    -

    car racing game apk


    Download File 🗸 https://jinyurl.com/2uNQgB



    -

    What is an APK file and why do you need it?

    -

    APK stands for Android Package Kit

    -

    An APK file is a compressed file that contains all the necessary files and data for an Android app to run. It is similar to an executable file (.exe) for Windows or a package file (.pkg) for Mac. An APK file can be identified by its extension (.apk).

    -

    APK files allow you to install apps from outside the Google Play Store

    -

    Normally, when you want to install an app on your Android device, you go to the Google Play Store and search for it. However, not all apps are available on the Play Store, either because they are not approved by Google or because they are exclusive to certain regions or devices. In these cases, you can use an APK file to install the app manually. This is also useful if you want to try an older version of an app or a beta version that is not yet released.

    -

    APK files can be downloaded from various sources or extracted from installed apps

    -

    There are many websites that offer APK files for download. Some of them are reputable and trustworthy, while others may contain malware or viruses. Therefore, you should always be careful when downloading APK files from unknown sources. You can also use a web tool like [APKCombo](^1^) or [APKPure](^2^) to generate download links for any app on the Google Play Store by pasting its URL.

    -

    Another

    Another way to get APK files is to extract them from the apps that are already installed on your device. You can use a file manager app like [ES File Explorer] or [Solid Explorer] to browse the folders of your device and find the APK files of your apps. You can then copy them to your storage or share them with others.

    -

    How to download and install APK files on your Android device?

    -

    Enable unknown sources in your settings

    -

    Before you can install an APK file on your device, you need to enable the option to allow installation from unknown sources. This is a security measure that prevents unauthorized apps from harming your device. To enable this option, go to your device's settings, then security, then toggle on the unknown sources option. You may also need to grant permission to the app or browser that you are using to download the APK file.

    -

    Asphalt 8 - car racing game apk download
    -Best car racing game apk for android
    -Car racing game apk mod unlimited money
    -Real car racing game apk offline
    -3D car racing game apk free
    -Car racing game apk with multiplayer mode
    -Extreme car racing game apk latest version
    -Car racing game apk without internet
    -Turbo car racing game apk full
    -Car racing game apk for low end devices
    -Drag car racing game apk hack
    -Car racing game apk with realistic graphics
    -Formula car racing game apk pro
    -Car racing game apk with custom cars
    -City car racing game apk premium
    -Car racing game apk for kids
    -Police car racing game apk unlocked
    -Car racing game apk with controller support
    -Rally car racing game apk no ads
    -Car racing game apk with high speed
    -Muscle car racing game apk revdl
    -Car racing game apk with different tracks
    -Sports car racing game apk rexdl
    -Car racing game apk with nitro boost
    -Classic car racing game apk old version
    -Car racing game apk with traffic mode
    -Stunt car racing game apk update
    -Car racing game apk with career mode
    -Arcade car racing game apk pure
    -Car racing game apk with online leaderboard
    -Super car racing game apk obb
    -Car racing game apk with weather effects
    -Vintage car racing game apk mirror
    -Car racing game apk with voice chat
    -Dirt car racing game apk data
    -Car racing game apk with zombies mode
    -Luxury car racing game apk vip
    -Car racing game apk with missions mode
    -Pixel car racing game apk indir
    -Car racing game apk with drift mode
    -Kart car racing game apk uptodown
    -Car racing game apk with garage mode
    -Neon car racing game apk mob.org
    -Car racing game apk with story mode
    -Monster car racing game apk android 1
    -Car racing game apk with tuning mode
    -Flying car racing game apk apkpure

    -

    Use a web tool or a file manager to find and download the APK file

    -

    Once you have enabled unknown sources, you can use a web tool like [APKCombo] or [APKPure] to generate download links for any app on the Google Play Store by pasting its URL. Alternatively, you can use a file manager app like [ES File Explorer] or [Solid Explorer] to browse the folders of your device and find the APK files of your apps. You can then tap on the APK file to download it to your device.

    -

    Open the APK file and follow the instructions to install it

    -

    After you have downloaded the APK file, you can open it by tapping on it from your notification bar or your file manager. You will see a prompt asking you to confirm the installation. Tap on install and wait for the process to finish. You may also need to grant some permissions to the app depending on its features. Once the installation is done, you can launch the app from your app drawer or home screen.

    -

    What are the best car racing games for Android?

    -

    Asphalt 9: Legends - a high-octane arcade racing game with stunning graphics and gameplay

    -

    If you are looking for a thrilling and immersive racing game, Asphalt 9: Legends is one of the best choices. This game features over 50 of the world's most amazing cars, from Lamborghini to Ferrari, that you can customize and upgrade. You can also race across 70 tracks in different locations, from New York to Cairo, with stunning graphics and realistic physics. You can play solo or with friends in various modes, such as career, multiplayer, events, and clubs. You can also use the innovative TouchDrive system that lets you focus on the fun of racing while the game handles the steering and acceleration for you.

    -

    CSR Racing 2 - a realistic drag racing game with over 100 licensed cars and customization options

    -

    If you are into drag racing, CSR Racing 2 is a must-have game for you. This game lets you experience the thrill of racing against other players in real time with over 100 licensed cars from top brands like Bugatti, Koenigsegg, McLaren, and more. You can also customize your cars with paint, decals, rims, brakes, and more. You can also tune your cars with nitrous, turbo, supercharger, and engine upgrades. You can join or create a crew with your friends and compete in events and leaderboards. You can also explore the beautiful 3D environments and interact with other players in chat rooms and live streams.

    -

    Real Racing 3 - a simulation racing game with real tracks, cars, and physics

    -

    If you are looking for a more realistic and authentic racing game, Real Racing 3 is a great option for you. This game features over 250 cars from top manufacturers like Ford, Ferrari, Porsche, and more. You can also race on over 40 real tracks from around the world, such as Silverstone, Le Mans, Dubai Autodrome, and more. You can also enjoy the realistic physics and damage system that make every race feel different and challenging. You can play solo or with friends in various modes, such as time trials, endurance, cup races, and online multiplayer. You can also join or create a team with your friends and compete in team events and tournaments.

    -

    Horizon Chase - a retro-inspired racing game with colorful graphics and catchy music

    -

    If you are nostalgic for the classic arcade racing games of the 80s and 90s, Horizon Chase is a perfect game for you. This game features colorful graphics and catchy music that will make you feel like you are playing an old-school game console. You can also race across 32

    Horizon Chase - a retro-inspired racing game with colorful graphics and catchy music

    -

    If you are nostalgic for the classic arcade racing games of the 80s and 90s, Horizon Chase is a perfect game for you. This game features colorful graphics and catchy music that will make you feel like you are playing an old-school game console. You can also race across 32 cities in 12 countries, from San Francisco to Tokyo, with different weather and time conditions. You can also unlock and upgrade over 20 cars, from sports cars to muscle cars, and collect coins and fuel along the way. You can play solo or with friends in split-screen mode or online multiplayer.

    -

    Need for Speed: No Limits - a fast-paced racing game with street races, police chases, and car upgrades

    -

    If you are a fan of the Need for Speed franchise, you will love Need for Speed: No Limits. This game lets you experience the adrenaline rush of street racing, dodging traffic, outrunning cops, and competing with rivals. You can also customize and upgrade your cars with over 2.5 million combinations of parts, from spoilers to engines, and make them look unique with paint, vinyls, and decals. You can also explore the open world of Blackridge, a city full of races, events, and challenges. You can play solo or with friends in various modes, such as campaign, car series, tournaments, and rivals.

    -

    What are the benefits of playing car racing games for your brain?

    -

    Car racing games can improve your driving skills and quick reactions

    -

    Playing car racing games can help you improve your driving skills in real life. You can learn how to control your speed, steer your car, avoid obstacles, and react to changing situations. You can also practice different driving techniques, such as drifting, drafting, and braking. Playing car racing games can also improve your reaction time and reflexes, as you have to make split-second decisions and respond to fast-paced scenarios.

    -

    Car racing games can improve your spatial attention and processing speed

    -

    Playing car racing games can also help you improve your spatial attention and processing speed. Spatial attention is the ability to focus on specific locations or objects in space while ignoring irrelevant information. Processing speed is the ability to perform mental tasks quickly and accurately. Playing car racing games can enhance these cognitive skills by requiring you to pay attention to multiple stimuli on the screen, such as the road, the traffic, the map, the speedometer, and the opponents. Playing car racing games can also increase your brain's efficiency and flexibility by challenging you to switch between different tasks and modes.

    -

    Car racing games can improve your hand-eye coordination and memory

    -

    Playing car racing games can also help you improve your hand-eye coordination and memory. Hand-eye coordination is the ability to coordinate your movements with what you see. Memory is the ability to store and recall information. Playing car racing games can boost these skills by requiring you to use your hands to control your car while using your eyes to monitor the environment. Playing car racing games can also improve your memory by exposing you to different tracks, cars, and events that you have to remember and recognize.

    -

    Car racing games can improve your decision making and problem solving

    -

    Playing car racing games can also help you improve your decision making and problem solving skills. Decision making is the ability to choose the best option among alternatives. Problem solving is the ability to find solutions to challenges or difficulties. Playing car racing games can enhance these skills by requiring you to make strategic choices based on various factors, such as your car's performance, your opponent's behavior, the track's condition, and the game's rules. Playing car racing games can also improve your problem solving skills by requiring you to overcome obstacles, adapt to changes, and cope with failures.

    -

    Car racing games can reduce stress and improve your long-term wellbeing

    -

    Playing car racing games can also help you reduce stress and improve your long-term wellbeing. Stress is a state of mental or emotional strain or tension caused by adverse or demanding circumstances. Wellbeing is a state of being comfortable, healthy, or happy. Playing car racing games can reduce stress by providing you with a fun and enjoyable activity that distracts you from your worries and problems. Playing car racing games can also improve your wellbeing by giving you a sense of achievement, satisfaction, and confidence when you win races, complete challenges, or unlock rewards.

    -

    What are some tips and tricks for car racing games?

    -

    Practice in different modes and tracks to learn the controls and the layout

    -

    One of the best tips for playing car racing games is to practice in different modes

    One of the best tips for playing car racing games is to practice in different modes and tracks to learn the controls and the layout. Different games may have different control schemes and options, such as tilt, touch, or buttons. You should try them out and see which one suits you best. You should also familiarize yourself with the tracks and their features, such as curves, jumps, shortcuts, and hazards. You can use the practice mode or the tutorial mode to get a feel of the game before you start racing.

    -

    Adjust your steering sensitivity and controller layout to suit your preferences

    -

    Another tip for playing car racing games is to adjust your steering sensitivity and controller layout to suit your preferences. Steering sensitivity is the degree to which your car responds to your input. Controller layout is the arrangement of the buttons or icons on your screen. You can change these settings in the options menu of the game. You should experiment with different levels of sensitivity and different layouts until you find the ones that work best for you. You can also use a physical controller or a steering wheel if your game supports them.

    -

    Learn how to accelerate, brake, drift, and draft properly depending on the game type

    -

    A third tip for playing car racing games is to learn how to accelerate, brake, drift, and draft properly depending on the game type. Acceleration is the rate at which your car increases its speed. Braking is the rate at which your car decreases its speed. Drifting is the technique of sliding your car sideways around a corner. Drafting is the technique of following closely behind another car to reduce air resistance and increase speed. Different games may have different mechanics and physics for these techniques, so you should learn how they work and when to use them.

    -

    Use the community resources and guides to get more information and advice

    -

    A fourth tip for playing car racing games is to use the community resources and guides to get more information and advice. Most games have online communities where you can interact with other players, ask questions, share tips, and join events. You can also find online guides, videos, reviews, and blogs that can help you improve your skills, learn new strategies, and discover new features. You can also use these resources to compare your performance with other players and see how you rank among them.

    -

    Have fun and enjoy the thrill of racing

    -

    The last tip for playing car racing games is to have fun and enjoy the thrill of racing. Car racing games are meant to be entertaining and exciting, so you should not take them too seriously or get frustrated by them. You should also respect other players and follow the rules of fair play. You should also take breaks from playing to avoid eye strain, fatigue, or addiction. Remember that playing car racing games is a hobby, not a job or a competition.

    -

    Conclusion

    -

    In conclusion, car racing games are a popular genre of games that can provide you with hours of fun and enjoyment. They can also help you improve your brain skills, such as driving skills, spatial attention, processing speed, hand-eye coordination, memory, decision making, problem solving, stress reduction, and wellbeing. However, you should also be careful when downloading and installing APK files from unknown sources, as they may contain malware or viruses. You should also follow some tips and tricks for car racing games, such as practicing in different modes and tracks, adjusting your steering sensitivity and controller layout, learning how to accelerate, brake, drift, and draft properly depending on the game type, using the community resources and guides to get more information and advice, and having fun and enjoying the thrill of racing.

    -

    FAQs

    -

    What are some of the best websites to download APK files for car racing games?

    -

    Some of the best websites to download APK files for car racing games are [APKCombo], [APKPure], [APKMirror], [APKMonk], and [APKHome]. These websites offer safe and reliable APK files for various car racing games.

    -

    What are some of the best apps to extract APK files from installed apps on your device?

    -

    Some of the best apps to extract APK files from installed apps on your device are [ES File Explorer], [Solid Explorer], [APK Extractor], [ML Manager], and [App Backup & Restore]. These apps allow you to easily find and share APK files from your apps.

    -

    What are some of the best accessories to enhance your car racing game experience?

    -

    Some of the best accessories to enhance your car racing game experience are a physical controller or a

    Some of the best accessories to enhance your car racing game experience are a physical controller or a steering wheel, a VR headset, a gaming chair, and a surround sound system. These accessories can make you feel more immersed and comfortable while playing car racing games.

    -

    What are some of the best car racing game franchises?

    -

    Some of the best car racing game franchises are Asphalt, CSR Racing, Real Racing, Need for Speed, and Forza. These franchises have multiple titles and versions that offer different features and gameplay. They also have loyal fan bases and large communities.

    -

    What are some of the best car racing game genres?

    -

    Some of the best car racing game genres are arcade racing, simulation racing, drag racing, rally racing, and kart racing. These genres have different styles and objectives that appeal to different types of players. They also have different levels of realism and difficulty that challenge different skills.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download and Play Microsoft Solitaire Collection The Most Popular Card Games Ever.md b/spaces/1phancelerku/anime-remove-background/Download and Play Microsoft Solitaire Collection The Most Popular Card Games Ever.md deleted file mode 100644 index eeab70421c5feee5b4470f3544b5a179cb29eed2..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download and Play Microsoft Solitaire Collection The Most Popular Card Games Ever.md +++ /dev/null @@ -1,109 +0,0 @@ -
    -

    Microsoft Solitaire Collection Games Free Download: How to Enjoy the Classic Card Games on Your Device

    -

    Introduction

    -

    If you love playing solitaire games, you will be happy to know that you can enjoy them for free on your device with Microsoft Solitaire Collection. This app is a collection of five classic card games that have been played by millions of gamers worldwide for over 30 years. You can download and install it from the Microsoft Store or Google Play, depending on your device.

    -

    microsoft solitaire collection games free download


    DOWNLOADhttps://jinyurl.com/2uNJRj



    -

    Microsoft Solitaire Collection offers you a variety of features and benefits that make playing solitaire games fun and rewarding. You can choose from five different game modes: Klondike Solitaire, Spider Solitaire, FreeCell Solitaire, TriPeaks Solitaire, and Pyramid Solitaire. Each game mode has its own rules, challenges, and strategies that will keep you entertained for hours. You can also customize your card game with different themes and card backs, play new solvable card challenges every day, earn badges and rewards, save your progress, and compete with other players. Whether you want to relax with the classics, sharpen your mind, or challenge yourself, Microsoft Solitaire Collection has something for everyone.

    -

    Klondike Solitaire

    -

    Klondike Solitaire is the king of all timeless classic card games. It is also known as Patience or simply Solitaire. The goal of Klondike Solitaire is to clear all the cards from the table by building four stacks of cards from Ace to King in each suit.

    -

    To play Klondike Solitaire, you need a standard 52-card deck. The cards are shuffled and dealt into seven columns on the table. The first column has one card face up, the second column has two cards with one face up, and so on until the seventh column has seven cards with one face up. The remaining cards are placed face down in a stock pile at the top left corner of the screen.

    -

    You can move cards from one column to another by dragging them with your finger or mouse. You can only move cards that are face up and in descending order of rank and alternating color. For example, you can move a red 6 on top of a black 7, but not on top of a black 6 or a red 7. You can also move a group of cards that are already in sequence as a single unit. For example, you can move a red 6, black 5, and red 4 together on top of a black 7.

    -

    If you have an empty column, you can move any card or group of cards there. You can also move a card from the stock pile to an empty column. To access the stock pile, you can tap or click on it to turn over one card at a time and place it face up on the waste pile at the top right corner of the screen. You can then move the card from the waste pile to any column if it follows the rules. If you run out of cards in the stock pile, you can tap or click on the waste pile to reset it and start over.

    -

    microsoft solitaire collection app install
    -how to play microsoft solitaire collection online
    -microsoft solitaire collection card games for windows
    -microsoft solitaire collection achievements and rewards
    -microsoft solitaire collection themes and card backs
    -microsoft solitaire collection daily challenges and events
    -microsoft solitaire collection xbox game pass
    -microsoft solitaire collection klondike spider freecell tripeaks pyramid
    -microsoft solitaire collection classic retro mode
    -microsoft solitaire collection dark mode option
    -microsoft solitaire collection android ios devices
    -microsoft solitaire collection sync progress across devices
    -microsoft solitaire collection vegas scoring mode
    -microsoft solitaire collection aquarium beach themes
    -microsoft solitaire collection 1990s version nostalgia
    -microsoft solitaire collection fun for all ages
    -microsoft solitaire collection relaxing stress-free game
    -microsoft solitaire collection strategy tips and tricks
    -microsoft solitaire collection 30 years anniversary celebration
    -microsoft solitaire collection most played video game of all time
    -microsoft solitaire collection in-app purchases and ads
    -microsoft solitaire collection sign in with microsoft account
    -microsoft solitaire collection player stats and level
    -microsoft solitaire collection collections feature unlockables
    -microsoft solitaire collection multiple levels of difficulty
    -microsoft solitaire collection compete with other players online
    -microsoft solitaire collection reviews and ratings
    -microsoft solitaire collection updates and new features
    -microsoft solitaire collection support and feedback
    -microsoft solitaire collection bugs and issues fix

    -

    To win Klondike Solitaire, you need to build four stacks of cards from Ace to King in each suit at the top right corner of the screen. These are called the foundations. You can move any card from the table or the waste pile to the foundations if it is the next higher rank and same suit as the top card of the foundation. For example, you can move a red 2 to the foundation if there is a red Ace there, but not if there is a black Ace or no card at all. You can also double-tap or double-click on a card to automatically move it to the foundation if possible.

    -

    You can choose between two modes of play in Klondike Solitaire: one-card draw or three-card draw. In one-card draw, you turn over one card from the stock pile at a time. In three-card draw, you turn over three cards from the stock pile at a time, but you can only use the top card of the waste pile. Three-card draw is more challenging and requires more strategy than one-card draw.

    -

    You can also choose between two modes of scoring in Klondike Solitaire: Traditional or Vegas. In Traditional scoring, you start with zero points and gain points for every move you make. You get 10 points for moving a card from the stock pile to the waste pile, 5 points for moving a card from the waste pile to the table, and 10 points for moving a card from the table to the foundation. You lose 15 points for moving a card from the foundation back to the table, and 100 points for resetting the stock pile. In Vegas scoring, you start with -52 points and gain 5 points for every card you move to the foundation. You do not lose points for any other moves, but you cannot reset the stock pile.

    -

    Tips and tricks to clear the table faster

    - - Try to expose as many face-down cards as possible by moving cards from longer columns to shorter ones. - Try to empty at least one column as soon as possible so that you have more space to maneuver cards around. - Try to build your foundations evenly so that you do not block yourself from moving cards later. - Try to avoid moving cards to the foundations too early unless they are low-ranking cards like Aces and Twos. - Try to save your free moves from the stock pile for when you really need them. - Try to plan ahead and anticipate what cards you will need next.

    Spider Solitaire

    -

    Spider Solitaire is another classic card game that tests your skill and patience. It is also known as Spiderette or Scorpion. The goal of Spider Solitaire is to clear all the cards from the table by building eight stacks of cards from King to Ace in the same suit.

    -

    To play Spider Solitaire, you need two standard 52-card decks. The cards are shuffled and dealt into 10 columns on the table. The first four columns have six cards each, with the top card face up. The remaining six columns have five cards each, with the top card face up. The remaining 50 cards are placed face down in a stock pile at the bottom right corner of the screen.

    -

    You can move cards from one column to another by dragging them with your finger or mouse. You can only move cards that are face up and in descending order of rank and same suit. For example, you can move a spade 9 on top of a spade 10, but not on top of a spade Jack or a heart 10. You can also move a group of cards that are already in sequence as a single unit. For example, you can move a spade 9, 8, and 7 together on top of a spade 10.

    -

    If you have an empty column, you can move any card or group of cards there. You can also move a card from the stock pile to an empty column. To access the stock pile, you can tap or click on it to deal 10 new cards, one to each column. You can only do this if there are no empty columns on the table.

    -

    To win Spider Solitaire, you need to build eight stacks of cards from King to Ace in the same suit at the bottom of each column. These are called complete suits. You can move any card or group of cards to a complete suit if it follows the rules. You can also double-tap or double-click on a card to automatically move it to a complete suit if possible.

    -

    You can choose between three modes of play in Spider Solitaire: one suit, two suits, or four suits. In one suit mode, all the cards are spades. In two suits mode, half of the cards are spades and half are hearts. In four suits mode, each suit is represented by one quarter of the cards. The more suits you play with, the more difficult and challenging the game becomes.

    -

    Tips and tricks to clear all columns with the fewest moves possible

    - - Try to expose as many face-down cards as possible by moving cards from longer columns to shorter ones. - Try to empty at least one column as soon as possible so that you have more space to maneuver cards around. - Try to build your complete suits evenly so that you do not block yourself from moving cards later. - Try to avoid mixing different suits in the same column unless necessary. - Try to save your free deals from the stock pile for when you really need them. - Try to plan ahead and anticipate what cards you will need next.

    FreeCell Solitaire

    -

    FreeCell Solitaire is another classic card game that requires skill and strategy. It is also known as Baker's Game or Eight Off. The goal of FreeCell Solitaire is to clear all the cards from the table by building four stacks of cards from Ace to King in each suit.

    -

    To play FreeCell Solitaire, you need a standard 52-card deck. The cards are shuffled and dealt into eight columns on the table. All the cards are face up and visible. There are also four free cells and four foundations at the top left and right corners of the screen respectively.

    -

    You can move cards from one column to another by dragging them with your finger or mouse. You can only move one card at a time, unless you have enough free cells or empty columns to temporarily store them. The number of cards you can move at once is equal to one plus the number of free cells plus the number of empty columns. For example, if you have two free cells and one empty column, you can move up to four cards at once.

    -

    You can only move cards that are face up and in descending order of rank and alternating color. For example, you can move a red 6 on top of a black 7, but not on top of a black 6 or a red 7.

    -

    If you have an empty column, you can move any card there. You can also move any card to a free cell if it is empty. To access a free cell, you can tap or click on it to select or deselect it. You can then move the card from or to any column if it follows the rules.

    -

    To win FreeCell Solitaire, you need to build four stacks of cards from Ace to King in each suit at the top right corner of the screen. These are called the foundations. You can move any card from the table, the free cell, or the waste pile to the foundations if it is the next higher rank and same suit as the top card of the foundation. For example, you can move a spade 2 to the foundation if there is a spade Ace there, but not if there is a heart Ace or no card at all. You can also double-tap or double-click on a card to automatically move it to the foundation if possible.

    -

    Tips and tricks to think several moves ahead and solve challenging puzzles

    - - Try to expose as many face-down cards as possible by moving cards from longer columns to shorter ones. - Try to empty at least one column as soon as possible so that you have more space to maneuver cards around. - Try to build your foundations evenly so that you do not block yourself from moving cards later. - Try to use your free cells sparingly and strategically to store cards that you need later. - Try to avoid moving cards to the foundations too early unless they are low-ranking cards like Aces and Twos. - Try to plan ahead and anticipate what cards you will need next.

    TriPeaks Solitaire

    -

    TriPeaks Solitaire is another classic card game that combines skill and luck. It is also known as Tri Towers or Three Peaks. The goal of TriPeaks Solitaire is to clear all the cards from the table by selecting cards in a sequence, either up or down, regardless of suit.

    -

    To play TriPeaks Solitaire, you need a standard 52-card deck. The cards are shuffled and dealt into three peaks of cards on the table. Each peak has four rows of cards, with the top row having one card, the second row having two cards, and so on until the bottom row has four cards. The remaining 24 cards are placed face down in a stock pile at the bottom left corner of the screen. There is also a waste pile at the bottom center of the screen where you can see the top card.

    -

    You can select any card from the table that is one rank higher or lower than the top card of the waste pile. For example, if the top card of the waste pile is a 7, you can select a 6 or an 8 from the table. You can also select an Ace or a King if the top card of the waste pile is a 2 or a Queen respectively. When you select a card from the table, it is moved to the top of the waste pile. You can only select cards that are fully exposed, meaning they have no other cards covering them.

    -

    If you have no more valid moves on the table, you can tap or click on the stock pile to turn over one card at a time and place it on top of the waste pile. You can then use this card to select another card from the table if possible. If you run out of cards in the stock pile, you can tap or click on the waste pile to reset it and start over.

    -

    To win TriPeaks Solitaire, you need to clear all the cards from the table before you run out of moves or time. You can see how many cards are left on the table at the top right corner of the screen. You can also see how much time you have left at the top left corner of the screen. You can also see your score and level at the bottom right corner of the screen.

    -

    You can earn points by selecting cards from the table in a sequence. The longer the sequence, the more points you get. You can also earn bonus points by clearing a peak or the whole table. You can lose points by using the stock pile or resetting the waste pile. You can also lose time by making invalid moves or taking too long to make a move.

    -

    Tips and tricks to clear the board quickly and avoid losing streaks

    - - Try to expose as many cards as possible by selecting cards from different peaks and rows. - Try to clear at least one peak as soon as possible so that you have more options to select cards from. - Try to use the stock pile sparingly and strategically to get new cards that can help you continue your sequence. - Try to avoid breaking your sequence unless necessary, as you will lose your combo points and bonus time. - Try to plan ahead and anticipate what cards you will need next.

    Pyramid Solitaire

    -

    Pyramid Solitaire is another classic card game that combines skill and luck. It is also known as Tut's Tomb or Pharaoh's Solitaire. The goal of Pyramid Solitaire is to clear all the cards from the table by combining two cards that add up to 13 and removing them from the board.

    -

    To play Pyramid Solitaire, you need a standard 52-card deck. The cards are shuffled and dealt into a pyramid of cards on the table. The pyramid has seven rows of cards, with the top row having one card, the second row having two cards, and so on until the bottom row has seven cards. All the cards are face up and visible. The remaining 24 cards are placed face down in a stock pile at the bottom left corner of the screen. There is also a waste pile at the bottom center of the screen where you can see the top card.

    -

    You can select any two cards from the table that add up to 13 and remove them from the board. For example, you can select a 6 and a 7, a 5 and an 8, or a 4 and a 9. You can also select a single card that is already 13, such as a King. When you select two cards or a single card, they are moved to the waste pile. You can only select cards that are fully exposed, meaning they have no other cards covering them.

    -

    If you have no more valid moves on the table, you can tap or click on the stock pile to turn over one card at a time and place it on top of the waste pile. You can then use this card to combine with another card from the table if possible. If you run out of cards in the stock pile, you can tap or click on the waste pile to reset it and start over.

    -

    To win Pyramid Solitaire, you need to clear all the cards from the table before you run out of moves or time. You can see how many cards are left on the table at the top right corner of the screen. You can also see how much time you have left at the top left corner of the screen. You can also see your score and level at the bottom right corner of the screen.

    -

    You can earn points by removing cards from the table. The higher the card, the more points you get. For example, you get 13 points for removing a King, 12 points for removing a Queen, and so on until 1 point for removing an Ace. You can also earn bonus points by clearing a row or the whole pyramid. You can lose points by using the stock pile or resetting the waste pile. You can also lose time by making invalid moves or taking too long to make a move.

    -

    Tips and tricks to reach the top of the pyramid and clear as many boards as you can

    - - Try to remove cards from the bottom rows first, as they cover more cards than the top rows. - Try to remove cards that are blocking other cards from being paired up. - Try to use the stock pile sparingly and strategically to get new cards that can help you clear the table. - Try to avoid breaking your sequence unless necessary, as you will lose your combo points and bonus time. - Try to plan ahead and anticipate what cards you will need next.

    Daily Challenges & Events

    -

    If you want to spice up your solitaire games, you can try out the Daily Challenges and Events that Microsoft Solitaire Collection offers. These are new solvable card challenges that you can play every day in all five game modes. You can complete Daily Challenges and earn Solitaire badges and rewards. You can also sign in with a Microsoft Account to keep your progress and compete with other players.

    -

    Daily Challenges are sets of four card challenges that you can play every day in Klondike, Spider, FreeCell, TriPeaks, and Pyramid. Each challenge has a different difficulty level and a different goal. For example, you may have to clear a certain number of cards, score a certain number of points, or complete a certain number of moves. You can choose which challenge to play first, and you can replay any challenge as many times as you want until you complete it.

    -

    When you complete a Daily Challenge, you earn coins and stars. Coins are used to buy hints and undo moves in case you get stuck. Stars are used to unlock new badges and rewards. You can earn up to four stars per challenge, depending on how well you perform. For example, you may earn more stars if you finish faster, use fewer moves, or score higher. You can also earn bonus stars if you complete all four challenges in a day or in a month.

    -

    Badges are special achievements that you can collect by completing Daily Challenges. There are different types of badges, such as bronze, silver, gold, and platinum badges. Each badge has a different design and a different requirement to unlock it. For example, you may have to complete a certain number of challenges, earn a certain number of stars, or play on a certain date. You can see your badge collection at any time by tapping or clicking on the badge icon at the top right corner of the screen.

    -

    Rewards are extra benefits that you can enjoy by completing Daily Challenges. There are different types of rewards, such as themes, card backs, coins, and game boosts. Each reward has a different value and a different way to claim it. For example, you may have to complete a certain number of challenges in a month, earn a certain number of stars in a year, or play on a special occasion. You can see your reward collection at any time by tapping or clicking on the reward icon at the top right corner of the screen.

    -

    Events are special card challenges that you can play on certain days or periods of time in Microsoft Solitaire Collection. They are similar to Daily Challenges, but they have different themes and goals. For example, you may have to play with holiday-themed cards, score as many points as possible in a limited time, or clear as many boards as possible in a row. You can see the current and upcoming events at any time by tapping or clicking on the event icon at the top right corner of the screen.

    -

    When you complete an event challenge, you earn coins and trophies. Coins are used to buy hints and undo moves in case you get stuck. Trophies are used to show off your achievements and rank among other players. You can earn up to three trophies per challenge, depending on how well you perform. For example, you may earn more trophies if you finish faster, use fewer moves, or score higher. You can also earn bonus trophies if you complete all the challenges in an event or in a series of events. You can see your trophy collection at any time by tapping or clicking on the trophy icon at the top right corner of the screen.

    -

    To participate in events, you need to sign in with a Microsoft Account. This will allow you to keep your progress, earn trophies, and compete with other players. You can see your rank and score at any time by tapping or clicking on the leaderboard icon at the top right corner of the screen. You can also see how other players are doing and compare your results with them.

    -

    Tips and tricks to play new solvable card challenges every day and earn Solitaire badges and rewards

    - - Try to play the Daily Challenges and Events regularly to improve your skills and earn more coins, stars, badges, rewards, and trophies. - Try to complete all the challenges in a day or in a month to earn bonus stars and badges. - Try to play the events on special occasions to earn special rewards and trophies. - Try to use your coins wisely to buy hints and undo moves when you need them. - Try to challenge yourself by playing with higher difficulty levels and scoring modes.

    Themes & Card Backs

    -

    If you want to customize your card game, you can choose from different themes and card backs that Microsoft Solitaire Collection offers. Themes are visual styles that change the appearance of the background, the cards, and the interface. Card backs are designs that change the look of the back of the cards.

    -

    You can choose from a variety of themes and card backs, such as Classic, Aquarium, Beach, Dark Mode, Retro, and more. Each theme and card back has a different color scheme, mood, and vibe that can suit your preference and mood. You can also unlock new themes and card backs by completing Daily Challenges and Events.

    -

    To change your theme or card back, you can tap or click on the settings icon at the top right corner of the screen. You can then select the theme or card back option and browse through the available choices. You can preview how each theme or card back looks like before applying it. You can also change your theme or card back anytime you want.

    -

    Tips and tricks to customize your card game with different themes and card backs

    - - Try to experiment with different themes and card backs to find the ones that you like best. - Try to match your theme or card back with the game mode or event that you are playing. - Try to unlock new themes and card backs by completing Daily Challenges and Events. - Try to change your theme or card back occasionally to keep your game fresh and exciting.

    Save Your Progress

    -

    If you want to save your progress, you can sign in with a Microsoft Account in Microsoft Solitaire Collection. This will allow you to keep your player stats, XP, level, achievements, and events across multiple devices. You can also connect with an Xbox Game Pass account to access an ad-free game experience.

    -

    Your player stats include your score, time, moves, wins, losses, streaks, and completion percentage for each game mode. You can see your player stats at any time by tapping or clicking on the stats icon at the top right corner of the screen. You can also see how you compare with other players in terms of skill level.

    -

    Your XP is a measure of your experience and progress in Microsoft Solitaire Collection. You can earn XP by playing games, completing challenges, earning badges, unlocking rewards, and participating in events. You can see your XP at any time by tapping or clicking on the XP icon at the top right corner of the screen. You can also see how much XP you need to reach the next level.

    -

    Your level is a reflection of your skill and achievement in Microsoft Solitaire Collection. You can increase your level by earning XP. You can see your level at any time by tapping or clicking on the level icon at the top right corner of the screen. You can also see what benefits you get for reaching higher levels, such as more coins, themes, card backs, and game boosts.

    -

    Your achievements are milestones that you can accomplish by playing games, completing challenges, earning badges, unlocking rewards, and participating in events. You can see your achievements at any time by tapping or clicking on the achievements icon at the top right corner of the screen. You can also see how many achievements you have completed and how many are left to complete.

    -

    Your events are special card challenges that you can play on certain days or periods of time in Microsoft Solitaire Collection. You can see your events at any time by tapping or clicking on the event icon at the top right corner of the screen. You can also see how many events you have completed and how many are left to complete.

    -

    To sign in with a Microsoft Account, you can tap or click on the sign in icon at the top left corner of the screen. You can then enter your email address and password, or create a new account if you do not have one. You can also sign in with a Facebook account if you prefer. Signing in with a Microsoft Account will allow you to sync your progress across multiple devices, such as your PC, laptop, tablet, or phone. You can also sign out anytime you want.

    -

    To connect with an Xbox Game Pass account, you need to have an active subscription to Xbox Game Pass Ultimate or Xbox Game Pass for PC. This will allow you to access an ad-free game experience in Microsoft Solitaire Collection, as well as other benefits such as cloud gaming, exclusive discounts, and more. To connect with an Xbox Game Pass account, you need to sign in with a Microsoft Account that is linked to your Xbox Game Pass subscription. You can then tap or click on the Xbox Game Pass icon at the top left corner of the screen and follow the instructions.

    -

    Tips and tricks to save your progress and compete with other players

    - - Try to sign in with a Microsoft Account regularly to keep your progress and enjoy more features and benefits. - Try to connect with an Xbox Game Pass account if you have one to enjoy an ad-free game experience and other perks. - Try to improve your player stats, XP, level, achievements, and events by playing games, completing challenges, earning badges, unlocking rewards, and participating in events. - Try to compare your results with other players and see how you rank among them.

    Conclusion

    -

    Microsoft Solitaire Collection is a great way to enjoy the classic card games on your device for free. You can choose from five different game modes: Klondike Solitaire, Spider Solitaire, FreeCell Solitaire, TriPeaks Solitaire, and Pyramid Solitaire. Each game mode has its own rules, challenges, and strategies that will keep you entertained for hours. You can also customize your card game with different themes and card backs, play new solvable card challenges every day, earn badges and rewards, save your progress, and compete with other players. Whether you want to relax with the classics, sharpen your mind, or challenge yourself, Microsoft Solitaire Collection has something for everyone.

    -

    So what are you waiting for? Download Microsoft Solitaire Collection games for free today and start playing!

    -

    FAQs

    - - Q: How do I download Microsoft Solitaire Collection games for free? - A: You can download Microsoft Solitaire Collection games for free from the Microsoft Store or Google Play, depending on your device. - Q: How do I play Microsoft Solitaire Collection games offline? - A: You can play Microsoft Solitaire Collection games offline by turning off your internet connection before launching the app. However, some features and benefits may not be available offline. - Q: How do I get more coins in Microsoft Solitaire Collection? - A: You can get more coins by playing games, completing challenges, earning badges, unlocking rewards, and participating in events. You can also buy more coins with real money if you want. - Q: How do I get rid of ads in Microsoft Solitaire Collection? - A: You can get rid of ads in Microsoft Solitaire Collection by connecting with an Xbox Game Pass account that has an active subscription to Xbox Game Pass Ultimate or Xbox Game Pass for PC. - Q: How do I contact customer support for Microsoft Solitaire Collection? - A: You can contact customer support for Microsoft Solitaire Collection by tapping or clicking on the settings icon at the top right corner of the screen. You can then select the help option and follow the instructions.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Dude Theft Wars Offline games - A Funny Action Game with Sandbox Simulator and Mod Features.md b/spaces/1phancelerku/anime-remove-background/Dude Theft Wars Offline games - A Funny Action Game with Sandbox Simulator and Mod Features.md deleted file mode 100644 index d656a88eadc97185e7ad4bebcaa2ac2d608fe7d7..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Dude Theft Wars Offline games - A Funny Action Game with Sandbox Simulator and Mod Features.md +++ /dev/null @@ -1,112 +0,0 @@ - -

    Dude Theft Wars Offline Games Mod Apk: A Sandbox Game with Unlimited Fun

    -

    If you are looking for a fun and exciting sandbox game that lets you do whatever you want, then you should try Dude Theft Wars. This game is a parody of Grand Theft Auto, where you can explore a huge open world, steal cars, rob banks, shoot guns, and cause chaos. You can also interact with other dudes, make friends or enemies, and have hilarious conversations.

    -

    dude theft wars offline games mod apk


    Download File 🆓 https://jinyurl.com/2uNNNX



    -

    However, if you want to enjoy the game to the fullest, you might want to download the mod apk version of Dude Theft Wars. This version gives you unlimited money and weapons, as well as access to all the features and modes of the game. You can also play the game offline, without any internet connection.

    -

    In this article, we will tell you everything you need to know about Dude Theft Wars offline games mod apk. We will show you how to download and install the mod apk file, how to play the game and use its features, and how to get more money and weapons. We will also give you some tips and tricks to make the most out of your gaming experience. Finally, we will list some pros and cons of playing Dude Theft Wars offline games mod apk, and answer some frequently asked questions.

    -

    Gameplay and Features

    -

    Dude Theft Wars offline games mod apk is a sandbox game that lets you do whatever you want in a huge open world. You can roam around freely, drive cars, bikes, helicopters, tanks, or even UFOs. You can also steal money from ATMs or shops, rob banks or casinos, or hack computers. You can also use guns, grenades, rockets, or even nukes to shoot at anything or anyone. You can also interact with other dudes, who have their own personalities and dialogues. You can make friends or enemies with them, chat with them, prank them, or fight them.

    -

    The game has different modes and missions that you can choose from. You can play in free roam mode, where you can do whatever you want without any objectives or restrictions. You can also play in story mode, where you can follow a storyline and complete various quests. You can also play in online mode, where you can join other players from around the world and compete or cooperate with them.

    -

    The mod apk version of Dude Theft Wars gives you unlimited money and weapons, which means you can buy anything you want from the shops or online market. You can also unlock all the features and modes of the game without any ads or in-app purchases. You can also play the game offline, without any internet connection.

    -

    Tips and Tricks

    -

    If you want to get more money and weapons in Dude Theft Wars offline games mod apk, here are some tips and tricks that you can use:

    - -

    If you want to avoid getting arrested or killed by the police or gangs in Dude Theft Wars offline games mod apk, here are some tips and tricks that you can use:

    -

    dude theft wars mod apk unlimited money
    -dude theft wars open world sandbox simulator mod apk
    -dude theft wars offline games hack apk
    -dude theft wars mod apk latest version
    -dude theft wars offline games free download
    -dude theft wars mod apk android 1
    -dude theft wars open world sandbox simulator beta mod apk
    -dude theft wars offline games cheats
    -dude theft wars mod apk revdl
    -dude theft wars offline games for pc
    -dude theft wars mod apk happymod
    -dude theft wars open world sandbox simulator download
    -dude theft wars offline games gameplay
    -dude theft wars mod apk rexdl
    -dude theft wars offline games online
    -dude theft wars mod apk unlimited health
    -dude theft wars open world sandbox simulator cheats
    -dude theft wars offline games review
    -dude theft wars mod apk all weapons unlocked
    -dude theft wars open world sandbox simulator hack
    -dude theft wars offline games mod menu
    -dude theft wars mod apk no ads
    -dude theft wars open world sandbox simulator free download
    -dude theft wars offline games tips and tricks
    -dude theft wars mod apk unlimited everything
    -dude theft wars open world sandbox simulator for pc
    -dude theft wars offline games best weapons
    -dude theft wars mod apk god mode
    -dude theft wars open world sandbox simulator online
    -dude theft wars offline games new update
    -dude theft wars mod apk all cars unlocked
    -dude theft wars open world sandbox simulator gameplay
    -dude theft wars offline games codes
    -dude theft wars mod apk unlimited ammo
    -dude theft wars open world sandbox simulator mod menu
    -dude theft wars offline games funny moments
    -dude theft wars mod apk all characters unlocked
    -dude theft wars open world sandbox simulator review
    -dude theft wars offline games secrets
    -dude theft wars mod apk mega mod
    -dude theft wars open world sandbox simulator tips and tricks
    -dude theft wars offline games easter eggs
    -dude theft wars mod apk no root
    -dude theft wars open world sandbox simulator best weapons
    -dude theft wars offline games glitches
    -dude theft wars mod apk obb download
    -dude theft wars open world sandbox simulator codes
    -dude theft wars offline games how to get money fast

    - -

    If you want to customize your character and vehicles in Dude Theft Wars offline games mod apk, here are some tips and tricks that you can use:

    - -

    Pros and Cons

    -

    Dude Theft Wars offline games mod apk is a fun and exciting sandbox game that offers unlimited possibilities and freedom. However, it also has some pros and cons that you should consider before playing it. Here are some of them:

    - - - - - - - -
    ProsCons
    - It has a huge open world that you can explore and interact with.- It has some bugs and glitches that might affect the gameplay.
    - It has a lot of features and modes that you can enjoy and choose from.- It has some violent and inappropriate content that might not be suitable for everyone.
    - It has a lot of humor and parody that will make you laugh and have fun.- It has some ads and in-app purchases that might annoy you.
    - It has unlimited money and weapons that will let you buy anything you want and do anything you want.- It might get boring or repetitive after a while if you do not have any goals or challenges.
    - It can be played offline, without any internet connection.- It might not be compatible with some devices or operating systems.
    -

    Conclusion

    -

    Dude Theft Wars offline games mod apk is a sandbox game that lets you do whatever you want in a huge open world. You can explore, drive, steal, rob, shoot, and interact with other dudes. You can also play in different modes and missions, and customize your character and vehicles. You can also enjoy unlimited money and weapons, as well as play offline without any internet connection.

    -

    In conclusion, Dude Theft Wars offline games mod apk is a great game for anyone who loves sandbox games and wants to have unlimited fun. However, it also has some drawbacks that might not appeal to everyone. Therefore, we recommend you to try it out for yourself and see if it suits your taste and preference.

    -

    We hope this article was helpful and informative for you. If you have any questions or comments about Dude Theft Wars offline games mod apk, feel free to share them with us below. We would love to hear from you!

    -

    FAQs

    -

    Here are some frequently asked questions and answers about Dude Theft Wars offline games mod apk:

    -
      -
    1. Q: Is Dude Theft Wars offline games mod apk safe to download and install?
    2. A: Yes, Dude Theft Wars offline games mod apk is safe to download and install, as long as you get it from a trusted and reliable source. However, you should always be careful when downloading and installing any mod apk file, as some of them might contain viruses or malware that could harm your device or data. Therefore, we advise you to scan the file with an antivirus software before installing it, and to backup your data before playing the game. -
    3. Q: How can I update Dude Theft Wars offline games mod apk?
    4. -A: To update Dude Theft Wars offline games mod apk, you need to download and install the latest version of the mod apk file from the same source that you got the previous one. You should also uninstall the old version of the game before installing the new one, to avoid any conflicts or errors. However, you should note that updating the game might erase your progress or data, so you might want to save your game before updating it. -
    5. Q: How can I uninstall Dude Theft Wars offline games mod apk?
    6. -A: To uninstall Dude Theft Wars offline games mod apk, you need to go to your device's settings and find the app manager or applications option. Then, you need to find and select Dude Theft Wars offline games mod apk from the list of apps, and tap on the uninstall button. You should also delete the mod apk file from your device's storage, to free up some space. -
    7. Q: What are some alternatives to Dude Theft Wars offline games mod apk?
    8. -A: If you are looking for some alternatives to Dude Theft Wars offline games mod apk, you might want to check out these other sandbox games that are similar or related to it:

      - -
    9. Q: Where can I get more information about Dude Theft Wars offline games mod apk?
    10. -A: If you want to get more information about Dude Theft Wars offline games mod apk, you can visit the official website of the game developer, Poxel Studios. You can also follow their social media accounts on Facebook, Twitter, Instagram, or YouTube. You can also join their Discord server or Reddit community to chat with other fans and players of the game. -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Enjoy Blocky Graphics and Online PvP Battles with Block Strike APK.md b/spaces/1phancelerku/anime-remove-background/Enjoy Blocky Graphics and Online PvP Battles with Block Strike APK.md deleted file mode 100644 index 1f38c3c05d90564d4d36a34ba718e49c371259fb..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Enjoy Blocky Graphics and Online PvP Battles with Block Strike APK.md +++ /dev/null @@ -1,113 +0,0 @@ - -

    Block Strike APKPure: How to Download and Play the Blocky FPS Shooter

    -

    If you are looking for a fun and addictive online multiplayer first-person shooter game with blocky graphics and competitive gameplay, you might want to check out Block Strike. This game is available on Google Play Store, but you can also download it from APKPure, a third-party app store that offers free and safe Android apps and games. In this article, we will tell you what Block Strike is, how to download it from APKPure, and why you should play it on APKPure. We will also give you some tips and tricks to help you improve your skills and enjoy the game more.

    -

    What is Block Strike?

    -

    Block Strike is a 3D shooter game developed by Rexet Studio, a small indie game studio based in Russia. The game was released in 2015 and has since gained over 50 million downloads and 4.4 stars rating on Google Play Store. The game features over 60 different maps, 15 game modes, hundreds of weapons and skins, and a customizable character. You can play solo or team up with your friends and other players from around the world to compete in various modes such as Deathmatch, Team Deathmatch, Gun Game, Hunger Games, Zombie Survival, Bunny Hop, and more. You can also create your own rooms and invite your friends to join you.

    -

    block strike apkpure


    DOWNLOAD ►►►►► https://jinyurl.com/2uNMy6



    -

    Features of Block Strike

    -

    Some of the features that make Block Strike an exciting and enjoyable game are:

    - -

    How to download Block Strike from APKPure

    -

    If you want to download Block Strike from APKPure, you need to follow these simple steps:

    -
      -
    1. Go to [APKPure.com](^1^) on your browser or download the APKPure app from Google Play Store.
    2. -
    3. Search for "Block Strike" in the search bar or browse the categories to find it.
    4. -
    5. Click on the "Download APK" button or scan the QR code to download the file.
    6. -
    7. Once the download is complete, open the file and install it on your device. You may need to enable "Unknown Sources" in your settings to allow the installation of apps from sources other than Google Play Store.
    8. -
    9. After the installation is done, you can launch the game and enjoy it.
    10. -
    -

    Why play Block Strike on APKPure?

    -

    There are many reasons why you should play Block Strike on APKPure instead of Google Play Store. Here are some of them:

    -

    Benefits of APKPure

    - -

    Tips and tricks for playing Block Strike on APKPure

    -

    To make the most out of your gaming experience, here are some tips and tricks that you can use when playing Block Strike on APKPure:

    - -

    Conclusion

    -

    Block Strike is a fun and addictive online multiplayer first-person shooter game that you can download and play on APKPure. The game has blocky graphics, competitive gameplay, and social interaction. You can enjoy over 60 different maps, 15 game modes, hundreds of weapons and skins, and a customizable character. You can also benefit from APKPure's features, such as no region restrictions, free and safe apps and games, and easy and fast downloads. If you want to improve your skills and enjoy the game more, you can follow our tips and tricks for playing Block Strike on APKPure.

    -

    block strike fps shooter apkpure
    -block strike game download apkpure
    -block strike mod apk apkpure
    -block strike online multiplayer apkpure
    -block strike 3d pixel gun apkpure
    -block strike latest version apkpure
    -block strike apk free download apkpure
    -block strike rexet studio apkpure
    -block strike hack apk apkpure
    -block strike android game apkpure
    -block strike shooting game apkpure
    -block strike unlimited money apkpure
    -block strike offline mode apkpure
    -block strike apk old version apkpure
    -block strike apk pure download
    -block strike action game apkpure
    -block strike battle royale apkpure
    -block strike cheats apk apkpure
    -block strike craft mode apkpure
    -block strike zombie mode apkpure
    -block strike apk mirror apkpure
    -block strike apk mod menu apkpure
    -block strike new update apkpure
    -block strike no ads apkpure
    -block strike original apk apkpure
    -block strike pro apk apkpure
    -block strike pvp multiplayer apkpure
    -block strike skins apk apkpure
    -block strike unlimited gold apkpure
    -block strike weapons mod apkpure
    -download game block strike mod apk pure
    -how to install block strike from apkpure
    -is block strike safe to download from apkpure
    -play block strike on pc with apkpure app player
    -what is the difference between block strike and block strike 2 on apkpure
    -where can i find the best reviews for block strike on apkpure
    -why is block strike not available on google play but only on apkpure
    -how to update block strike using apkpure app store
    -how to get free coins in block strike with apkpure modded apk
    -how to join a clan in block strike through apkpure community forum

    -

    Summary of the article

    -

    In this article, we have covered the following topics:

    - -

    FAQs

    -

    Here are some frequently asked questions about Block Strike and APKPure:

    -
      -
    1. Is Block Strike free to play?
    2. -

      Yes, Block Strike is free to play. However, it contains ads and offers in-app purchases. You can disable the ads by purchasing the premium version of the game or by using an ad blocker app.

      -
    3. Is Block Strike offline or online?
    4. -

      Block Strike is mainly an online game that requires an internet connection to play. However, it also has an offline mode that allows you to play without internet. You can access the offline mode by tapping on the "Offline" button on the main menu.

      -
    5. Is APKPure safe to use?
    6. -

      Yes, APKPure is safe to use. It is a trusted third-party app store that offers free and safe apps and games that are verified by their team. It does not contain any malware, viruses, or spyware.

      -
    7. How to update Block Strike on APKPure?
    8. -

      To update Block Strike on APKPure, you need to follow these steps:

      -
        -
      1. Open the APKPure app or go to [APKPure.com] on your browser.
      2. -
      3. Search for "Block Strike" or
      4. Tap on the "Update" button or scan the QR code to download the latest version of the game.
      5. -
      6. Open the file and install it on your device. You may need to enable "Unknown Sources" in your settings to allow the installation of apps from sources other than Google Play Store.
      7. -
      -
    9. How to contact Block Strike or APKPure support?
    10. -

      If you have any issues, questions, or feedback about Block Strike or APKPure, you can contact their support teams by using the following methods:

      - -
    -

    I hope you found this article helpful and informative. If you did, please share it with your friends and leave a comment below. Thank you for reading and happy gaming!

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/232labs/VToonify/vtoonify/model/stylegan/op_gpu/fused_bias_act.cpp b/spaces/232labs/VToonify/vtoonify/model/stylegan/op_gpu/fused_bias_act.cpp deleted file mode 100644 index 71f612cdbaaca03822eedc002a980d055d2f485c..0000000000000000000000000000000000000000 --- a/spaces/232labs/VToonify/vtoonify/model/stylegan/op_gpu/fused_bias_act.cpp +++ /dev/null @@ -1,32 +0,0 @@ - -#include -#include - -torch::Tensor fused_bias_act_op(const torch::Tensor &input, - const torch::Tensor &bias, - const torch::Tensor &refer, int act, int grad, - float alpha, float scale); - -#define CHECK_CUDA(x) \ - TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor") -#define CHECK_CONTIGUOUS(x) \ - TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") -#define CHECK_INPUT(x) \ - CHECK_CUDA(x); \ - CHECK_CONTIGUOUS(x) - -torch::Tensor fused_bias_act(const torch::Tensor &input, - const torch::Tensor &bias, - const torch::Tensor &refer, int act, int grad, - float alpha, float scale) { - CHECK_INPUT(input); - CHECK_INPUT(bias); - - at::DeviceGuard guard(input.device()); - - return fused_bias_act_op(input, bias, refer, act, grad, alpha, scale); -} - -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { - m.def("fused_bias_act", &fused_bias_act, "fused bias act (CUDA)"); -} \ No newline at end of file diff --git a/spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/configs/glint360k_r18.py b/spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/configs/glint360k_r18.py deleted file mode 100644 index 7a8db34cd547e8e667103c93585296e47a894e97..0000000000000000000000000000000000000000 --- a/spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/configs/glint360k_r18.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 = "r18" -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/7hao/bingo/postcss.config.js b/spaces/7hao/bingo/postcss.config.js deleted file mode 100644 index 33ad091d26d8a9dc95ebdf616e217d985ec215b8..0000000000000000000000000000000000000000 --- a/spaces/7hao/bingo/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} diff --git a/spaces/AI-Hobbyist/Hoyo-RVC/uvr5_pack/lib_v5/nets.py b/spaces/AI-Hobbyist/Hoyo-RVC/uvr5_pack/lib_v5/nets.py deleted file mode 100644 index d4c376ed8715f9e85d71609e348add0a6550a4ba..0000000000000000000000000000000000000000 --- a/spaces/AI-Hobbyist/Hoyo-RVC/uvr5_pack/lib_v5/nets.py +++ /dev/null @@ -1,123 +0,0 @@ -import torch -from torch import nn -import torch.nn.functional as F - -from uvr5_pack.lib_v5 import layers -from uvr5_pack.lib_v5 import spec_utils - - -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, 16) - self.stg1_high_band_net = BaseASPPNet(2, 16) - - self.stg2_bridge = layers.Conv2DBNActiv(18, 8, 1, 1, 0) - self.stg2_full_band_net = BaseASPPNet(8, 16) - - self.stg3_bridge = layers.Conv2DBNActiv(34, 16, 1, 1, 0) - self.stg3_full_band_net = BaseASPPNet(16, 32) - - self.out = nn.Conv2d(32, 2, 1, bias=False) - self.aux1_out = nn.Conv2d(16, 2, 1, bias=False) - self.aux2_out = nn.Conv2d(16, 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/AIConsultant/MusicGen/audiocraft/grids/_base_explorers.py b/spaces/AIConsultant/MusicGen/audiocraft/grids/_base_explorers.py deleted file mode 100644 index d3f26666aa596f7bd2e8695c4f00e7963e978ceb..0000000000000000000000000000000000000000 --- a/spaces/AIConsultant/MusicGen/audiocraft/grids/_base_explorers.py +++ /dev/null @@ -1,80 +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 abc import ABC, abstractmethod -import time -import typing as tp -from dora import Explorer -import treetable as tt - - -def get_sheep_ping(sheep) -> tp.Optional[str]: - """Return the amount of time since the Sheep made some update - to its log. Returns a str using the relevant time unit.""" - ping = None - if sheep.log is not None and sheep.log.exists(): - delta = time.time() - sheep.log.stat().st_mtime - if delta > 3600 * 24: - ping = f'{delta / (3600 * 24):.1f}d' - elif delta > 3600: - ping = f'{delta / (3600):.1f}h' - elif delta > 60: - ping = f'{delta / 60:.1f}m' - else: - ping = f'{delta:.1f}s' - return ping - - -class BaseExplorer(ABC, Explorer): - """Base explorer for AudioCraft grids. - - All task specific solvers are expected to implement the `get_grid_metrics` - method to specify logic about metrics to display for a given task. - - If additional stages are used, the child explorer must define how to handle - these new stages in the `process_history` and `process_sheep` methods. - """ - def stages(self): - return ["train", "valid", "evaluate"] - - def get_grid_meta(self): - """Returns the list of Meta information to display for each XP/job. - """ - return [ - tt.leaf("index", align=">"), - tt.leaf("name", wrap=140), - tt.leaf("state"), - tt.leaf("sig", align=">"), - tt.leaf("sid", align="<"), - ] - - @abstractmethod - def get_grid_metrics(self): - """Return the metrics that should be displayed in the tracking table. - """ - ... - - def process_sheep(self, sheep, history): - train = { - "epoch": len(history), - } - parts = {"train": train} - for metrics in history: - for key, sub in metrics.items(): - part = parts.get(key, {}) - if 'duration' in sub: - # Convert to minutes for readability. - sub['duration'] = sub['duration'] / 60. - part.update(sub) - parts[key] = part - ping = get_sheep_ping(sheep) - if ping is not None: - for name in self.stages(): - if name not in parts: - parts[name] = {} - # Add the ping to each part for convenience. - parts[name]['ping'] = ping - return parts diff --git a/spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/metrics/diagonal_metrics.py b/spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/metrics/diagonal_metrics.py deleted file mode 100644 index ba9807c1a594b38632c4731391e2d4fa3289037b..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/metrics/diagonal_metrics.py +++ /dev/null @@ -1,74 +0,0 @@ -import torch - - -def get_focus_rate(attn, src_padding_mask=None, tgt_padding_mask=None): - ''' - attn: bs x L_t x L_s - ''' - if src_padding_mask is not None: - attn = attn * (1 - src_padding_mask.float())[:, None, :] - - if tgt_padding_mask is not None: - attn = attn * (1 - tgt_padding_mask.float())[:, :, None] - - focus_rate = attn.max(-1).values.sum(-1) - focus_rate = focus_rate / attn.sum(-1).sum(-1) - return focus_rate - - -def get_phone_coverage_rate(attn, src_padding_mask=None, src_seg_mask=None, tgt_padding_mask=None): - ''' - attn: bs x L_t x L_s - ''' - src_mask = attn.new(attn.size(0), attn.size(-1)).bool().fill_(False) - if src_padding_mask is not None: - src_mask |= src_padding_mask - if src_seg_mask is not None: - src_mask |= src_seg_mask - - attn = attn * (1 - src_mask.float())[:, None, :] - if tgt_padding_mask is not None: - attn = attn * (1 - tgt_padding_mask.float())[:, :, None] - - phone_coverage_rate = attn.max(1).values.sum(-1) - # phone_coverage_rate = phone_coverage_rate / attn.sum(-1).sum(-1) - phone_coverage_rate = phone_coverage_rate / (1 - src_mask.float()).sum(-1) - return phone_coverage_rate - - -def get_diagonal_focus_rate(attn, attn_ks, target_len, src_padding_mask=None, tgt_padding_mask=None, - band_mask_factor=5, band_width=50): - ''' - attn: bx x L_t x L_s - attn_ks: shape: tensor with shape [batch_size], input_lens/output_lens - - diagonal: y=k*x (k=attn_ks, x:output, y:input) - 1 0 0 - 0 1 0 - 0 0 1 - y>=k*(x-width) and y<=k*(x+width):1 - else:0 - ''' - # width = min(target_len/band_mask_factor, 50) - width1 = target_len / band_mask_factor - width2 = target_len.new(target_len.size()).fill_(band_width) - width = torch.where(width1 < width2, width1, width2).float() - base = torch.ones(attn.size()).to(attn.device) - zero = torch.zeros(attn.size()).to(attn.device) - x = torch.arange(0, attn.size(1)).to(attn.device)[None, :, None].float() * base - y = torch.arange(0, attn.size(2)).to(attn.device)[None, None, :].float() * base - cond = (y - attn_ks[:, None, None] * x) - cond1 = cond + attn_ks[:, None, None] * width[:, None, None] - cond2 = cond - attn_ks[:, None, None] * width[:, None, None] - mask1 = torch.where(cond1 < 0, zero, base) - mask2 = torch.where(cond2 > 0, zero, base) - mask = mask1 * mask2 - - if src_padding_mask is not None: - attn = attn * (1 - src_padding_mask.float())[:, None, :] - if tgt_padding_mask is not None: - attn = attn * (1 - tgt_padding_mask.float())[:, :, None] - - diagonal_attn = attn * mask - diagonal_focus_rate = diagonal_attn.sum(-1).sum(-1) / attn.sum(-1).sum(-1) - return diagonal_focus_rate, mask diff --git a/spaces/AIZ2H/02-Gradio-Art-From-Text-And-Images/README.md b/spaces/AIZ2H/02-Gradio-Art-From-Text-And-Images/README.md deleted file mode 100644 index 2d1a198ade9ac0edcd9a466326253e58a38c6115..0000000000000000000000000000000000000000 --- a/spaces/AIZ2H/02-Gradio-Art-From-Text-And-Images/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 🎨GradioArtFromTextAndImages -emoji: 📝 -colorFrom: indigo -colorTo: gray -sdk: gradio -sdk_version: 3.3.1 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/ASJMO/freegpt/g4f/models.py b/spaces/ASJMO/freegpt/g4f/models.py deleted file mode 100644 index 37efcfb2a7e870f3ef3093d167efdab299083220..0000000000000000000000000000000000000000 --- a/spaces/ASJMO/freegpt/g4f/models.py +++ /dev/null @@ -1,233 +0,0 @@ -from g4f import Provider - - -class Model: - class model: - name: str - base_provider: str - best_provider: str - - class gpt_35_turbo: - name: str = 'gpt-3.5-turbo' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Wewordle - - class gpt_35_turbo_0613: - name: str = 'gpt-3.5-turbo-0613' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Zeabur - - class gpt_35_turbo_0301: - name: str = 'gpt-3.5-turbo-0301' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Zeabur - - class gpt_35_turbo_16k_0613: - name: str = 'gpt-3.5-turbo-16k-0613' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Zeabur - - class gpt_35_turbo_16k: - name: str = 'gpt-3.5-turbo-16k' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.ChatFree - - class gpt_4_dev: - name: str = 'gpt-4-for-dev' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Phind - - class gpt_4: - name: str = 'gpt-4' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.ChatgptAi - - class gpt_4_0613: - name: str = 'gpt-4-0613' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Lockchat - best_providers: list = [Provider.Bing, Provider.Lockchat] - - class claude_instant_v1_100k: - name: str = 'claude-instant-v1-100k' - base_provider: str = 'anthropic' - best_provider: Provider.Provider = Provider.Vercel - - class claude_instant_v1: - name: str = 'claude-instant-v1' - base_provider: str = 'anthropic' - best_provider: Provider.Provider = Provider.Vercel - - class claude_v1_100k: - name: str = 'claude-v1-100k' - base_provider: str = 'anthropic' - best_provider: Provider.Provider = Provider.Vercel - - class claude_v1: - name: str = 'claude-v1' - base_provider: str = 'anthropic' - best_provider: Provider.Provider = Provider.Vercel - - class alpaca_7b: - name: str = 'alpaca-7b' - base_provider: str = 'replicate' - best_provider: Provider.Provider = Provider.Vercel - - class stablelm_tuned_alpha_7b: - name: str = 'stablelm-tuned-alpha-7b' - base_provider: str = 'replicate' - best_provider: Provider.Provider = Provider.Vercel - - class bloom: - name: str = 'bloom' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class bloomz: - name: str = 'bloomz' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class flan_t5_xxl: - name: str = 'flan-t5-xxl' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class flan_ul2: - name: str = 'flan-ul2' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class gpt_neox_20b: - name: str = 'gpt-neox-20b' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class oasst_sft_4_pythia_12b_epoch_35: - name: str = 'oasst-sft-4-pythia-12b-epoch-3.5' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class santacoder: - name: str = 'santacoder' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.Vercel - - class command_medium_nightly: - name: str = 'command-medium-nightly' - base_provider: str = 'cohere' - best_provider: Provider.Provider = Provider.Vercel - - class command_xlarge_nightly: - name: str = 'command-xlarge-nightly' - base_provider: str = 'cohere' - best_provider: Provider.Provider = Provider.Vercel - - class code_cushman_001: - name: str = 'code-cushman-001' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class code_davinci_002: - name: str = 'code-davinci-002' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class text_ada_001: - name: str = 'text-ada-001' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class text_babbage_001: - name: str = 'text-babbage-001' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class text_curie_001: - name: str = 'text-curie-001' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class text_davinci_002: - name: str = 'text-davinci-002' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class text_davinci_003: - name: str = 'text-davinci-003' - base_provider: str = 'openai' - best_provider: Provider.Provider = Provider.Vercel - - class palm: - name: str = 'palm2' - base_provider: str = 'google' - best_provider: Provider.Provider = Provider.Bard - - class falcon_40b: - name: str = 'falcon-40b' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.H2o - - class falcon_7b: - name: str = 'falcon-7b' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.H2o - - class llama_13b: - name: str = 'llama-13b' - base_provider: str = 'huggingface' - best_provider: Provider.Provider = Provider.H2o - - -class ModelUtils: - convert: dict = { - 'gpt-3.5-turbo': Model.gpt_35_turbo, - 'gpt-3.5-turbo-0613': Model.gpt_35_turbo_0613, - 'gpt-3.5-turbo-0301': Model.gpt_35_turbo_0301, - 'gpt-4': Model.gpt_4, - 'gpt-4-0613': Model.gpt_4_0613, - 'gpt-4-for-dev': Model.gpt_4_dev, - 'gpt-3.5-turbo-16k': Model.gpt_35_turbo_16k, - 'gpt-3.5-turbo-16k-0613': Model.gpt_35_turbo_16k_0613, - - 'claude-instant-v1-100k': Model.claude_instant_v1_100k, - 'claude-v1-100k': Model.claude_v1_100k, - 'claude-instant-v1': Model.claude_instant_v1, - 'claude-v1': Model.claude_v1, - - 'alpaca-7b': Model.alpaca_7b, - 'stablelm-tuned-alpha-7b': Model.stablelm_tuned_alpha_7b, - - 'bloom': Model.bloom, - 'bloomz': Model.bloomz, - - 'flan-t5-xxl': Model.flan_t5_xxl, - 'flan-ul2': Model.flan_ul2, - - 'gpt-neox-20b': Model.gpt_neox_20b, - 'oasst-sft-4-pythia-12b-epoch-3.5': Model.oasst_sft_4_pythia_12b_epoch_35, - 'santacoder': Model.santacoder, - - 'command-medium-nightly': Model.command_medium_nightly, - 'command-xlarge-nightly': Model.command_xlarge_nightly, - - 'code-cushman-001': Model.code_cushman_001, - 'code-davinci-002': Model.code_davinci_002, - - 'text-ada-001': Model.text_ada_001, - 'text-babbage-001': Model.text_babbage_001, - 'text-curie-001': Model.text_curie_001, - 'text-davinci-002': Model.text_davinci_002, - 'text-davinci-003': Model.text_davinci_003, - - 'palm2': Model.palm, - 'palm': Model.palm, - 'google': Model.palm, - 'google-bard': Model.palm, - 'google-palm': Model.palm, - 'bard': Model.palm, - - 'falcon-40b': Model.falcon_40b, - 'falcon-7b': Model.falcon_7b, - 'llama-13b': Model.llama_13b, - } diff --git a/spaces/Abdllh/poetry/README.md b/spaces/Abdllh/poetry/README.md deleted file mode 100644 index 76056b70fef5b18d2a32e30d1fb3ed222779a30d..0000000000000000000000000000000000000000 --- a/spaces/Abdllh/poetry/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Arabic Poetry Generator -emoji: 🐠 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.6 -app_file: app.py -license: cc-by-nc-4.0 -duplicated_from: aaaaaabbbbbbbdddddddduuuuulllll/poetry ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/midas/midas/midas_net_custom.py b/spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/midas/midas/midas_net_custom.py deleted file mode 100644 index 50e4acb5e53d5fabefe3dde16ab49c33c2b7797c..0000000000000000000000000000000000000000 --- a/spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/midas/midas/midas_net_custom.py +++ /dev/null @@ -1,128 +0,0 @@ -"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. -This file contains code that is adapted from -https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py -""" -import torch -import torch.nn as nn - -from .base_model import BaseModel -from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder - - -class MidasNet_small(BaseModel): - """Network for monocular depth estimation. - """ - - def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negative=True, exportable=True, channels_last=False, align_corners=True, - blocks={'expand': True}): - """Init. - - Args: - path (str, optional): Path to saved model. Defaults to None. - features (int, optional): Number of features. Defaults to 256. - backbone (str, optional): Backbone network for encoder. Defaults to resnet50 - """ - print("Loading weights: ", path) - - super(MidasNet_small, self).__init__() - - use_pretrained = False if path else True - - self.channels_last = channels_last - self.blocks = blocks - self.backbone = backbone - - self.groups = 1 - - features1=features - features2=features - features3=features - features4=features - self.expand = False - if "expand" in self.blocks and self.blocks['expand'] == True: - self.expand = True - features1=features - features2=features*2 - features3=features*4 - features4=features*8 - - self.pretrained, self.scratch = _make_encoder(self.backbone, features, use_pretrained, groups=self.groups, expand=self.expand, exportable=exportable) - - self.scratch.activation = nn.ReLU(False) - - self.scratch.refinenet4 = FeatureFusionBlock_custom(features4, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) - self.scratch.refinenet3 = FeatureFusionBlock_custom(features3, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) - self.scratch.refinenet2 = FeatureFusionBlock_custom(features2, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) - self.scratch.refinenet1 = FeatureFusionBlock_custom(features1, self.scratch.activation, deconv=False, bn=False, align_corners=align_corners) - - - self.scratch.output_conv = nn.Sequential( - nn.Conv2d(features, features//2, kernel_size=3, stride=1, padding=1, groups=self.groups), - Interpolate(scale_factor=2, mode="bilinear"), - nn.Conv2d(features//2, 32, kernel_size=3, stride=1, padding=1), - self.scratch.activation, - nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), - nn.ReLU(True) if non_negative else nn.Identity(), - nn.Identity(), - ) - - if path: - self.load(path) - - - def forward(self, x): - """Forward pass. - - Args: - x (tensor): input data (image) - - Returns: - tensor: depth - """ - if self.channels_last==True: - print("self.channels_last = ", self.channels_last) - x.contiguous(memory_format=torch.channels_last) - - - layer_1 = self.pretrained.layer1(x) - layer_2 = self.pretrained.layer2(layer_1) - layer_3 = self.pretrained.layer3(layer_2) - layer_4 = self.pretrained.layer4(layer_3) - - layer_1_rn = self.scratch.layer1_rn(layer_1) - layer_2_rn = self.scratch.layer2_rn(layer_2) - layer_3_rn = self.scratch.layer3_rn(layer_3) - layer_4_rn = self.scratch.layer4_rn(layer_4) - - - path_4 = self.scratch.refinenet4(layer_4_rn) - path_3 = self.scratch.refinenet3(path_4, layer_3_rn) - path_2 = self.scratch.refinenet2(path_3, layer_2_rn) - path_1 = self.scratch.refinenet1(path_2, layer_1_rn) - - out = self.scratch.output_conv(path_1) - - return torch.squeeze(out, dim=1) - - - -def fuse_model(m): - prev_previous_type = nn.Identity() - prev_previous_name = '' - previous_type = nn.Identity() - previous_name = '' - for name, module in m.named_modules(): - if prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d and type(module) == nn.ReLU: - # print("FUSED ", prev_previous_name, previous_name, name) - torch.quantization.fuse_modules(m, [prev_previous_name, previous_name, name], inplace=True) - elif prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d: - # print("FUSED ", prev_previous_name, previous_name) - torch.quantization.fuse_modules(m, [prev_previous_name, previous_name], inplace=True) - # elif previous_type == nn.Conv2d and type(module) == nn.ReLU: - # print("FUSED ", previous_name, name) - # torch.quantization.fuse_modules(m, [previous_name, name], inplace=True) - - prev_previous_type = previous_type - prev_previous_name = previous_name - previous_type = type(module) - previous_name = name \ No newline at end of file diff --git a/spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/openpose/__init__.py b/spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/openpose/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/ResolveHeight.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/ResolveHeight.js deleted file mode 100644 index 63cc461f42a6bb7c31b18f4cb5074cd11f5b4a3d..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/ResolveHeight.js +++ /dev/null @@ -1,14 +0,0 @@ -var ResolveHeight = function (height) { - var minHeight = Math.max(this.childrenHeight, this.minHeight); - if (height === undefined) { - height = minHeight; - } else { - if (minHeight > height) { - // Warning - } - } - - return height; -} - -export default ResolveHeight; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/circlemaskimage/CircleMaskImage.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/circlemaskimage/CircleMaskImage.js deleted file mode 100644 index dafd452a231491a4edd777ee789ddbd6b6d04f5c..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/circlemaskimage/CircleMaskImage.js +++ /dev/null @@ -1,2 +0,0 @@ -import CircleMaskImage from '../../../plugins/circlemaskimage.js'; -export default CircleMaskImage; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/pan/Factory.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/pan/Factory.js deleted file mode 100644 index 20c20ff5432613ebca1006ed054e31f1f20bc045..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/pan/Factory.js +++ /dev/null @@ -1,16 +0,0 @@ -import Pan from './Pan.js'; -import ObjectFactory from '../ObjectFactory.js'; -import IsGameObject from '../../../plugins/utils/system/IsGameObject.js'; -import SetValue from '../../../plugins/utils/object/SetValue.js'; - -ObjectFactory.register('pan', function (gameObject, config) { - if (!IsGameObject(gameObject)) { - config = gameObject; - gameObject = this.scene; - } - return new Pan(gameObject, config); -}); - -SetValue(window, 'RexPlugins.UI.Pan', Pan); - -export default Pan; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/scrollablepanel/Factory.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/scrollablepanel/Factory.d.ts deleted file mode 100644 index 3e5d06a614ab0ef70037b26a92dde54c361c5fc1..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/scrollablepanel/Factory.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import ScrollablePanel from './ScrollablePanel'; - -export default function ( - config?: ScrollablePanel.IConfig -): ScrollablePanel; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/statesroundrectangle/methods/ExtractStyle.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/statesroundrectangle/methods/ExtractStyle.js deleted file mode 100644 index 1e256b80eebdcf15913ec2e1dba69347012a2b28..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/statesroundrectangle/methods/ExtractStyle.js +++ /dev/null @@ -1,18 +0,0 @@ -import ExtractByPrefix from '../../../../plugins/utils/object/ExtractByPrefix.js'; - -var ExtractStyle = function (config, prefix, propertiesMap) { - var result = ExtractByPrefix(config, prefix); - - if (propertiesMap) { - for (var name in result) { - if (propertiesMap.hasOwnProperty(name)) { - result[propertiesMap[name]] = result[name]; - delete result[name]; - } - } - } - - return result; -} - -export default ExtractStyle \ No newline at end of file diff --git a/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/README.md b/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/README.md deleted file mode 100644 index 6fd7d547a3e31617d4a3f94775fe2d7b6ce0e23b..0000000000000000000000000000000000000000 --- a/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: League of Legends Yuumi Text to Speech -sdk: gradio -emoji: 🔥 -colorFrom: blue -colorTo: yellow -app_file: app.py -pinned: false -duplicated_from: kiramayatu/Vits-Hana ---- - -# League of Legends Yuumi Text to Speech Demo - -League of Legends Yuumi Text to Speech model trained with Yuumi's English in-game audio. - -## 👍Give original author stars & likes if you liked the project - -https://github.com/Plachtaa/VITS-fast-fine-tuning - -https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer - -## ❓How to fine-tune your own model - -Follow the directions in this repo: https://github.com/Plachtaa/VITS-fast-fine-tuning - -## ⚠Use of the model should respect https://www.riotgames.com/en/legal - -## ⚠Disclaimer: Not legally responsible for anything the model generates \ No newline at end of file diff --git a/spaces/Amrrs/DragGan-Inversion/torch_utils/ops/bias_act.h b/spaces/Amrrs/DragGan-Inversion/torch_utils/ops/bias_act.h deleted file mode 100644 index 60b81c6058d54638a6d74a13046fa388442d767d..0000000000000000000000000000000000000000 --- a/spaces/Amrrs/DragGan-Inversion/torch_utils/ops/bias_act.h +++ /dev/null @@ -1,38 +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. - -//------------------------------------------------------------------------ -// CUDA kernel parameters. - -struct bias_act_kernel_params -{ - const void* x; // [sizeX] - const void* b; // [sizeB] or NULL - const void* xref; // [sizeX] or NULL - const void* yref; // [sizeX] or NULL - const void* dy; // [sizeX] or NULL - void* y; // [sizeX] - - int grad; - int act; - float alpha; - float gain; - float clamp; - - int sizeX; - int sizeB; - int stepB; - int loopX; -}; - -//------------------------------------------------------------------------ -// CUDA kernel selection. - -template void* choose_bias_act_kernel(const bias_act_kernel_params& p); - -//------------------------------------------------------------------------ diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/alt_diffusion/__init__.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/alt_diffusion/__init__.py deleted file mode 100644 index 03c9f5ebc63ec1fdbf57f6bd11346250a7fa4878..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/alt_diffusion/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -from dataclasses import dataclass -from typing import List, Optional, Union - -import numpy as np -import PIL -from PIL import Image - -from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available - - -@dataclass -# Copied from diffusers.pipelines.stable_diffusion.__init__.StableDiffusionPipelineOutput with Stable->Alt -class AltDiffusionPipelineOutput(BaseOutput): - """ - Output class for Alt Diffusion pipelines. - - Args: - images (`List[PIL.Image.Image]` or `np.ndarray`) - List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width, - num_channels)`. - nsfw_content_detected (`List[bool]`) - List indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or - `None` if safety checking could not be performed. - """ - - images: Union[List[PIL.Image.Image], np.ndarray] - nsfw_content_detected: Optional[List[bool]] - - -try: - if not (is_transformers_available() and is_torch_available()): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline -else: - from .modeling_roberta_series import RobertaSeriesModelWithTransformation - from .pipeline_alt_diffusion import AltDiffusionPipeline - from .pipeline_alt_diffusion_img2img import AltDiffusionImg2ImgPipeline diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py deleted file mode 100644 index e7fe39b9c86540c6baa2620e40bb79c6730f0d96..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +++ /dev/null @@ -1,713 +0,0 @@ -# Copyright 2023 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. - -import contextlib -import inspect -import warnings -from typing import Any, Callable, Dict, List, Optional, Union - -import numpy as np -import PIL -import torch -from packaging import version -from transformers import CLIPTextModel, CLIPTokenizer, DPTFeatureExtractor, DPTForDepthEstimation - -from ...configuration_utils import FrozenDict -from ...image_processor import VaeImageProcessor -from ...loaders import LoraLoaderMixin, TextualInversionLoaderMixin -from ...models import AutoencoderKL, UNet2DConditionModel -from ...schedulers import KarrasDiffusionSchedulers -from ...utils import PIL_INTERPOLATION, deprecate, logging, randn_tensor -from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput - - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - - -# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.preprocess -def preprocess(image): - warnings.warn( - "The preprocess method is deprecated and will be removed in a future version. Please" - " use VaeImageProcessor.preprocess instead", - FutureWarning, - ) - if isinstance(image, torch.Tensor): - return image - elif isinstance(image, PIL.Image.Image): - image = [image] - - if isinstance(image[0], PIL.Image.Image): - w, h = image[0].size - w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 - - image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image] - image = np.concatenate(image, axis=0) - image = np.array(image).astype(np.float32) / 255.0 - image = image.transpose(0, 3, 1, 2) - image = 2.0 * image - 1.0 - image = torch.from_numpy(image) - elif isinstance(image[0], torch.Tensor): - image = torch.cat(image, dim=0) - return image - - -class StableDiffusionDepth2ImgPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin): - r""" - Pipeline for text-guided depth-based image-to-image generation using Stable Diffusion. - - This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods - implemented for all pipelines (downloading, saving, running on a particular device, etc.). - - The pipeline also inherits the following loading methods: - - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings - - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights - - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights - - Args: - vae ([`AutoencoderKL`]): - Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. - text_encoder ([`~transformers.CLIPTextModel`]): - Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). - tokenizer ([`~transformers.CLIPTokenizer`]): - A `CLIPTokenizer` to tokenize text. - unet ([`UNet2DConditionModel`]): - A `UNet2DConditionModel` to denoise the encoded image latents. - scheduler ([`SchedulerMixin`]): - A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of - [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. - """ - - def __init__( - self, - vae: AutoencoderKL, - text_encoder: CLIPTextModel, - tokenizer: CLIPTokenizer, - unet: UNet2DConditionModel, - scheduler: KarrasDiffusionSchedulers, - depth_estimator: DPTForDepthEstimation, - feature_extractor: DPTFeatureExtractor, - ): - super().__init__() - - is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( - version.parse(unet.config._diffusers_version).base_version - ) < version.parse("0.9.0.dev0") - is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 - if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: - deprecation_message = ( - "The configuration file of the unet has set the default `sample_size` to smaller than" - " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the" - " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" - " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" - " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" - " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" - " in the config might lead to incorrect results in future versions. If you have downloaded this" - " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" - " the `unet/config.json` file" - ) - deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(unet.config) - new_config["sample_size"] = 64 - unet._internal_dict = FrozenDict(new_config) - - self.register_modules( - vae=vae, - text_encoder=text_encoder, - tokenizer=tokenizer, - unet=unet, - scheduler=scheduler, - depth_estimator=depth_estimator, - feature_extractor=feature_extractor, - ) - self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) - self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt - def _encode_prompt( - self, - prompt, - device, - num_images_per_prompt, - do_classifier_free_guidance, - negative_prompt=None, - prompt_embeds: Optional[torch.FloatTensor] = None, - negative_prompt_embeds: Optional[torch.FloatTensor] = None, - lora_scale: Optional[float] = None, - ): - r""" - Encodes the prompt into text encoder hidden states. - - Args: - prompt (`str` or `List[str]`, *optional*): - prompt to be encoded - device: (`torch.device`): - torch device - num_images_per_prompt (`int`): - number of images that should be generated per prompt - do_classifier_free_guidance (`bool`): - whether to use classifier free guidance or not - negative_prompt (`str` or `List[str]`, *optional*): - The prompt or prompts not to guide the image generation. If not defined, one has to pass - `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is - less than `1`). - prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not - provided, text embeddings will be generated from `prompt` input argument. - negative_prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt - weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input - argument. - lora_scale (`float`, *optional*): - A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. - """ - # set lora scale so that monkey patched LoRA - # function of text encoder can correctly access it - if lora_scale is not None and isinstance(self, LoraLoaderMixin): - self._lora_scale = lora_scale - - if prompt is not None and isinstance(prompt, str): - batch_size = 1 - elif prompt is not None and isinstance(prompt, list): - batch_size = len(prompt) - else: - batch_size = prompt_embeds.shape[0] - - if prompt_embeds is None: - # textual inversion: procecss multi-vector tokens if necessary - if isinstance(self, TextualInversionLoaderMixin): - prompt = self.maybe_convert_prompt(prompt, self.tokenizer) - - text_inputs = self.tokenizer( - prompt, - padding="max_length", - max_length=self.tokenizer.model_max_length, - truncation=True, - return_tensors="pt", - ) - text_input_ids = text_inputs.input_ids - untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids - - if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( - text_input_ids, untruncated_ids - ): - removed_text = self.tokenizer.batch_decode( - untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] - ) - logger.warning( - "The following part of your input was truncated because CLIP can only handle sequences up to" - f" {self.tokenizer.model_max_length} tokens: {removed_text}" - ) - - if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: - attention_mask = text_inputs.attention_mask.to(device) - else: - attention_mask = None - - prompt_embeds = self.text_encoder( - text_input_ids.to(device), - attention_mask=attention_mask, - ) - prompt_embeds = prompt_embeds[0] - - prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) - - bs_embed, seq_len, _ = prompt_embeds.shape - # duplicate text embeddings for each generation per prompt, using mps friendly method - prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) - prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) - - # get unconditional embeddings for classifier free guidance - if do_classifier_free_guidance and negative_prompt_embeds is None: - uncond_tokens: List[str] - if negative_prompt is None: - uncond_tokens = [""] * batch_size - elif prompt is not None and type(prompt) is not type(negative_prompt): - raise TypeError( - f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" - f" {type(prompt)}." - ) - elif isinstance(negative_prompt, str): - uncond_tokens = [negative_prompt] - elif batch_size != len(negative_prompt): - raise ValueError( - f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" - f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" - " the batch size of `prompt`." - ) - else: - uncond_tokens = negative_prompt - - # textual inversion: procecss multi-vector tokens if necessary - if isinstance(self, TextualInversionLoaderMixin): - uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer) - - max_length = prompt_embeds.shape[1] - uncond_input = self.tokenizer( - uncond_tokens, - padding="max_length", - max_length=max_length, - truncation=True, - return_tensors="pt", - ) - - if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: - attention_mask = uncond_input.attention_mask.to(device) - else: - attention_mask = None - - negative_prompt_embeds = self.text_encoder( - uncond_input.input_ids.to(device), - attention_mask=attention_mask, - ) - negative_prompt_embeds = negative_prompt_embeds[0] - - if do_classifier_free_guidance: - # duplicate unconditional embeddings for each generation per prompt, using mps friendly method - seq_len = negative_prompt_embeds.shape[1] - - negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) - - negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) - negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) - - # For classifier free guidance, we need to do two forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing two forward passes - prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) - - return prompt_embeds - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker - def run_safety_checker(self, image, device, dtype): - if self.safety_checker is None: - has_nsfw_concept = None - else: - if torch.is_tensor(image): - feature_extractor_input = self.image_processor.postprocess(image, output_type="pil") - else: - feature_extractor_input = self.image_processor.numpy_to_pil(image) - safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device) - image, has_nsfw_concept = self.safety_checker( - images=image, clip_input=safety_checker_input.pixel_values.to(dtype) - ) - return image, has_nsfw_concept - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents - def decode_latents(self, latents): - warnings.warn( - "The decode_latents method is deprecated and will be removed in a future version. Please" - " use VaeImageProcessor instead", - FutureWarning, - ) - latents = 1 / self.vae.config.scaling_factor * latents - image = self.vae.decode(latents, return_dict=False)[0] - image = (image / 2 + 0.5).clamp(0, 1) - # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 - image = image.cpu().permute(0, 2, 3, 1).float().numpy() - return image - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs - def prepare_extra_step_kwargs(self, generator, eta): - # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature - # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. - # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 - # and should be between [0, 1] - - accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) - extra_step_kwargs = {} - if accepts_eta: - extra_step_kwargs["eta"] = eta - - # check if the scheduler accepts generator - accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) - if accepts_generator: - extra_step_kwargs["generator"] = generator - return extra_step_kwargs - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.check_inputs - def check_inputs( - self, prompt, strength, callback_steps, negative_prompt=None, prompt_embeds=None, negative_prompt_embeds=None - ): - if strength < 0 or strength > 1: - raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}") - - if (callback_steps is None) or ( - callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) - ): - raise ValueError( - f"`callback_steps` has to be a positive integer but is {callback_steps} of type" - f" {type(callback_steps)}." - ) - - if prompt is not None and prompt_embeds is not None: - raise ValueError( - f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" - " only forward one of the two." - ) - elif prompt is None and prompt_embeds is None: - raise ValueError( - "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." - ) - elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): - raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") - - if negative_prompt is not None and negative_prompt_embeds is not None: - raise ValueError( - f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" - f" {negative_prompt_embeds}. Please make sure to only forward one of the two." - ) - - if prompt_embeds is not None and negative_prompt_embeds is not None: - if prompt_embeds.shape != negative_prompt_embeds.shape: - raise ValueError( - "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" - f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" - f" {negative_prompt_embeds.shape}." - ) - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps - def get_timesteps(self, num_inference_steps, strength, device): - # get the original timestep using init_timestep - init_timestep = min(int(num_inference_steps * strength), num_inference_steps) - - t_start = max(num_inference_steps - init_timestep, 0) - timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] - - return timesteps, num_inference_steps - t_start - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.prepare_latents - def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None): - if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)): - raise ValueError( - f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}" - ) - - image = image.to(device=device, dtype=dtype) - - batch_size = batch_size * num_images_per_prompt - - if image.shape[1] == 4: - init_latents = image - - else: - if isinstance(generator, list) and len(generator) != batch_size: - raise ValueError( - f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" - f" size of {batch_size}. Make sure the batch size matches the length of the generators." - ) - - elif isinstance(generator, list): - init_latents = [ - self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size) - ] - init_latents = torch.cat(init_latents, dim=0) - else: - init_latents = self.vae.encode(image).latent_dist.sample(generator) - - init_latents = self.vae.config.scaling_factor * init_latents - - if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0: - # expand init_latents for batch_size - deprecation_message = ( - f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial" - " images (`image`). Initial images are now duplicating to match the number of text prompts. Note" - " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update" - " your script to pass as many initial images as text prompts to suppress this warning." - ) - deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False) - additional_image_per_prompt = batch_size // init_latents.shape[0] - init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0) - elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0: - raise ValueError( - f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts." - ) - else: - init_latents = torch.cat([init_latents], dim=0) - - shape = init_latents.shape - noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) - - # get latents - init_latents = self.scheduler.add_noise(init_latents, noise, timestep) - latents = init_latents - - return latents - - def prepare_depth_map(self, image, depth_map, batch_size, do_classifier_free_guidance, dtype, device): - if isinstance(image, PIL.Image.Image): - image = [image] - else: - image = list(image) - - if isinstance(image[0], PIL.Image.Image): - width, height = image[0].size - elif isinstance(image[0], np.ndarray): - width, height = image[0].shape[:-1] - else: - height, width = image[0].shape[-2:] - - if depth_map is None: - pixel_values = self.feature_extractor(images=image, return_tensors="pt").pixel_values - pixel_values = pixel_values.to(device=device) - # The DPT-Hybrid model uses batch-norm layers which are not compatible with fp16. - # So we use `torch.autocast` here for half precision inference. - context_manger = torch.autocast("cuda", dtype=dtype) if device.type == "cuda" else contextlib.nullcontext() - with context_manger: - depth_map = self.depth_estimator(pixel_values).predicted_depth - else: - depth_map = depth_map.to(device=device, dtype=dtype) - - depth_map = torch.nn.functional.interpolate( - depth_map.unsqueeze(1), - size=(height // self.vae_scale_factor, width // self.vae_scale_factor), - mode="bicubic", - align_corners=False, - ) - - depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True) - depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True) - depth_map = 2.0 * (depth_map - depth_min) / (depth_max - depth_min) - 1.0 - depth_map = depth_map.to(dtype) - - # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method - if depth_map.shape[0] < batch_size: - repeat_by = batch_size // depth_map.shape[0] - depth_map = depth_map.repeat(repeat_by, 1, 1, 1) - - depth_map = torch.cat([depth_map] * 2) if do_classifier_free_guidance else depth_map - return depth_map - - @torch.no_grad() - def __call__( - self, - prompt: Union[str, List[str]] = None, - image: Union[ - torch.FloatTensor, - PIL.Image.Image, - np.ndarray, - List[torch.FloatTensor], - List[PIL.Image.Image], - List[np.ndarray], - ] = None, - depth_map: Optional[torch.FloatTensor] = None, - strength: float = 0.8, - num_inference_steps: Optional[int] = 50, - guidance_scale: Optional[float] = 7.5, - negative_prompt: Optional[Union[str, List[str]]] = None, - num_images_per_prompt: Optional[int] = 1, - eta: Optional[float] = 0.0, - generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, - prompt_embeds: Optional[torch.FloatTensor] = None, - negative_prompt_embeds: Optional[torch.FloatTensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, - callback_steps: int = 1, - cross_attention_kwargs: Optional[Dict[str, Any]] = None, - ): - r""" - The call function to the pipeline for generation. - - Args: - prompt (`str` or `List[str]`, *optional*): - The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. - image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`): - `Image` or tensor representing an image batch to be used as the starting point. Can accept image - latents as `image` only if `depth_map` is not `None`. - depth_map (`torch.FloatTensor`, *optional*): - Depth prediction to be used as additional conditioning for the image generation process. If not - defined, it automatically predicts the depth with `self.depth_estimator`. - strength (`float`, *optional*, defaults to 0.8): - Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a - starting point and more noise is added the higher the `strength`. The number of denoising steps depends - on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising - process runs for the full number of iterations specified in `num_inference_steps`. A value of 1 - essentially ignores `image`. - num_inference_steps (`int`, *optional*, defaults to 50): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. This parameter is modulated by `strength`. - guidance_scale (`float`, *optional*, defaults to 7.5): - A higher guidance scale value encourages the model to generate images closely linked to the text - `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. - negative_prompt (`str` or `List[str]`, *optional*): - The prompt or prompts to guide what to not include in image generation. If not defined, you need to - pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - eta (`float`, *optional*, defaults to 0.0): - Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies - to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. - generator (`torch.Generator` or `List[torch.Generator]`, *optional*): - A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make - generation deterministic. - prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not - provided, text embeddings are generated from the `prompt` input argument. - negative_prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If - not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generated image. Choose between `PIL.Image` or `np.array`. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a - plain tuple. - callback (`Callable`, *optional*): - A function that calls every `callback_steps` steps during inference. The function is called with the - following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. - callback_steps (`int`, *optional*, defaults to 1): - The frequency at which the `callback` function is called. If not specified, the callback is called at - every step. - cross_attention_kwargs (`dict`, *optional*): - A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in - [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py). - - Examples: - - ```py - >>> import torch - >>> import requests - >>> from PIL import Image - - >>> from diffusers import StableDiffusionDepth2ImgPipeline - - >>> pipe = StableDiffusionDepth2ImgPipeline.from_pretrained( - ... "stabilityai/stable-diffusion-2-depth", - ... torch_dtype=torch.float16, - ... ) - >>> pipe.to("cuda") - - - >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" - >>> init_image = Image.open(requests.get(url, stream=True).raw) - >>> prompt = "two tigers" - >>> n_propmt = "bad, deformed, ugly, bad anotomy" - >>> image = pipe(prompt=prompt, image=init_image, negative_prompt=n_propmt, strength=0.7).images[0] - ``` - - Returns: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: - If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, - otherwise a `tuple` is returned where the first element is a list with the generated images. - """ - # 1. Check inputs - self.check_inputs( - prompt, - strength, - callback_steps, - negative_prompt=negative_prompt, - prompt_embeds=prompt_embeds, - negative_prompt_embeds=negative_prompt_embeds, - ) - - if image is None: - raise ValueError("`image` input cannot be undefined.") - - # 2. Define call parameters - if prompt is not None and isinstance(prompt, str): - batch_size = 1 - elif prompt is not None and isinstance(prompt, list): - batch_size = len(prompt) - else: - batch_size = prompt_embeds.shape[0] - - device = self._execution_device - # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) - # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` - # corresponds to doing no classifier free guidance. - do_classifier_free_guidance = guidance_scale > 1.0 - - # 3. Encode input prompt - text_encoder_lora_scale = ( - cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None - ) - prompt_embeds = self._encode_prompt( - prompt, - device, - num_images_per_prompt, - do_classifier_free_guidance, - negative_prompt, - prompt_embeds=prompt_embeds, - negative_prompt_embeds=negative_prompt_embeds, - lora_scale=text_encoder_lora_scale, - ) - - # 4. Prepare depth mask - depth_mask = self.prepare_depth_map( - image, - depth_map, - batch_size * num_images_per_prompt, - do_classifier_free_guidance, - prompt_embeds.dtype, - device, - ) - - # 5. Preprocess image - image = self.image_processor.preprocess(image) - - # 6. Set timesteps - self.scheduler.set_timesteps(num_inference_steps, device=device) - timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device) - latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) - - # 7. Prepare latent variables - latents = self.prepare_latents( - image, latent_timestep, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator - ) - - # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline - extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) - - # 9. Denoising loop - num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order - with self.progress_bar(total=num_inference_steps) as progress_bar: - for i, t in enumerate(timesteps): - # expand the latents if we are doing classifier free guidance - latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents - latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) - latent_model_input = torch.cat([latent_model_input, depth_mask], dim=1) - - # predict the noise residual - noise_pred = self.unet( - latent_model_input, - t, - encoder_hidden_states=prompt_embeds, - cross_attention_kwargs=cross_attention_kwargs, - return_dict=False, - )[0] - - # perform guidance - if do_classifier_free_guidance: - noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) - noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) - - # compute the previous noisy sample x_t -> x_t-1 - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] - - # call the callback, if provided - if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): - progress_bar.update() - if callback is not None and i % callback_steps == 0: - callback(i, t, latents) - - if not output_type == "latent": - image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] - else: - image = latents - - image = self.image_processor.postprocess(image, output_type=output_type) - - if not return_dict: - return (image,) - - return ImagePipelineOutput(images=image) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/fpg/README.md b/spaces/Andy1621/uniformer_image_detection/configs/fpg/README.md deleted file mode 100644 index 89f5adb5fb41809bfcddeca80b7fe730d70e4838..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/fpg/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Feature Pyramid Grids - -## Introduction - -```latex -@article{chen2020feature, - title={Feature pyramid grids}, - author={Chen, Kai and Cao, Yuhang and Loy, Chen Change and Lin, Dahua and Feichtenhofer, Christoph}, - journal={arXiv preprint arXiv:2004.03580}, - year={2020} -} -``` - -## Results and Models - -We benchmark the new training schedule (crop training, large batch, unfrozen BN, 50 epochs) introduced in NAS-FPN. -All backbones are Resnet-50 in pytorch style. - -| Method | Neck | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | -|:------------:|:-----------:|:-------:|:--------:|:--------------:|:------:|:-------:|:-------:|:--------:| -| Faster R-CNN | FPG | 50e | 20.0 | - | 42.2 | - |[config](https://github.com/open-mmlab/mmdetection/tree/master/configs/fpg/faster_rcnn_r50_fpg_crop640_50e_coco.py) | -| Faster R-CNN | FPG-chn128 | 50e | 11.9 | - | 41.2 | - |[config](https://github.com/open-mmlab/mmdetection/tree/master/configs/fpg/faster_rcnn_r50_fpg-chn128_crop640_50e_coco.py) | -| Mask R-CNN | FPG | 50e | 23.2 | - | 42.7 | 37.8 |[config](https://github.com/open-mmlab/mmdetection/tree/master/configs/fpg/mask_rcnn_r50_fpg_crop640_50e_coco.py) | -| Mask R-CNN | FPG-chn128 | 50e | 15.3 | - | 41.7 | 36.9 |[config](https://github.com/open-mmlab/mmdetection/tree/master/configs/fpg/mask_rcnn_r50_fpg-chn128_crop640_50e_coco.py) | -| RetinaNet | FPG | 50e | 20.8 | - | 40.5 | - |[config](https://github.com/open-mmlab/mmdetection/tree/master/configs/fpg/retinanet_r50_fpg_crop640_50e_coco.py) | -| RetinaNet | FPG-chn128 | 50e | | - | | - |[config](https://github.com/open-mmlab/mmdetection/tree/master/configs/fpg/retinanet_r50_fpg-chn128_crop640_50e_coco.py) | - -**Note**: Chn128 means to decrease the number of channels of features and convs from 256 (default) to 128 in -Neck and BBox Head, which can greatly decrease memory consumption without sacrificing much precision. diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/cnn/vgg.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/cnn/vgg.py deleted file mode 100644 index 8778b649561a45a9652b1a15a26c2d171e58f3e1..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/cnn/vgg.py +++ /dev/null @@ -1,175 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import logging - -import torch.nn as nn - -from .utils import constant_init, kaiming_init, normal_init - - -def conv3x3(in_planes, out_planes, dilation=1): - """3x3 convolution with padding.""" - return nn.Conv2d( - in_planes, - out_planes, - kernel_size=3, - padding=dilation, - dilation=dilation) - - -def make_vgg_layer(inplanes, - planes, - num_blocks, - dilation=1, - with_bn=False, - ceil_mode=False): - layers = [] - for _ in range(num_blocks): - layers.append(conv3x3(inplanes, planes, dilation)) - if with_bn: - layers.append(nn.BatchNorm2d(planes)) - layers.append(nn.ReLU(inplace=True)) - inplanes = planes - layers.append(nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=ceil_mode)) - - return layers - - -class VGG(nn.Module): - """VGG backbone. - - Args: - depth (int): Depth of vgg, from {11, 13, 16, 19}. - with_bn (bool): Use BatchNorm or not. - num_classes (int): number of classes for classification. - num_stages (int): VGG stages, normally 5. - dilations (Sequence[int]): Dilation of each stage. - out_indices (Sequence[int]): Output from which stages. - frozen_stages (int): Stages to be frozen (all param fixed). -1 means - not freezing any parameters. - bn_eval (bool): Whether to set BN layers as eval mode, namely, freeze - running stats (mean and var). - bn_frozen (bool): Whether to freeze weight and bias of BN layers. - """ - - arch_settings = { - 11: (1, 1, 2, 2, 2), - 13: (2, 2, 2, 2, 2), - 16: (2, 2, 3, 3, 3), - 19: (2, 2, 4, 4, 4) - } - - def __init__(self, - depth, - with_bn=False, - num_classes=-1, - num_stages=5, - dilations=(1, 1, 1, 1, 1), - out_indices=(0, 1, 2, 3, 4), - frozen_stages=-1, - bn_eval=True, - bn_frozen=False, - ceil_mode=False, - with_last_pool=True): - super(VGG, self).__init__() - if depth not in self.arch_settings: - raise KeyError(f'invalid depth {depth} for vgg') - assert num_stages >= 1 and num_stages <= 5 - stage_blocks = self.arch_settings[depth] - self.stage_blocks = stage_blocks[:num_stages] - assert len(dilations) == num_stages - assert max(out_indices) <= num_stages - - self.num_classes = num_classes - self.out_indices = out_indices - self.frozen_stages = frozen_stages - self.bn_eval = bn_eval - self.bn_frozen = bn_frozen - - self.inplanes = 3 - start_idx = 0 - vgg_layers = [] - self.range_sub_modules = [] - for i, num_blocks in enumerate(self.stage_blocks): - num_modules = num_blocks * (2 + with_bn) + 1 - end_idx = start_idx + num_modules - dilation = dilations[i] - planes = 64 * 2**i if i < 4 else 512 - vgg_layer = make_vgg_layer( - self.inplanes, - planes, - num_blocks, - dilation=dilation, - with_bn=with_bn, - ceil_mode=ceil_mode) - vgg_layers.extend(vgg_layer) - self.inplanes = planes - self.range_sub_modules.append([start_idx, end_idx]) - start_idx = end_idx - if not with_last_pool: - vgg_layers.pop(-1) - self.range_sub_modules[-1][1] -= 1 - self.module_name = 'features' - self.add_module(self.module_name, nn.Sequential(*vgg_layers)) - - if self.num_classes > 0: - self.classifier = nn.Sequential( - nn.Linear(512 * 7 * 7, 4096), - nn.ReLU(True), - nn.Dropout(), - nn.Linear(4096, 4096), - nn.ReLU(True), - nn.Dropout(), - nn.Linear(4096, num_classes), - ) - - def init_weights(self, pretrained=None): - if isinstance(pretrained, str): - logger = logging.getLogger() - from ..runner import load_checkpoint - load_checkpoint(self, pretrained, strict=False, logger=logger) - elif pretrained is None: - for m in self.modules(): - if isinstance(m, nn.Conv2d): - kaiming_init(m) - elif isinstance(m, nn.BatchNorm2d): - constant_init(m, 1) - elif isinstance(m, nn.Linear): - normal_init(m, std=0.01) - else: - raise TypeError('pretrained must be a str or None') - - def forward(self, x): - outs = [] - vgg_layers = getattr(self, self.module_name) - for i in range(len(self.stage_blocks)): - for j in range(*self.range_sub_modules[i]): - vgg_layer = vgg_layers[j] - x = vgg_layer(x) - if i in self.out_indices: - outs.append(x) - if self.num_classes > 0: - x = x.view(x.size(0), -1) - x = self.classifier(x) - outs.append(x) - if len(outs) == 1: - return outs[0] - else: - return tuple(outs) - - def train(self, mode=True): - super(VGG, self).train(mode) - if self.bn_eval: - for m in self.modules(): - if isinstance(m, nn.BatchNorm2d): - m.eval() - if self.bn_frozen: - for params in m.parameters(): - params.requires_grad = False - vgg_layers = getattr(self, self.module_name) - if mode and self.frozen_stages >= 0: - for i in range(self.frozen_stages): - for j in range(*self.range_sub_modules[i]): - mod = vgg_layers[j] - mod.eval() - for param in mod.parameters(): - param.requires_grad = False diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/sessions.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/sessions.py deleted file mode 100644 index 6cb3b4dae397930fba60e4c08b25b9444783b6f7..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/sessions.py +++ /dev/null @@ -1,831 +0,0 @@ -""" -requests.sessions -~~~~~~~~~~~~~~~~~ - -This module provides a Session object to manage and persist settings across -requests (cookies, auth, proxies). -""" -import os -import sys -import time -from collections import OrderedDict -from datetime import timedelta - -from ._internal_utils import to_native_string -from .adapters import HTTPAdapter -from .auth import _basic_auth_str -from .compat import Mapping, cookielib, urljoin, urlparse -from .cookies import ( - RequestsCookieJar, - cookiejar_from_dict, - extract_cookies_to_jar, - merge_cookies, -) -from .exceptions import ( - ChunkedEncodingError, - ContentDecodingError, - InvalidSchema, - TooManyRedirects, -) -from .hooks import default_hooks, dispatch_hook - -# formerly defined here, reexposed here for backward compatibility -from .models import ( # noqa: F401 - DEFAULT_REDIRECT_LIMIT, - REDIRECT_STATI, - PreparedRequest, - Request, -) -from .status_codes import codes -from .structures import CaseInsensitiveDict -from .utils import ( # noqa: F401 - DEFAULT_PORTS, - default_headers, - get_auth_from_url, - get_environ_proxies, - get_netrc_auth, - requote_uri, - resolve_proxies, - rewind_body, - should_bypass_proxies, - to_key_val_list, -) - -# Preferred clock, based on which one is more accurate on a given system. -if sys.platform == "win32": - preferred_clock = time.perf_counter -else: - preferred_clock = time.time - - -def merge_setting(request_setting, session_setting, dict_class=OrderedDict): - """Determines appropriate setting for a given request, taking into account - the explicit setting on that request, and the setting in the session. If a - setting is a dictionary, they will be merged together using `dict_class` - """ - - if session_setting is None: - return request_setting - - if request_setting is None: - return session_setting - - # Bypass if not a dictionary (e.g. verify) - if not ( - isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) - ): - return request_setting - - merged_setting = dict_class(to_key_val_list(session_setting)) - merged_setting.update(to_key_val_list(request_setting)) - - # Remove keys that are set to None. Extract keys first to avoid altering - # the dictionary during iteration. - none_keys = [k for (k, v) in merged_setting.items() if v is None] - for key in none_keys: - del merged_setting[key] - - return merged_setting - - -def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): - """Properly merges both requests and session hooks. - - This is necessary because when request_hooks == {'response': []}, the - merge breaks Session hooks entirely. - """ - if session_hooks is None or session_hooks.get("response") == []: - return request_hooks - - if request_hooks is None or request_hooks.get("response") == []: - return session_hooks - - return merge_setting(request_hooks, session_hooks, dict_class) - - -class SessionRedirectMixin: - def get_redirect_target(self, resp): - """Receives a Response. Returns a redirect URI or ``None``""" - # Due to the nature of how requests processes redirects this method will - # be called at least once upon the original response and at least twice - # on each subsequent redirect response (if any). - # If a custom mixin is used to handle this logic, it may be advantageous - # to cache the redirect location onto the response object as a private - # attribute. - if resp.is_redirect: - location = resp.headers["location"] - # Currently the underlying http module on py3 decode headers - # in latin1, but empirical evidence suggests that latin1 is very - # rarely used with non-ASCII characters in HTTP headers. - # It is more likely to get UTF8 header rather than latin1. - # This causes incorrect handling of UTF8 encoded location headers. - # To solve this, we re-encode the location in latin1. - location = location.encode("latin1") - return to_native_string(location, "utf8") - return None - - def should_strip_auth(self, old_url, new_url): - """Decide whether Authorization header should be removed when redirecting""" - old_parsed = urlparse(old_url) - new_parsed = urlparse(new_url) - if old_parsed.hostname != new_parsed.hostname: - return True - # Special case: allow http -> https redirect when using the standard - # ports. This isn't specified by RFC 7235, but is kept to avoid - # breaking backwards compatibility with older versions of requests - # that allowed any redirects on the same host. - if ( - old_parsed.scheme == "http" - and old_parsed.port in (80, None) - and new_parsed.scheme == "https" - and new_parsed.port in (443, None) - ): - return False - - # Handle default port usage corresponding to scheme. - changed_port = old_parsed.port != new_parsed.port - changed_scheme = old_parsed.scheme != new_parsed.scheme - default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) - if ( - not changed_scheme - and old_parsed.port in default_port - and new_parsed.port in default_port - ): - return False - - # Standard case: root URI must match - return changed_port or changed_scheme - - def resolve_redirects( - self, - resp, - req, - stream=False, - timeout=None, - verify=True, - cert=None, - proxies=None, - yield_requests=False, - **adapter_kwargs, - ): - """Receives a Response. Returns a generator of Responses or Requests.""" - - hist = [] # keep track of history - - url = self.get_redirect_target(resp) - previous_fragment = urlparse(req.url).fragment - while url: - prepared_request = req.copy() - - # Update history and keep track of redirects. - # resp.history must ignore the original request in this loop - hist.append(resp) - resp.history = hist[1:] - - try: - resp.content # Consume socket so it can be released - except (ChunkedEncodingError, ContentDecodingError, RuntimeError): - resp.raw.read(decode_content=False) - - if len(resp.history) >= self.max_redirects: - raise TooManyRedirects( - f"Exceeded {self.max_redirects} redirects.", response=resp - ) - - # Release the connection back into the pool. - resp.close() - - # Handle redirection without scheme (see: RFC 1808 Section 4) - if url.startswith("//"): - parsed_rurl = urlparse(resp.url) - url = ":".join([to_native_string(parsed_rurl.scheme), url]) - - # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) - parsed = urlparse(url) - if parsed.fragment == "" and previous_fragment: - parsed = parsed._replace(fragment=previous_fragment) - elif parsed.fragment: - previous_fragment = parsed.fragment - url = parsed.geturl() - - # Facilitate relative 'location' headers, as allowed by RFC 7231. - # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') - # Compliant with RFC3986, we percent encode the url. - if not parsed.netloc: - url = urljoin(resp.url, requote_uri(url)) - else: - url = requote_uri(url) - - prepared_request.url = to_native_string(url) - - self.rebuild_method(prepared_request, resp) - - # https://github.com/psf/requests/issues/1084 - if resp.status_code not in ( - codes.temporary_redirect, - codes.permanent_redirect, - ): - # https://github.com/psf/requests/issues/3490 - purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") - for header in purged_headers: - prepared_request.headers.pop(header, None) - prepared_request.body = None - - headers = prepared_request.headers - headers.pop("Cookie", None) - - # Extract any cookies sent on the response to the cookiejar - # in the new request. Because we've mutated our copied prepared - # request, use the old one that we haven't yet touched. - extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) - merge_cookies(prepared_request._cookies, self.cookies) - prepared_request.prepare_cookies(prepared_request._cookies) - - # Rebuild auth and proxy information. - proxies = self.rebuild_proxies(prepared_request, proxies) - self.rebuild_auth(prepared_request, resp) - - # A failed tell() sets `_body_position` to `object()`. This non-None - # value ensures `rewindable` will be True, allowing us to raise an - # UnrewindableBodyError, instead of hanging the connection. - rewindable = prepared_request._body_position is not None and ( - "Content-Length" in headers or "Transfer-Encoding" in headers - ) - - # Attempt to rewind consumed file-like object. - if rewindable: - rewind_body(prepared_request) - - # Override the original request. - req = prepared_request - - if yield_requests: - yield req - else: - - resp = self.send( - req, - stream=stream, - timeout=timeout, - verify=verify, - cert=cert, - proxies=proxies, - allow_redirects=False, - **adapter_kwargs, - ) - - extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) - - # extract redirect url, if any, for the next loop - url = self.get_redirect_target(resp) - yield resp - - def rebuild_auth(self, prepared_request, response): - """When being redirected we may want to strip authentication from the - request to avoid leaking credentials. This method intelligently removes - and reapplies authentication where possible to avoid credential loss. - """ - headers = prepared_request.headers - url = prepared_request.url - - if "Authorization" in headers and self.should_strip_auth( - response.request.url, url - ): - # If we get redirected to a new host, we should strip out any - # authentication headers. - del headers["Authorization"] - - # .netrc might have more auth for us on our new host. - new_auth = get_netrc_auth(url) if self.trust_env else None - if new_auth is not None: - prepared_request.prepare_auth(new_auth) - - def rebuild_proxies(self, prepared_request, proxies): - """This method re-evaluates the proxy configuration by considering the - environment variables. If we are redirected to a URL covered by - NO_PROXY, we strip the proxy configuration. Otherwise, we set missing - proxy keys for this URL (in case they were stripped by a previous - redirect). - - This method also replaces the Proxy-Authorization header where - necessary. - - :rtype: dict - """ - headers = prepared_request.headers - scheme = urlparse(prepared_request.url).scheme - new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) - - if "Proxy-Authorization" in headers: - del headers["Proxy-Authorization"] - - try: - username, password = get_auth_from_url(new_proxies[scheme]) - except KeyError: - username, password = None, None - - if username and password: - headers["Proxy-Authorization"] = _basic_auth_str(username, password) - - return new_proxies - - def rebuild_method(self, prepared_request, response): - """When being redirected we may want to change the method of the request - based on certain specs or browser behavior. - """ - method = prepared_request.method - - # https://tools.ietf.org/html/rfc7231#section-6.4.4 - if response.status_code == codes.see_other and method != "HEAD": - method = "GET" - - # Do what the browsers do, despite standards... - # First, turn 302s into GETs. - if response.status_code == codes.found and method != "HEAD": - method = "GET" - - # Second, if a POST is responded to with a 301, turn it into a GET. - # This bizarre behaviour is explained in Issue 1704. - if response.status_code == codes.moved and method == "POST": - method = "GET" - - prepared_request.method = method - - -class Session(SessionRedirectMixin): - """A Requests session. - - Provides cookie persistence, connection-pooling, and configuration. - - Basic Usage:: - - >>> import requests - >>> s = requests.Session() - >>> s.get('https://httpbin.org/get') - - - Or as a context manager:: - - >>> with requests.Session() as s: - ... s.get('https://httpbin.org/get') - - """ - - __attrs__ = [ - "headers", - "cookies", - "auth", - "proxies", - "hooks", - "params", - "verify", - "cert", - "adapters", - "stream", - "trust_env", - "max_redirects", - ] - - def __init__(self): - - #: A case-insensitive dictionary of headers to be sent on each - #: :class:`Request ` sent from this - #: :class:`Session `. - self.headers = default_headers() - - #: Default Authentication tuple or object to attach to - #: :class:`Request `. - self.auth = None - - #: Dictionary mapping protocol or protocol and host to the URL of the proxy - #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to - #: be used on each :class:`Request `. - self.proxies = {} - - #: Event-handling hooks. - self.hooks = default_hooks() - - #: Dictionary of querystring data to attach to each - #: :class:`Request `. The dictionary values may be lists for - #: representing multivalued query parameters. - self.params = {} - - #: Stream response content default. - self.stream = False - - #: SSL Verification default. - #: Defaults to `True`, requiring requests to verify the TLS certificate at the - #: remote end. - #: If verify is set to `False`, requests will accept any TLS certificate - #: presented by the server, and will ignore hostname mismatches and/or - #: expired certificates, which will make your application vulnerable to - #: man-in-the-middle (MitM) attacks. - #: Only set this to `False` for testing. - self.verify = True - - #: SSL client certificate default, if String, path to ssl client - #: cert file (.pem). If Tuple, ('cert', 'key') pair. - self.cert = None - - #: Maximum number of redirects allowed. If the request exceeds this - #: limit, a :class:`TooManyRedirects` exception is raised. - #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is - #: 30. - self.max_redirects = DEFAULT_REDIRECT_LIMIT - - #: Trust environment settings for proxy configuration, default - #: authentication and similar. - self.trust_env = True - - #: A CookieJar containing all currently outstanding cookies set on this - #: session. By default it is a - #: :class:`RequestsCookieJar `, but - #: may be any other ``cookielib.CookieJar`` compatible object. - self.cookies = cookiejar_from_dict({}) - - # Default connection adapters. - self.adapters = OrderedDict() - self.mount("https://", HTTPAdapter()) - self.mount("http://", HTTPAdapter()) - - def __enter__(self): - return self - - def __exit__(self, *args): - self.close() - - def prepare_request(self, request): - """Constructs a :class:`PreparedRequest ` for - transmission and returns it. The :class:`PreparedRequest` has settings - merged from the :class:`Request ` instance and those of the - :class:`Session`. - - :param request: :class:`Request` instance to prepare with this - session's settings. - :rtype: requests.PreparedRequest - """ - cookies = request.cookies or {} - - # Bootstrap CookieJar. - if not isinstance(cookies, cookielib.CookieJar): - cookies = cookiejar_from_dict(cookies) - - # Merge with session cookies - merged_cookies = merge_cookies( - merge_cookies(RequestsCookieJar(), self.cookies), cookies - ) - - # Set environment's basic authentication if not explicitly set. - auth = request.auth - if self.trust_env and not auth and not self.auth: - auth = get_netrc_auth(request.url) - - p = PreparedRequest() - p.prepare( - method=request.method.upper(), - url=request.url, - files=request.files, - data=request.data, - json=request.json, - headers=merge_setting( - request.headers, self.headers, dict_class=CaseInsensitiveDict - ), - params=merge_setting(request.params, self.params), - auth=merge_setting(auth, self.auth), - cookies=merged_cookies, - hooks=merge_hooks(request.hooks, self.hooks), - ) - return p - - def request( - self, - method, - url, - params=None, - data=None, - headers=None, - cookies=None, - files=None, - auth=None, - timeout=None, - allow_redirects=True, - proxies=None, - hooks=None, - stream=None, - verify=None, - cert=None, - json=None, - ): - """Constructs a :class:`Request `, prepares it and sends it. - Returns :class:`Response ` object. - - :param method: method for the new :class:`Request` object. - :param url: URL for the new :class:`Request` object. - :param params: (optional) Dictionary or bytes to be sent in the query - string for the :class:`Request`. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) json to send in the body of the - :class:`Request`. - :param headers: (optional) Dictionary of HTTP Headers to send with the - :class:`Request`. - :param cookies: (optional) Dict or CookieJar object to send with the - :class:`Request`. - :param files: (optional) Dictionary of ``'filename': file-like-objects`` - for multipart encoding upload. - :param auth: (optional) Auth tuple or callable to enable - Basic/Digest/Custom HTTP Auth. - :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 allow_redirects: (optional) Set to True by default. - :type allow_redirects: bool - :param proxies: (optional) Dictionary mapping protocol or protocol and - hostname to the URL of the proxy. - :param stream: (optional) whether to immediately download the response - content. Defaults to ``False``. - :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. Defaults to ``True``. When set to - ``False``, requests will accept any TLS certificate presented by - the server, and will ignore hostname mismatches and/or expired - certificates, which will make your application vulnerable to - man-in-the-middle (MitM) attacks. Setting verify to ``False`` - may be useful during local development or testing. - :param cert: (optional) if String, path to ssl client cert file (.pem). - If Tuple, ('cert', 'key') pair. - :rtype: requests.Response - """ - # Create the Request. - req = Request( - method=method.upper(), - url=url, - headers=headers, - files=files, - data=data or {}, - json=json, - params=params or {}, - auth=auth, - cookies=cookies, - hooks=hooks, - ) - prep = self.prepare_request(req) - - proxies = proxies or {} - - settings = self.merge_environment_settings( - prep.url, proxies, stream, verify, cert - ) - - # Send the request. - send_kwargs = { - "timeout": timeout, - "allow_redirects": allow_redirects, - } - send_kwargs.update(settings) - resp = self.send(prep, **send_kwargs) - - return resp - - def get(self, url, **kwargs): - r"""Sends a GET request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", True) - return self.request("GET", url, **kwargs) - - def options(self, url, **kwargs): - r"""Sends a OPTIONS request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", True) - return self.request("OPTIONS", url, **kwargs) - - def head(self, url, **kwargs): - r"""Sends a HEAD request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", False) - return self.request("HEAD", url, **kwargs) - - def post(self, url, data=None, json=None, **kwargs): - r"""Sends a POST request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) json to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("POST", url, data=data, json=json, **kwargs) - - def put(self, url, data=None, **kwargs): - r"""Sends a PUT request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("PUT", url, data=data, **kwargs) - - def patch(self, url, data=None, **kwargs): - r"""Sends a PATCH request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("PATCH", url, data=data, **kwargs) - - def delete(self, url, **kwargs): - r"""Sends a DELETE request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("DELETE", url, **kwargs) - - def send(self, request, **kwargs): - """Send a given PreparedRequest. - - :rtype: requests.Response - """ - # Set defaults that the hooks can utilize to ensure they always have - # the correct parameters to reproduce the previous request. - kwargs.setdefault("stream", self.stream) - kwargs.setdefault("verify", self.verify) - kwargs.setdefault("cert", self.cert) - if "proxies" not in kwargs: - kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) - - # It's possible that users might accidentally send a Request object. - # Guard against that specific failure case. - if isinstance(request, Request): - raise ValueError("You can only send PreparedRequests.") - - # Set up variables needed for resolve_redirects and dispatching of hooks - allow_redirects = kwargs.pop("allow_redirects", True) - stream = kwargs.get("stream") - hooks = request.hooks - - # Get the appropriate adapter to use - adapter = self.get_adapter(url=request.url) - - # Start time (approximately) of the request - start = preferred_clock() - - # Send the request - r = adapter.send(request, **kwargs) - - # Total elapsed time of the request (approximately) - elapsed = preferred_clock() - start - r.elapsed = timedelta(seconds=elapsed) - - # Response manipulation hooks - r = dispatch_hook("response", hooks, r, **kwargs) - - # Persist cookies - if r.history: - - # If the hooks create history then we want those cookies too - for resp in r.history: - extract_cookies_to_jar(self.cookies, resp.request, resp.raw) - - extract_cookies_to_jar(self.cookies, request, r.raw) - - # Resolve redirects if allowed. - if allow_redirects: - # Redirect resolving generator. - gen = self.resolve_redirects(r, request, **kwargs) - history = [resp for resp in gen] - else: - history = [] - - # Shuffle things around if there's history. - if history: - # Insert the first (original) request at the start - history.insert(0, r) - # Get the last request made - r = history.pop() - r.history = history - - # If redirects aren't being followed, store the response on the Request for Response.next(). - if not allow_redirects: - try: - r._next = next( - self.resolve_redirects(r, request, yield_requests=True, **kwargs) - ) - except StopIteration: - pass - - if not stream: - r.content - - return r - - def merge_environment_settings(self, url, proxies, stream, verify, cert): - """ - Check the environment and merge it with some settings. - - :rtype: dict - """ - # Gather clues from the surrounding environment. - if self.trust_env: - # Set environment's proxies. - no_proxy = proxies.get("no_proxy") if proxies is not None else None - env_proxies = get_environ_proxies(url, no_proxy=no_proxy) - for (k, v) in env_proxies.items(): - proxies.setdefault(k, v) - - # Look for requests environment configuration - # and be compatible with cURL. - if verify is True or verify is None: - verify = ( - os.environ.get("REQUESTS_CA_BUNDLE") - or os.environ.get("CURL_CA_BUNDLE") - or verify - ) - - # Merge all the kwargs. - proxies = merge_setting(proxies, self.proxies) - stream = merge_setting(stream, self.stream) - verify = merge_setting(verify, self.verify) - cert = merge_setting(cert, self.cert) - - return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} - - def get_adapter(self, url): - """ - Returns the appropriate connection adapter for the given URL. - - :rtype: requests.adapters.BaseAdapter - """ - for (prefix, adapter) in self.adapters.items(): - - if url.lower().startswith(prefix.lower()): - return adapter - - # Nothing matches :-/ - raise InvalidSchema(f"No connection adapters were found for {url!r}") - - def close(self): - """Closes all adapters and as such the session""" - for v in self.adapters.values(): - v.close() - - def mount(self, prefix, adapter): - """Registers a connection adapter to a prefix. - - Adapters are sorted in descending order by prefix length. - """ - self.adapters[prefix] = adapter - keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] - - for key in keys_to_move: - self.adapters[key] = self.adapters.pop(key) - - def __getstate__(self): - state = {attr: getattr(self, attr, None) for attr in self.__attrs__} - return state - - def __setstate__(self, state): - for attr, value in state.items(): - setattr(self, attr, value) - - -def session(): - """ - Returns a :class:`Session` for context-management. - - .. deprecated:: 1.0.0 - - This method has been deprecated since version 1.0.0 and is only kept for - backwards compatibility. New code should use :class:`~requests.sessions.Session` - to create a session. This may be removed at a future date. - - :rtype: Session - """ - return Session() diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/connection.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/connection.py deleted file mode 100644 index 6af1138f260e4eaaa0aa242f7f50b918a283b49f..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/connection.py +++ /dev/null @@ -1,149 +0,0 @@ -from __future__ import absolute_import - -import socket - -from ..contrib import _appengine_environ -from ..exceptions import LocationParseError -from ..packages import six -from .wait import NoWayToWaitForSocketError, wait_for_read - - -def is_connection_dropped(conn): # Platform-specific - """ - Returns True if the connection is dropped and should be closed. - - :param conn: - :class:`http.client.HTTPConnection` object. - - Note: For platforms like AppEngine, this will always return ``False`` to - let the platform handle connection recycling transparently for us. - """ - sock = getattr(conn, "sock", False) - if sock is False: # Platform-specific: AppEngine - return False - if sock is None: # Connection already closed (such as by httplib). - return True - try: - # Returns True if readable, which here means it's been dropped - return wait_for_read(sock, timeout=0.0) - except NoWayToWaitForSocketError: # Platform-specific: AppEngine - return False - - -# This function is copied from socket.py in the Python 2.7 standard -# library test suite. Added to its signature is only `socket_options`. -# One additional modification is that we avoid binding to IPv6 servers -# discovered in DNS if the system doesn't have IPv6 functionality. -def create_connection( - address, - timeout=socket._GLOBAL_DEFAULT_TIMEOUT, - source_address=None, - socket_options=None, -): - """Connect to *address* and return the socket object. - - Convenience function. Connect to *address* (a 2-tuple ``(host, - port)``) and return the socket object. Passing the optional - *timeout* parameter will set the timeout on the socket instance - before attempting to connect. If no *timeout* is supplied, the - global default timeout setting returned by :func:`socket.getdefaulttimeout` - is used. If *source_address* is set it must be a tuple of (host, port) - for the socket to bind as a source address before making the connection. - An host of '' or port 0 tells the OS to use the default. - """ - - host, port = address - if host.startswith("["): - host = host.strip("[]") - err = None - - # Using the value from allowed_gai_family() in the context of getaddrinfo lets - # us select whether to work with IPv4 DNS records, IPv6 records, or both. - # The original create_connection function always returns all records. - family = allowed_gai_family() - - try: - host.encode("idna") - except UnicodeError: - return six.raise_from( - LocationParseError(u"'%s', label empty or too long" % host), None - ) - - for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): - af, socktype, proto, canonname, sa = res - sock = None - try: - sock = socket.socket(af, socktype, proto) - - # If provided, set socket level options before connecting. - _set_socket_options(sock, socket_options) - - if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: - sock.settimeout(timeout) - if source_address: - sock.bind(source_address) - sock.connect(sa) - return sock - - except socket.error as e: - err = e - if sock is not None: - sock.close() - sock = None - - if err is not None: - raise err - - raise socket.error("getaddrinfo returns an empty list") - - -def _set_socket_options(sock, options): - if options is None: - return - - for opt in options: - sock.setsockopt(*opt) - - -def allowed_gai_family(): - """This function is designed to work in the context of - getaddrinfo, where family=socket.AF_UNSPEC is the default and - will perform a DNS search for both IPv6 and IPv4 records.""" - - family = socket.AF_INET - if HAS_IPV6: - family = socket.AF_UNSPEC - return family - - -def _has_ipv6(host): - """Returns True if the system can bind an IPv6 address.""" - sock = None - has_ipv6 = False - - # App Engine doesn't support IPV6 sockets and actually has a quota on the - # number of sockets that can be used, so just early out here instead of - # creating a socket needlessly. - # See https://github.com/urllib3/urllib3/issues/1446 - if _appengine_environ.is_appengine_sandbox(): - return False - - if socket.has_ipv6: - # has_ipv6 returns true if cPython was compiled with IPv6 support. - # It does not tell us if the system has IPv6 support enabled. To - # determine that we must bind to an IPv6 address. - # https://github.com/urllib3/urllib3/pull/611 - # https://bugs.python.org/issue658327 - try: - sock = socket.socket(socket.AF_INET6) - sock.bind((host, 0)) - has_ipv6 = True - except Exception: - pass - - if sock: - sock.close() - return has_ipv6 - - -HAS_IPV6 = _has_ipv6("::1") diff --git a/spaces/Aveygo/AstroSleuth/results/details.md b/spaces/Aveygo/AstroSleuth/results/details.md deleted file mode 100644 index feddd7277487f60443718943ca466397809aa948..0000000000000000000000000000000000000000 --- a/spaces/Aveygo/AstroSleuth/results/details.md +++ /dev/null @@ -1,44 +0,0 @@ -## Details - -The provided sample images were selected from the daily top of r/astrophotography on 4/9/2023. -To minise cherry picking, my only criteria was that they must cover a broad range of deep space targets. -They have not been resized or had noise added to them, but were cropped to a 512x512 tile of my choosing based on what I deemed as the most important aspect. eg: lots of noise/stars, nebulosity, or artifacts. - -## Tips, Tricks & Issues - -After upscaling many images, in general it almost always helps to **reduce the image size** before feeding it into the model. It is slightly counterintuitive as one might think that larger is better, but the main failure point is the original size. I believe this is due to the fact that the model is trained to expect images that are 4x smaller than they should be because it's task is to reverse this process. - -**After reducing image size such that the stars are at no more than 6pixels wide, performance can drastically improve.** - -To get to the expected size, the upscaled "crushed" image can be upscaled once again. - -### Workflow for difficult cases - -1. Original -> +downsample 4x -> +noise -> +blur -> Crushed -2. Crushed -> +upscale -> +upscale -> Output - -Please note that the tile size parameter for the model was reduced from 512x512 to 128x128 to fit the input image better. - -### Summary - -1. Reduce image size and upscale twice -2. AstroSleuthV1 generally works better for smoother results, V2 for anything else -3. Don't be afraid to add noise or blur the image to improve results -4. Diffraction spikes are almost always troublesome - -### Workflow result on original/sample2.png - - - -| Raw AstroSleuthV2 | Workflow with V2 | Workflow with V1 | -| --- | --- | --- | -| | | | - -As you can see, this workflow works much better with AstroSleuthV1 for this particular image. However I find results can drastically differ based on the amount of noise/blur applied to the crushed image, but were kept the same for the sake of comparison. - - -### Image credits / sources -https://www.reddit.com/r/astrophotography/comments/12fnhb3/m35_and_ngc_2158/ -https://www.reddit.com/r/astrophotography/comments/12flzf1/messier_106_in_lrgb/ -https://www.reddit.com/r/astrophotography/comments/12febjp/orion_nebula/ -https://www.reddit.com/r/astrophotography/comments/12fewff/northwestern_cygnus_nebulae/ diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/config/test_lazy_config.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/config/test_lazy_config.py deleted file mode 100644 index 6ff5b6dc117744a9d978e0aff324bddeb496409b..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/config/test_lazy_config.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import os -import unittest -import tempfile -from itertools import count - -from detectron2.config import LazyConfig, LazyCall as L -from omegaconf import DictConfig - - -class TestLazyPythonConfig(unittest.TestCase): - def setUp(self): - self.root_filename = os.path.join(os.path.dirname(__file__), "root_cfg.py") - - def test_load(self): - cfg = LazyConfig.load(self.root_filename) - - self.assertEqual(cfg.dir1a_dict.a, "modified") - self.assertEqual(cfg.dir1b_dict.a, 1) - self.assertEqual(cfg.lazyobj.x, "base_a_1") - - cfg.lazyobj.x = "new_x" - # reload - cfg = LazyConfig.load(self.root_filename) - self.assertEqual(cfg.lazyobj.x, "base_a_1") - - def test_save_load(self): - cfg = LazyConfig.load(self.root_filename) - with tempfile.TemporaryDirectory(prefix="detectron2") as d: - fname = os.path.join(d, "test_config.yaml") - LazyConfig.save(cfg, fname) - cfg2 = LazyConfig.load(fname) - - self.assertEqual(cfg2.lazyobj._target_, "itertools.count") - self.assertEqual(cfg.lazyobj._target_, count) - cfg2.lazyobj.pop("_target_") - cfg.lazyobj.pop("_target_") - # the rest are equal - self.assertEqual(cfg, cfg2) - - def test_failed_save(self): - cfg = DictConfig({"x": lambda: 3}, flags={"allow_objects": True}) - with tempfile.TemporaryDirectory(prefix="detectron2") as d: - fname = os.path.join(d, "test_config.yaml") - LazyConfig.save(cfg, fname) - self.assertTrue(os.path.exists(fname)) - self.assertTrue(os.path.exists(fname + ".pkl")) - - def test_overrides(self): - cfg = LazyConfig.load(self.root_filename) - LazyConfig.apply_overrides(cfg, ["lazyobj.x=123", 'dir1b_dict.a="123"']) - self.assertEqual(cfg.dir1b_dict.a, "123") - self.assertEqual(cfg.lazyobj.x, 123) - - def test_invalid_overrides(self): - cfg = LazyConfig.load(self.root_filename) - with self.assertRaises(KeyError): - LazyConfig.apply_overrides(cfg, ["lazyobj.x.xxx=123"]) - - def test_to_py(self): - cfg = LazyConfig.load(self.root_filename) - cfg.lazyobj.x = {"a": 1, "b": 2, "c": L(count)(x={"r": "a", "s": 2.4, "t": [1, 2, 3, "z"]})} - cfg.list = ["a", 1, "b", 3.2] - py_str = LazyConfig.to_py(cfg) - expected = """cfg.dir1a_dict.a = "modified" -cfg.dir1a_dict.b = 2 -cfg.dir1b_dict.a = 1 -cfg.dir1b_dict.b = 2 -cfg.lazyobj = itertools.count( - x={ - "a": 1, - "b": 2, - "c": itertools.count(x={"r": "a", "s": 2.4, "t": [1, 2, 3, "z"]}), - }, - y="base_a_1_from_b", -) -cfg.list = ["a", 1, "b", 3.2] -""" - self.assertEqual(py_str, expected) diff --git a/spaces/Benson/text-generation/Examples/7 Espaol.md b/spaces/Benson/text-generation/Examples/7 Espaol.md deleted file mode 100644 index a887ecffeb45a347b480d0179117c260dc5a27ad..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/7 Espaol.md +++ /dev/null @@ -1,45 +0,0 @@ -
    -

    ¿Qué es 7 Inglés y cómo puede ayudarle a aprender gramática inglesa?

    -

    El inglés es uno de los idiomas más hablados en el mundo, y aprenderlo puede abrirte muchas puertas en términos de educación, carrera, viajes y comunicación. Sin embargo, aprender inglés no siempre es fácil, especialmente cuando se trata de gramática. La gramática es el conjunto de reglas que gobiernan cómo las palabras y las oraciones se estructuran y se utilizan en un idioma. La gramática puede ser confusa y frustrante para muchos estudiantes, ya que hay muchas excepciones, variaciones y matices que necesitan ser dominados.

    -

    Ahí es donde 7 Inglés entra en juego. 7 English es un sitio web que proporciona lecciones completas y fáciles de seguir sobre varios aspectos de la gramática inglesa. Ya seas un principiante o un estudiante avanzado, 7 Inglés puede ayudarte a mejorar tus habilidades gramaticales de una manera simple y efectiva. Puedes acceder a cientos de temas de gramática, ejemplos, ejercicios, hojas de trabajo, videos, cuestionarios, consejos y más en el sitio web de 7 English. También puedes interactuar con otros estudiantes y profesores en el foro de inglés 7. 7 El inglés es tu destino único para aprender gramática inglesa en línea.

    -

    7 Español


    Download File ——— https://bltlly.com/2v6Ksb



    -

    En este artículo, te mostraremos cómo aprender gramática inglesa con 7 Inglés en seis sencillos pasos. Siguiendo estos pasos, podrás dominar las reglas gramaticales esenciales y los conceptos que te ayudarán a hablar y escribir mejor en inglés. ¡Vamos a empezar!

    -

    Cómo aprender gramática inglesa con 7

    -

    Aprender partes del habla

    - -

    Aprender partes del habla es importante porque te ayuda a entender cómo las palabras trabajan juntas para formar significado. También te ayuda a evitar errores gramaticales como el acuerdo sujeto-verbo o el acuerdo sustantivo-pronombre. Para aprender partes del habla con 7 Inglés, puede visitar su parts of speech sectionpartes de videos de discurso para aprender los fundamentos de cada parte del discurso de una manera divertida y atractiva.

    -

    Aprender tiempos verbales

    -

    Los tiempos verbales son las formas que toman los verbos para indicar el tiempo y el aspecto de una acción o estado. Hay tres tipos principales de tiempos verbales en inglés: pasado, presente y futuro. Cada tipo tiene cuatro aspectos: simple, continuo, perfecto y perfecto continuo. Por ejemplo, el tiempo simple pasado expresa una acción o estado que ocurrió en el pasado y se completa; el tiempo continuo pasado expresa una acción o estado que estaba en progreso en el pasado; el tiempo perfecto pasado expresa una acción o estado que se completó antes de otra acción o estado en el pasado; el tiempo continuo perfecto pasado expresa una acción o estado que estaba en progreso durante algún tiempo antes de otra acción o estado en el pasado.

    -

    Aprender los tiempos verbales es importante porque te ayuda a expresar cuándo y cómo sucede o sucedió algo. También le ayuda a evitar errores gramaticales tales como inconsistencia del tiempo o mal uso del tiempo. Para aprender los tiempos verbales con 7 en inglés, puedes visitar su sección tiempos verbales donde puedes encontrar explicaciones detalladas, ejemplos y ejercicios para cada tiempo verbal. También puedes ver sus videos verb tenses videos para aprender los conceptos básicos de cada verbo de una manera divertida y atractiva.

    -

    Aprender oraciones, frases y cláusulas

    - -

    Aprender oraciones, frases y cláusulas es importante porque te ayuda a entender cómo las palabras están organizadas y conectadas con el significado de la forma. También le ayuda a evitar errores gramaticales como fragmentos de oración, oraciones en ejecución, empalmes de coma o modificadores mal colocados. Para aprender oraciones, frases y cláusulas con 7 Inglés, puede visitar su sección sentences, phrases, and clauses section donde puede encontrar explicaciones detalladas, ejemplos y ejercicios para cada tema. También puedes ver sus videos sentences, phrases, and clauses videos para aprender los conceptos básicos de cada tema de una manera divertida y atractiva.

    -

    Aprender Condicionales, Habla Reportada, Voz Pasiva, Cuantificadores y Determinantes

    -

    Condicionales, discurso informado, voz pasiva, cuantificadores y determinantes son algunos de los temas avanzados de la gramática inglesa que pueden ayudarte a expresar ideas y situaciones complejas. Las condicionales son oraciones que expresan situaciones hipotéticas o reales y sus consecuencias. El discurso informado es la forma de informar lo que alguien dijo o pensó sin usar citas directas. La voz pasiva es la forma de expresar una acción sin enfatizar quién o qué la realiza. Cuantificadores son palabras que indican la cantidad o cantidad de algo. Los determinantes son palabras que modifican sustantivos o frases de sustantivos y especifican su referencia.

    - -

    Aprenda las reglas básicas de gramática: Estructura de oraciones en inglés

    -

    Las reglas gramaticales básicas son los principios generales que rigen la forma en que las palabras y las oraciones se estructuran y usan en inglés. Algunas de las reglas gramaticales básicas incluyen acuerdo sujeto-verbo, acuerdo sustantivo-pronombre, orden de las palabras, mayúsculas, puntuación, ortografía y más. Estas reglas te ayudan a crear oraciones claras y correctas que transmiten tu significado.

    -

    -

    Aprender reglas gramaticales básicas es importante porque te ayuda a evitar errores gramaticales comunes y malentendidos que pueden afectar tu comunicación y credibilidad. También le ayuda a mejorar sus habilidades de lectura y escritura y prepararse para varios exámenes y exámenes. Para aprender las reglas gramaticales básicas con 7 en inglés, puedes visitar su sección basic grammar rules donde puedes encontrar explicaciones detalladas, ejemplos y ejercicios para cada regla. También puedes ver sus videos basic grammar rules videos para aprender los fundamentos de cada regla de una manera divertida y atractiva.

    -

    Aprende a escribir números y signos de puntuación

    -

    Los números y los signos de puntuación son los símbolos que se utilizan para representar cantidades, valores, fechas, tiempos, fracciones, decimales, porcentajes y más. También se utilizan para separar, conectar o enfatizar palabras y oraciones. Algunos de los números y signos de puntuación comunes en inglés son: 0-9, . ¿; ; ? ! ' " ( ) [ ] - _ / \ * & # @ % $ € £ + = < > ~ ^ ¨ ´ ` ¸ ¯ º ª © ® ™ ¹ ² ³ ¼ ½ ¾ ° ∞ √ π × ÷ ≠ ≤ ≥ ± ∑ ∏ ∫ ∂ ∆ ∇ ∧ ∨ ¬ ⇒ ⇔ ∀ ∃ ∈ ∉ ⊂ ⊃ ⊆ ⊇ ∅ ∩ ∪ ℵ ℤ ℚ ℝ ℂ ℍ ℕ ℙ ℚ ℤ ℬ ℰ ℱ ℋ ℐ ℒ ℳ ℛ ℭ ℌ ℑ ℜ ℵ α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ σ τ υ φ χ ψ ω Γ Δ Θ Λ Ξ Π Σ Φ Ψ Ω and more.

    - -

    Conclusión

    -

    En conclusión, 7 English es un sitio web que puede ayudarte a aprender gramática inglesa de una manera simple y efectiva. Puedes acceder a cientos de temas de gramática, ejemplos, ejercicios, hojas de trabajo, videos, cuestionarios, consejos y más en el sitio web de 7 English. También puede interactuar con otros estudiantes y profesores en el foro 7 Inglés. Siguiendo los seis pasos que hemos descrito en este artículo, podrás dominar las reglas gramaticales y los conceptos esenciales que te ayudarán a hablar y escribir mejor en inglés.

    -

    Si quieres mejorar tus habilidades gramaticales y aumentar tu confianza en el uso del inglés, no dudes en visitar el sitio web 7 en inglés hoy. Te sorprenderá lo mucho que puedes aprender y mejorar con 7 Inglés. Recuerda, la gramática no es una pesadilla; es una herramienta que puede ayudarte a alcanzar tus metas en el aprendizaje del inglés.

    -

    Preguntas frecuentes

    -

    Aquí están algunas de las preguntas más frecuentes relacionadas con el tema de este artículo:

    -
      -
    • ¿Cuál es la mejor manera de aprender gramática inglesa?
    • -

      La mejor manera de aprender gramática inglesa es usar una combinación de métodos que se adapten a tu estilo de aprendizaje, nivel, metas y preferencias. Algunos de los métodos incluyen: leer libros, artículos, blogs o revistas en inglés; escuchar podcasts, audiolibros, canciones o programas de radio en inglés; ver películas, programas de televisión, videos o documentales en inglés; hablar con hablantes nativos o fluidos de inglés; escribir ensayos, historias, correos electrónicos o revistas en inglés; tomar cursos o clases en línea o fuera de línea en inglés; usar recursos en línea o fuera de línea como sitios web, aplicaciones, libros, diccionarios o guías de gramática en inglés. La clave es practicar regularmente, revisar con frecuencia y aprender de tus errores.

      -
    • ¿Cuánto tiempo se tarda en aprender gramática inglesa?
    • - -
    • ¿Cuáles son los errores gramaticales más comunes en inglés?
    • -

      Algunos de los errores gramaticales más comunes en inglés son: errores de acuerdo sujeto-verbo, errores de acuerdo sustantivo-pronombre, errores de tiempo verbal, errores de orden de palabras, errores de mayúsculas, errores de puntuación, errores de ortografía, errores de artículo, errores de preposición, errores de modificación, errores de paralelismo y más. Para evitar estos errores, necesitas aprender las reglas gramaticales y los conceptos que los rigen y practicarlos con ejercicios y cuestionarios. También puede utilizar herramientas en línea como correctores de gramática o correctores de pruebas para ayudarle a identificar y corregir sus errores.

      -
    • ¿Cuáles son los beneficios de aprender gramática inglesa?
    • -

      Algunos de los beneficios de aprender gramática inglesa son: mejora tus habilidades de comunicación en el habla y la escritura; mejora tus habilidades de comprensión en la lectura y la escucha; aumenta tu confianza y fluidez en el uso del inglés; expande tu vocabulario y conocimiento del inglés; te prepara para varios exámenes y exámenes en inglés; te abre más oportunidades en educación, carrera, viajes y comunicación.

      -
    • ¿Dónde puedo encontrar más información sobre 7 Inglés?
    • -

      Puede encontrar más información sobre 7 Inglés visitando su sitio web en 7english.com. Allí puedes acceder a cientos de temas de gramática, ejemplos, ejercicios, hojas de trabajo, videos, cuestionarios, consejos y más. También puede interactuar con otros estudiantes y profesores en el foro 7 Inglés. También puedes seguirlos en sus redes sociales como Facebook, Twitter, Instagram, YouTube y Pinterest.

      -

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Billete nter Hall 2023 Ts.md b/spaces/Benson/text-generation/Examples/Descargar Billete nter Hall 2023 Ts.md deleted file mode 100644 index db793023cdc46338799c37f1da683265b457a33d..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Billete nter Hall 2023 Ts.md +++ /dev/null @@ -1,164 +0,0 @@ -
    -

    Descargar 2023 Lineup Fecha de lanzamiento: Todo lo que necesitas saber

    |

    Si eres un fan de la música rock y metal, probablemente has oído hablar de Download Festival. Es el festival de rock más grande y popular del Reino Unido, y ha albergado algunas de las leyendas del género, como Iron Maiden, Black Sabbath, Metallica, Slipknot y muchos más.

    -

    descargar billete ínter hall 2023 ts


    Download Zip ☆☆☆ https://bltlly.com/2v6KQo



    -

    Download Festival regresa en 2023 para una celebración de cuatro días de su 20 aniversario, y promete ser un evento épico. En este artículo, te contaremos todo lo que necesitas saber sobre la fecha de lanzamiento de la alineación Download 2023, entradas, ubicación, titulares, etapas, medidas de seguridad COVID-19 y consejos para preparar y disfrutar del festival.

    -

    ¿Qué es Download Festival?

    -

    Download Festival es un festival de música rock y metal que tiene lugar cada año en Donington Park en Leicestershire, Inglaterra. Fue creado en 2003 como un seguimiento de los festivales Monsters of Rock que se celebraron en el mismo lugar desde 1980 hasta 1996.

    -

    Una breve historia del Download Festival

    -

    El primer Download Festival fue co-reservado por Stuart Galbraith y Andy Copping en 2003, y contó con bandas como Iron Maiden, Audioslave, Marilyn Manson, Deftones y Disturbed. El festival fue inicialmente un evento de dos días, pero se expandió a tres días en 2005. El nombre Download fue elegido para reflejar la naturaleza rebelde de la música rock y la conectividad a Internet con su audiencia.

    -

    Con los años, Download Festival ha crecido en tamaño y popularidad, atrayendo a más de 100.000 asistentes cada año. También ha albergado algunos de los nombres más importantes en la historia del rock y el metal, como Black Sabbath, Metallica, Linkin Park, Korn, Soundgarden, Motörhead, Aerosmith, AC/DC, Def Leppard, Kiss, Judas Priest, Rammstein, Status Quo, Mötley Crüe, Journey, ZZ Top, Whitesnake, Fe No Más y Armas N' Rosas.

    -

    - -

    Las principales características de Download Festival

    -

    Download Festival no es solo música. También ofrece una variedad de atracciones y actividades para sus asistentes. Algunas de las características principales del Download Festival son:

    -
      -
    • The Village: Aquí es donde puedes encontrar puestos de comida, tiendas de mercancías, bares, lugares de entretenimiento y otros servicios.
    • -
    • The Arena: Aquí es donde se encuentran los escenarios principales, y donde puedes ver a tus bandas favoritas en vivo.
    • -
    • Los Campings: Aquí es donde puedes armar tu carpa, conocer a otros asistentes al festival,
    • The Doghouse: Esta es una carpa que alberga espectáculos de comedia, DJ sets, karaoke, discoteca silenciosa y otros eventos divertidos.
    • -
    • Los paquetes RIP (Rest In Peace): Estos son paquetes premium que ofrecen alojamiento de lujo, acceso VIP, instalaciones exclusivas y otras ventajas.
    • -
    -

    ¿Cuándo es Download Festival 2023?

    -

    Download Festival 2023 tendrá lugar del jueves 8 de junio al domingo 11 de junio. Marcará el 20 aniversario del festival, y será una edición especial con cuatro días de música en lugar de los tres habituales.

    -

    Las fechas y ubicación del Download Festival 2023

    -

    Las fechas y la ubicación de Download Festival 2023 son las siguientes:

    - - -Fecha -Ubicación - - -jueves, 8 de junio -Donington Park, Leicestershire, Inglaterra - - -viernes, 9 de junio -Donington Park, Leicestershire, Inglaterra - - -sábado, 10 de junio -Donington Park, Leicestershire, Inglaterra - - -domingo, 11 de junio -Donington Park, Leicestershire, Inglaterra - - -

    Donington Park es un famoso circuito de automovilismo que ha albergado muchos eventos de carreras, como la Fórmula 1, MotoGP y el Campeonato Mundial de Superbike. También es un sitio histórico para la música rock y metal, ya que fue el hogar de los festivales Monsters of Rock y el lugar de nacimiento del Download Festival.

    - -

    Los cabezas de cartel y los escenarios del Download Festival 2023

    -

    Los titulares y etapas de Download Festival 2023 no se han anunciado oficialmente todavía. Sin embargo, algunos rumores y especulaciones han estado circulando en línea. Según algunas fuentes , los posibles protagonistas y escenarios del Download Festival 2023 son:

    - - -Fecha -Etapa -Titular - - -jueves, 8 de junio -Escenario principal -Metallica (interpretando el álbum negro en su totalidad) - - -viernes, 9 de junio -Escenario principal -Beso (tour de despedida) - - -sábado, 10 de junio -Escenario principal -Iron Maiden (gira Legado de la Bestia) - - -domingo, 11 de junio -Escenario principal -Rammstein (nuevo álbum) - - -jueves, 8 de junio -Segunda etapa -Sistema de un Down (gira de reunión) - - -viernes, 9 de junio -Segunda etapa -Slipknot (nuevo álbum) - - -sábado, 10 de junio -Segunda etapa -Herramienta (nuevo álbum) - - -domingo, 11 de junio -Segunda etapa -Uñas de nueve pulgadas (nueva gira del álbum) - - -

    Por supuesto, estos son solo rumores y especulaciones, y pueden cambiar o ser inexactos. La alineación oficial y los escenarios del Download Festival 2023 serán anunciados por los organizadores a su debido tiempo. Puede consultar sus cuentas de sitios web o redes sociales para obtener las últimas actualizaciones y noticias.

    -

    ¿Cómo obtener entradas para Download Festival 2023?

    -

    Si estás interesado en asistir al Download Festival 2023, tendrás que conseguir entradas lo antes posible. Se espera que las entradas para el Download Festival 2023 se agoten rápidamente, ya que la demanda es alta y la oferta es limitada.

    -

    Los tipos y precios de las entradas para Download Festival 2023

    -

    Los tipos y precios de las entradas para Download Festival 2023 son los siguientes:

    - - - -Descripción -Precio - - -Boleto de fin de semana Arena -Este ticket te da acceso solo a la Arena, de viernes a domingo. Tendrás que organizar tu propio alojamiento. -£195 - - -Boleto de campamento de fin de semana -Este ticket te da acceso a la Arena y los Campings, de jueves a lunes. Tendrás que traer tu propia carpa y equipo de camping. -£230 - - -Boleto de acampada tranquila de fin de semana -Este ticket te da acceso a la Arena y al Camping Tranquilo, de jueves a lunes. Tendrá que traer su propia tienda y equipo de camping. El camping tranquilo está situado lejos del camping principal, y tiene un toque de queda ruido a medianoche. -£230 - - - -sitios web de terceros. Estas fuentes pueden vender billetes falsos, inválidos o caros que podrían resultar en decepción o fraude.

    ¿Cómo prepararse para el Festival 2023? -

    Download Festival 2023 va a ser una experiencia increíble, pero también requiere algo de preparación y planificación. Aquí hay algunos consejos sobre cómo prepararse para el Download Festival 2023:

    -

    Las medidas de seguridad COVID-19 para Download Festival 2023

    -

    La pandemia COVID-19 ha afectado muchos eventos y festivales, y Download Festival no es una excepción. Los organizadores del Download Festival 2023 han declarado que seguirán las directrices y regulaciones gubernamentales relativas a las medidas de seguridad COVID-19. También han aconsejado a los asistentes que consulten su sitio web y sus cuentas de redes sociales para obtener las últimas actualizaciones e información.

    -

    Algunas de las posibles medidas de seguridad de COVID-19 para el Download Festival 2023 son:

    -
      -
    • Prueba de vacunación o prueba negativa: Es posible que tenga que mostrar la prueba de vacunación completa o una prueba de flujo lateral negativa tomada dentro de las 48 horas de la llegada al sitio del festival.
    • -
    • Mascarillas y desinfectantes de manos: Es posible que necesite usar una mascarilla facial y usar desinfectante de manos al entrar o salir del sitio del festival, o cuando esté en áreas llenas o cerradas.
    • -
    • Distancia social y límites de capacidad: Es posible que necesites mantener una distancia segura de otras personas y seguir las señales y marcadores que indican los límites de capacidad de ciertas áreas o lugares.
    • -
    • Seguimiento y aislamiento de contactos: Es posible que necesite proporcionar sus datos de contacto y escanear un código QR al entrar o salir del sitio del festival, o al usar ciertas instalaciones o servicios. También es posible que tenga que aislarse e informar al personal del festival si desarrolla algún síntoma de COVID-19 durante o después del festival.
    • -
    - -

    Los consejos y trucos para sobrevivir Descargar Festival 2023

    -

    Download Festival 2023 va a ser muy divertido, pero también puede ser desafiante y agotador. Estos son algunos consejos y trucos para sobrevivir Descargar Festival 2023:

    -
      -
    • Empaca sabiamente: Debes empacar solo lo esencial, como ropa, artículos de tocador, equipo de campamento, cargador de teléfono, tapones para los oídos, protector solar, impermeable, etc. También debes empacar algunos bocadillos, bebidas y medicamentos en caso de que los necesites. Debe evitar traer objetos de valor, artículos prohibidos o exceso de equipaje que pueda agobiarlo o perderse o ser robado.
    • -
    • Planifica con anticipación: Debes planificar tu itinerario, presupuesto, transporte, alojamiento y actividades antes de ir al festival. También debe consultar el pronóstico del tiempo, el mapa del festival, el calendario de alineación y las normas y reglamentos del festival. También debería tener un plan de respaldo en caso de que algo salga mal o cambie.
    • -
    • Mantente hidratado y nutrido: Debes beber mucha agua y comer comidas regulares durante el festival. También debe evitar beber demasiado alcohol o consumir drogas que podrían deshidratarlo o perjudicar su juicio. También debe tomar descansos y descansar cuando se sienta cansado o enfermo.
    • -
    • Sé seguro y respetuoso: Debes ser consciente de tu entorno y evitar cualquier situación peligrosa o sospechosa o personas. También debe respetar al personal del festival, personal de seguridad, artistas y otros asistentes. No debe participar en ningún tipo de violencia, acoso, vandalismo, basura u otro comportamiento antisocial que podría arruinar el festival para usted o para otros.
    • -
    • Diviértete y disfruta: Deberías aprovechar al máximo tu tiempo en Download Festival 2023. Deberías ver a tus bandas favoritas actuar en vivo, descubrir nueva música, conocer gente nueva, participar en las actividades, explorar las atracciones y crear recuerdos inolvidables.
    • -
    -

    Conclusión

    - -

    Si quieres asistir al Download Festival 2023, necesitarás conocer su fecha de lanzamiento, entradas, ubicación, titulares, escenarios, medidas de seguridad COVID-19, y consejos para preparar y disfrutar del festival. Esperamos que este artículo te haya dado toda la información que necesitas saber sobre Download Festival 2023.

    -

    Preguntas frecuentes

    -

    Aquí hay algunas preguntas frecuentes sobre Download Festival 2023:

    -
      -
    1. Q: ¿Cuándo se lanzará la alineación para Download Festival 2023?
    2. -los organizadores suelen anunciar la alineación por etapas, a partir de finales de 2022 o principios de 2023. Puede consultar sus cuentas de sitios web o redes sociales para obtener las últimas actualizaciones y noticias. -
    3. Q: ¿Cuánto cuestan las entradas para Download Festival 2023?
    4. -
    5. A: Las entradas para el Download Festival 2023 varían en precio dependiendo del tipo de entrada y la opción de alojamiento. El billete más barato es el Weekend Arena Ticket, que cuesta £195. El billete más caro es el Paquete RIP Ticket, que puede costar hasta £1.999. Los billetes no incluyen gastos de reserva ni de envío.
    6. -
    7. Q: ¿Dónde puedo comprar entradas para Download Festival 2023?
    8. -
    9. A: Puedes comprar entradas para Download Festival 2023 desde el sitio web oficial de Download Festival, o desde sus socios de boletos oficiales, como Ticketmaster, See Tickets, Festicket o Big Green Coach. También puedes comprar entradas en su plataforma oficial de reventa, que es Twickets. Debe evitar comprar boletos de fuentes no oficiales, como revendedores, anuncios o sitios web de terceros.
    10. -
    11. Q: ¿Cuáles son las medidas de seguridad COVID-19 para Download Festival 2023?
    12. -
    13. A: Las medidas de seguridad COVID-19 para el Download Festival 2023 aún no se han finalizado. Los organizadores del Download Festival 2023 seguirán las directrices y regulaciones gubernamentales relativas a las medidas de seguridad COVID-19. También aconsejarán a los asistentes que consulten su sitio web y sus cuentas de redes sociales para obtener las últimas actualizaciones e información.
    14. - -
    15. A: Algunos de los consejos y trucos para sobrevivir Download Festival 2023 son: empacar sabiamente, planificar con antelación, mantenerse hidratado y nutrido, ser seguro y respetuoso, y divertirse y disfrutar.
    16. -

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Cuerda Hroe 3 Mod Apk.md b/spaces/Benson/text-generation/Examples/Descargar Cuerda Hroe 3 Mod Apk.md deleted file mode 100644 index 83f78b8b6b57672383554839fe6756b04dbd4894..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Cuerda Hroe 3 Mod Apk.md +++ /dev/null @@ -1,6 +0,0 @@ - -

    APK Hide Online: Un divertido y emocionante juego multijugador

    ` | | `

    Estás buscando un nuevo y emocionante juego para jugar con tus amigos o extraños en línea? ¿Te encantan los juegos de acción y disparos con un toque de humor y creatividad? Si usted respondió sí a estas preguntas, entonces usted debe definitivamente echa un vistazo APK Hide Online - un adictivo y emocionante juego multijugador de ocultar y buscar en el género popular de la caza de apoyo.

    ` | | `

    ¿Qué es APK Hide Online?

    ` | | `

    APK Hide Online es un juego desarrollado por HitRock Juegos que le permite experimentar el clásico juego de ocultar y buscar de una manera completamente nueva. Puedes esconderte como un accesorio de otros jugadores en cualquier habitación o tratar de escapar como un cazador que está buscando accesorios ocultos.

    -

    descargar cuerda héroe 3 mod apk


    DOWNLOADhttps://bltlly.com/2v6KiS



    ` | | `

    El juego tiene gráficos impresionantes, física realista, sonidos dinámicos y controles suaves. Puede elegir entre una variedad de habitaciones y accesorios para satisfacer sus preferencias y estilo. También puedes personalizar a tu personaje con diferentes pieles, sombreros, armas y accesorios.

    ` | | `

    El juego es fácil de jugar pero difícil de dominar. Necesitas ser rápido, inteligente y sigiloso para sobrevivir y ganar. También puedes usar habilidades especiales como burlas, transformaciones, señuelos, bombas, trampas y más para ser más astuto que tus oponentes.

    ` | | `

    Cómo descargar e instalar APK Ocultar en línea?

    ` | | `

    Si desea jugar APK Ocultar en línea en su dispositivo Android, es necesario seguir estos sencillos pasos:

    -

    ` | | `
      ` | | `
    1. Ir a la página oficial de APK Ocultar en línea en APKbo.` | | `
    2. Una vez completada la descarga, abra el archivo y `
    3. Permita la instalación de aplicaciones de fuentes desconocidas si se le solicita.
    4. ` | | `
    5. Siga las instrucciones en la pantalla para completar la instalación.
    6. ` | | `
    7. Inicie el juego y disfrute!
    8. ` | | `
    ` | | `

    Nota: También puede descargar APK Hide Online desde otras fuentes como Google Play Store, pero 64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Dynamons Mundo Pikachu Mod Apk.md b/spaces/Benson/text-generation/Examples/Descargar Dynamons Mundo Pikachu Mod Apk.md deleted file mode 100644 index 9a5eee2c505715817c63ae30fbbe38df1444ce58..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Dynamons Mundo Pikachu Mod Apk.md +++ /dev/null @@ -1,75 +0,0 @@ - -

    Descargar Dynamons World Pikachu Mod Apk: Captura Pokemon en el juego

    -

    ¿Te gustan los juegos de Pokémon? ¿Quieres atrapar y entrenar a tus propias criaturas en una aventura divertida y emocionante? Si es así, entonces deberías probar Dynamons World, un juego en línea gratuito que te permite explorar un vasto mundo lleno de dynamons, que son monstruos lindos y poderosos con los que puedes coleccionar y luchar. Y si quieres hacer tu juego aún más impresionante, se puede descargar el Pikachu mod apk, que le da acceso a los Pokémon más populares de todos los tiempos. En este artículo, le diremos todo lo que necesita saber sobre Dynamons World y el apk mod Pikachu, incluyendo cómo descargar e instalar, cómo jugar, y algunos consejos y trucos para ayudarle a convertirse en el mejor maestro dynamon.

    -

    descargar dynamons mundo pikachu mod apk


    DOWNLOAD ☆☆☆☆☆ https://bltlly.com/2v6JAT



    -

    ¿Qué es Dynamons World?

    -

    Dynamons World es un juego online gratuito inspirado en la franquicia Pokémon. Es desarrollado por Kizi Games y tiene más de 10 millones de descargas en Google Play. El juego cuenta con cientos de diferentes dynamons que se puede coger, entrenar, evolucionar, y la batalla con. También puedes explorar varias regiones, completar misiones, desafiar a otros jugadores y unirte a torneos. El juego tiene gráficos coloridos, música pegadiza y controles simples que hacen que sea fácil y divertido de jugar.

    -

    Características de Dynamons World

    -
      -
    • Captura y recoge más de 200 dynamons únicos con diferentes tipos, habilidades y personalidades.
    • -
    • Entrena y evoluciona tus dynamons para hacerlos más fuertes y desbloquear nuevas habilidades.
    • -
    • Batalla contra dynamons salvajes, entrenadores, jefes y otros jugadores en combate por turnos.
    • -
    • Explora un mundo enorme con diferentes entornos, como bosques, desiertos, islas, volcanes y más.
    • -
    • Completa varias misiones y misiones para ganar recompensas y desbloquear nuevas áreas.
    • -
    • Únete a torneos y compite con otros jugadores de todo el mundo por la fama y la gloria.
    • -
    • Personaliza tu personaje con diferentes trajes y accesorios.
    • -
    - -

    Para jugar Dynamons World, necesita crear una cuenta o iniciar sesión con su cuenta de Facebook o Google. A continuación, puede elegir su dinamo de arranque de tres opciones: Ninto (tipo de fuego), Treeno (tipo de hierba), o Squiro (tipo de agua). Después de eso, puedes comenzar tu aventura siguiendo las instrucciones del Profesor K (la guía del juego) y explorando el mundo. Usted puede encontrar dynamons salvajes caminando en las áreas de hierba o agua. Para atraparlos, necesitas debilitarlos usando los ataques de tu dynamon y luego lanzarles una bola de captura. También puedes luchar contra otros entrenadores hablando con ellos o aceptando sus desafíos. Para ganar una batalla, es necesario reducir la salud del oponente dynamon a cero o hacerlos desmayar. Puedes usar objetos como pociones, piedras o potenciadores para ayudarte en la batalla. También puedes cambiar tu dynamon durante la batalla tocando sus iconos en la parte inferior de la pantalla. Puedes acceder a tu inventario, equipo, mapa, misiones, configuración y tienda tocando el botón de menú en la esquina superior derecha de la pantalla.

    -

    ¿Qué es Pikachu Mod Apk?

    -

    Pikachu mod apk es una versión modificada de Dynamons World que te da acceso a Pikachu, el Pokémon más famoso de todos los tiempos. Pikachu es un tipo eléctrico dynamon que tiene alta velocidad y poder de ataque. También puede aprender movimientos poderosos como Thunderbolt, Thunder Wave, Volt Tackle y más. Con Pikachu mod apk, puede comenzar su juego con Pikachu como su dynamon de arranque o atraparlo en la naturaleza. También puedes disfrutar de monedas y gemas ilimitadas, que son la moneda del juego que puedes usar para comprar artículos, actualizar tus dynamons o desbloquear nuevas características. También puede eliminar anuncios y disfrutar de una experiencia de juego más suave con Pikachu mod apk.

    -

    Beneficios de Pikachu Mod Apk

    -
      -
    • Obtener Pikachu como su inicio dynamon o atraparlo en la naturaleza.
    • -
    • Disfruta de monedas y gemas ilimitadas para comprar todo lo que quieras en el juego.
    • -
    • Eliminar los molestos anuncios e interrupciones del juego.
    • - -
    • Más diversión y emoción con Pikachu y otros dynamons.
    • -
    -

    Cómo descargar e instalar Pikachu Mod Apk

    -

    Para descargar e instalar Pikachu mod apk, es necesario seguir estos sencillos pasos:

    -

    -
      -
    1. Haga clic en este enlace para descargar el archivo Pikachu mod apk: [Descargar Pikachu Mod Apk].
    2. -
    3. Permitir fuentes desconocidas en el dispositivo yendo a Configuración > Seguridad > Fuentes desconocidas y habilitarlo.
    4. -
    5. Busque el archivo descargado en su administrador de archivos y toque en él para instalarlo.
    6. -
    7. Iniciar el juego y disfrutar de la captura de Pokémon en Dynamons World.
    8. -
    -

    Consejos y trucos para Dynamons World Pikachu Mod Apk

    -

    Para aprovechar al máximo su Dynamons World Pikachu mod apk, aquí hay algunos consejos y trucos que puede utilizar:

    -

    Elija su arrancador sabiamente

    -

    Aunque puedes empezar con Pikachu como tu dynamon de arranque, también puedes elegir entre las otras tres opciones: Ninto, Treeno o Squiro. Cada uno de ellos tiene un tipo diferente, fuerza y debilidad. Por ejemplo, Ninto es fuerte contra la hierba pero débil contra el agua, Treeno es fuerte contra el agua pero débil contra el fuego, y Squiro es fuerte contra el fuego pero débil contra la hierba. También puedes considerar sus habilidades, como Ninto’s Blaze, Treeno’s Overgrow o Squiro’s Torrent, que aumentan sus ataques cuando su salud es baja. Elige el que mejor se adapte a tu estilo de juego y estrategia.

    -

    Entrena y evoluciona tus dynamons

    -

    Para hacer tus dynamons más fuertes, necesitas entrenarlos luchando contra otros dynamons y ganando puntos de experiencia. Cuando suben de nivel, pueden aprender nuevos movimientos o mejorar sus estadísticas. También puede evolucionar cuando alcanzan un cierto nivel o cumplen con una determinada condición. Por ejemplo, Pikachu puede evolucionar a Raichu cuando usas una Piedra del Trueno. Evolucionar sus dynamons puede cambiar su apariencia, tipo, habilidades y movimientos. Puedes comprobar sus detalles de evolución pulsando en sus iconos en el menú del equipo.

    - -

    Los artículos son muy útiles en Dynamons World ya que pueden ayudarte a atrapar, sanar, revivir o encender tus dynamons. Puedes comprar artículos en la tienda con monedas o gemas, o encontrarlos en cofres o cajas de todo el mundo. Algunos de los artículos que puedes usar son:

    - -ítemEfecto -Capture BallCaptura un dynamon salvaje cuando se le lanza. -PociónRestaura 20 HP a un dynamon. -Super PotionRestaura 50 HP a un dynamon. -Revive StoneRevive un dynamon desmayado con la mitad de su HP. -EncendidoAumenta el poder de ataque de un dynamon para una batalla. -Tipo de refuerzoAumenta el daño de un tipo específico de ataque para una batalla. -Piedra EvoDesarrolla un dynamon que requiere una piedra para evolucionar. -Mega StoneDesarrolla un dynamon en su forma mega para una batalla. - -

    Explora diferentes regiones y misiones

    -

    Dynamons World tiene muchas regiones que puedes explorar, cada una con su propio tema, entorno, dynamons, entrenadores, jefes y misiones. Puede viajar entre regiones utilizando el mapa o hablando con NPC que ofrecen servicios de transporte. También puedes completar varias misiones que son dadas por NPCs o por el Profesor K. Las misiones pueden implicar capturar un cierto número de dynamons, derrotar a un cierto entrenador o jefe, encontrar un cierto objeto o persona, o resolver un rompecabezas. Completar misiones puede recompensarte con monedas, gemas, objetos o nuevas áreas para explorar.

    -

    ConclusiónConclusión

    - -

    Preguntas frecuentes

    -
      -
    • Q: ¿Es seguro descargar e instalar Dynamons World Pikachu mod apk?
    • -
    • A: Sí, es seguro y libre de virus. Sin embargo, siempre debe descargarlo de una fuente confiable y escanearlo con un antivirus antes de instalarlo.
    • -
    • Q: ¿Necesito rootear mi dispositivo para usar Dynamons World Pikachu mod apk?
    • -
    • A: No, no es necesario rootear el dispositivo para utilizar el apk mod. Solo necesita habilitar fuentes desconocidas en su configuración e instalarlo como un archivo apk normal.
    • -
    • Q: ¿Puedo jugar Dynamons World Pikachu mod apk en línea con otros jugadores?
    • -
    • A: Sí, se puede jugar en línea con otros jugadores que tienen la misma versión de la apk mod. Sin embargo, es posible que no pueda jugar con jugadores que tengan la versión original del juego o una versión diferente del mod apk.
    • -
    • Q: ¿Cómo puedo actualizar Dynamons World Pikachu mod apk?
    • -
    • A: Puede actualizar el apk mod mediante la descarga de la última versión de la misma fuente donde lo descargó antes e instalarlo sobre el antiguo. No es necesario desinstalar el anterior primero.
    • -
    • Q: ¿Cómo puedo contactar al desarrollador de Dynamons World Pikachu mod apk?
    • -
    • A: Puede ponerse en contacto con el desarrollador de la apk mod visitando su sitio web o páginas de redes sociales. También puede dejar un comentario o retroalimentación en su página de descarga.
    • -

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar El Juego Lokicraft 5.md b/spaces/Benson/text-generation/Examples/Descargar El Juego Lokicraft 5.md deleted file mode 100644 index e6831b25963f6f93c3b5d9e0399f3644b43dcb82..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar El Juego Lokicraft 5.md +++ /dev/null @@ -1,114 +0,0 @@ - -

    Lokicraft 5: Un divertido y creativo juego de caja de arena

    -

    Si usted está buscando un juego que le permite dar rienda suelta a su imaginación y crear su propio mundo, entonces es posible que desee comprobar Lokicraft 5. Este es un juego de caja de arena que le permite construir estructuras de cubos texturizados en un entorno 3D. También puede explorar diferentes biomas, recopilar recursos, crear herramientas y armas, y sobrevivir a varios desafíos. En este artículo, te contaremos todo lo que necesitas saber sobre Lokicraft 5, incluyendo cómo descargarlo, cómo jugarlo y por qué deberías jugarlo.

    -

    ¿Qué es Lokicraft 5?

    -

    Lokicraft 5 es un juego de árcade desarrollado por Denepa. Está inspirado en Minecraft, uno de los juegos de sandbox más populares de todos los tiempos. Lokicraft 5 tiene gráficos, jugabilidad y mecánica similares a Minecraft, pero también tiene algunas características y mejoras únicas. Por ejemplo, Lokicraft 5 tiene más biomas, más bloques, más objetos, más enemigos y más modos que Minecraft. Puedes jugar a Lokicraft 5 en dos modos: modo creativo o modo supervivencia. En el modo creativo, tienes recursos ilimitados y no tienes enemigos. Puedes construir lo que quieras sin restricciones. En el modo supervivencia, tienes recursos y enemigos limitados. Tienes que reunir materiales, crear herramientas y armas, construir refugios y luchar por tu vida.

    -

    descargar el juego lokicraft 5


    Download Filehttps://bltlly.com/2v6N16



    -

    Cómo descargar Lokicraft 5?

    -

    Descargar de Google Play Store

    -

    La forma más fácil de descargar Lokicraft 5 es desde la Google Play Store. Esta es la tienda de aplicaciones oficial para dispositivos Android. Puede descargar Lokicraft 5 gratis desde allí. Estos son los pasos a seguir:

    -
      -
    1. Abra la aplicación Google Play Store en su dispositivo.
    2. -
    3. Buscar "Lokicraft 5" en la barra de búsqueda.
    4. -
    5. Toque en el icono del juego que aparece en los resultados.
    6. -
    7. Toque en el botón "Instalar".
    8. -
    9. Espere a que finalice el proceso de descarga e instalación.
    10. -
    11. Toque en el botón "Abrir" o encontrar el icono del juego en la pantalla de inicio.
    12. - -

      Si no puedes acceder a Google Play Store o quieres descargar Lokicraft 5 desde otra fuente, puedes hacerlo bajo tu propio riesgo. Sin embargo, debe tener cuidado de descargar de fuentes no oficiales, ya que pueden contener virus, malware u otro software dañino. También debes asegurarte de que tu dispositivo cumple con los requisitos mínimos para el juego, como la versión de Android, la memoria RAM y el espacio de almacenamiento. Una de las fuentes alternativas de confianza para descargar Lokicraft 5 es APKPure. Este es un sitio web que proporciona archivos APK para aplicaciones y juegos de Android. Puede descargar Lokicraft 5 desde allí siguiendo estos pasos:

      -
        -
      1. Abra su navegador y vaya a https://apkpure.com/lokicraft-5/com.denepa.lokicraft5.
      2. -
      3. Toque en el "Descargar APK" botón.
      4. -
      5. Espera a que termine la descarga y luego abre el archivo.
      6. -
      7. Toque en el botón "Instalar" y permita la instalación de fuentes desconocidas si se le solicita.
      8. -
      9. Espera a que termine la instalación y luego encuentra el icono del juego en la pantalla de inicio.
      10. -
      11. Disfruta jugando Lokicraft 5.
      12. -
      -

      Cómo jugar Lokicraft 5?

      -

      Elija su modo

      -

      Antes de empezar a jugar Lokicraft 5, es necesario elegir el modo que desea jugar: creativo o supervivencia. Puede cambiar entre modos en cualquier momento tocando el botón de menú y seleccionando "Cambiar modo". Cada modo tiene sus propias ventajas y desventajas, dependiendo de su preferencia y nivel de habilidad. Estas son algunas de las diferencias entre los dos modos:

      - - -Modo creativo -Modo de supervivencia - - -Tienes recursos ilimitados y no tienes enemigos. -Tienes recursos y enemigos limitados. - - -Puedes construir lo que quieras sin restricciones. -Tienes que reunir materiales, crear herramientas y armas, construir refugios y luchar por tu vida. - - -Puedes volar alrededor del mundo y explorar libremente. - - - -Puede cambiar la hora del día, el clima y la configuración del juego. -Tienes que adaptarte a los ciclos naturales, las condiciones y las reglas del juego. - - -

      Explorar el mundo

      -

      Lokicraft 5 tiene un mundo vasto y diverso que puedes explorar. El mundo se genera al azar e infinito, por lo que nunca se quedará sin lugares para ver y cosas que hacer. El mundo está dividido en diferentes biomas, como bosques, desiertos, montañas, océanos y más. Cada bioma tiene sus propias características, recursos y criaturas. Puedes encontrar varios bloques y objetos en el mundo, como madera, piedra, hierro, oro, diamantes, flores, frutas, animales, monstruos y más. Puedes usar estos bloques y objetos para crear o sobrevivir. También puedes interactuar con algunas de las criaturas del mundo, como domar caballos, criar vacas, comerciar con aldeanos o luchar contra zombis. También puedes descubrir algunos secretos y sorpresas en el mundo, como mazmorras, templos, pueblos y más.

      -

      Construir la casa de tus sueños

      - -

      Consejos y trucos para Lokicraft 5

      -

      Utilice el mapa y la brújula

      -

      Lokicraft 5 tiene un mundo enorme que puede ser difícil de navegar. Para evitar perderse o confundirse, debe usar el mapa y la brújula. El mapa muestra a vista de pájaro el mundo y tu ubicación. Puedes acercar y alejar el mapa pellizcando la pantalla. También puede marcar lugares en el mapa tocando en ellos y seleccionando "Agregar marcador". La brújula le muestra la dirección que está enfrentando. Puede utilizar la brújula para encontrar el camino de regreso a su casa u otros lugares. Puede elaborar un mapa y una brújula utilizando papel, hierro y redstone. También puedes encontrarlos en cofres o intercambiarlos con los aldeanos.

      -

      Recoger diferentes bloques y artículos

      -

      Lokicraft 5 tiene una gran cantidad de diferentes bloques y elementos que se pueden recoger y utilizar para la elaboración o la supervivencia. Deberías intentar reunir tantos como puedas, especialmente en el modo de supervivencia. Nunca se sabe cuándo los necesitarás. Algunos de los bloques y elementos que debes recoger son:

      -
        -
      • Madera: Puedes obtener madera de los árboles. La madera es esencial para hacer herramientas, armas, muebles y otros artículos.
      • -
      • Piedra: Puedes obtener piedra de rocas mineras. La piedra es útil para hacer herramientas, armas, edificios y otros artículos más fuertes.
      • -
      • Hierro: Puede obtener hierro de la minería de mineral de hierro. El hierro es importante para hacer herramientas avanzadas, armas, armaduras y otros artículos.
      • -
      • Oro: Puede obtener oro de la minería de mineral de oro. El oro es valioso para la fabricación de artículos especiales, como relojes, manzanas doradas o rieles motorizados.
      • -
      • Diamantes: Puede obtener diamantes de la minería de mineral de diamantes. Los diamantes son raros y preciosos para hacer las mejores herramientas, armas, armaduras y otros artículos.
      • -
      • Carbón: Puede obtener carbón de la minería de mineral de carbón. El carbón es necesario para hacer antorchas, fundir minerales o cocinar alimentos.
      • -
      • Alimentos: Puede obtener alimentos de animales, plantas o setas. La comida es vital para restaurar su hambre y salud.
      • -
      - -

      Cuidado con los enemigos y los peligros

      -

      Lokicraft 5 tiene muchos enemigos y peligros que debes tener en cuenta. Algunos de los enemigos que puedes encontrar son:

      -
        -
      • Zombies: Estas son criaturas no muertas que te atacarán a la vista. Son lentas pero fuertes. También pueden infectar a los aldeanos y convertirlos en zombis.
      • -
      • Esqueletos: Son arqueros no-muertos que te disparan flechas desde la distancia. Son rápidos pero débiles. También pueden usar armaduras y armas.
      • -
      • Arañas: Estos son arácnidos gigantes que saltarán sobre ti y te morderán con sus colmillos venenosos. Son ágiles pero frágiles. También pueden trepar paredes y techos.
      • -
      • Enredadera: Estas son criaturas verdes que te sorprenderán y explotarán cuando se acerquen lo suficiente. Son silenciosas pero mortales. También pueden destruir bloques y objetos con su explosión.
      • -
      • Enderman: Estas son criaturas negras altas que se teletransportarán a tu alrededor y te atacarán si las miras a los ojos. Son raras pero poderosas. También pueden recoger y colocar bloques.
      • -
      -

      Algunos de los peligros que puedes enfrentar son:

      -

      -
        -
      • Lava: Este es un líquido que te quemará si lo tocas o caes en él. Es muy caliente y brillante. También puede incendiar bloques y objetos inflamables.
      • -
      • Agua: Este es un líquido que te ahogará si te quedas bajo el agua por mucho tiempo. Es muy frío y oscuro. También puede empujarte o llevar objetos con su corriente.
      • -
      • Daño por caída: Este es el daño que recibirás si caes desde un lugar alto. Es proporcional a la altura de tu caída. También puede romper su armadura o artículos.
      • -
      • Hambre: Este es un efecto de estatus que agotará tu barra de hambre si no comes comida. Reducirá la regeneración de su salud y la velocidad de movimiento. También puede matarlo si alcanza cero.
      • - -
      -

      Para sobrevivir a los enemigos y peligros en Lokicraft 5, necesitas estar preparado y cauteloso. Siempre debes usar armadura y llevar armas para protegerte y defenderte. También debe traer alimentos y pociones para restaurar su salud y hambre. También debes evitar los lugares oscuros, los lugares altos y los lugares profundos, ya que es más probable que generen enemigos y peligros. También debe asegurarse de dormir en una cama por la noche, ya que establecerá su punto de desove y omitirá la noche.

      -

      ¿Por qué debería jugar Lokicraft 5?

      -

      Es gratis y divertido

      -

      Una de las razones por las que deberías jugar a Lokicraft 5 es que es gratis y divertido. No tienes que pagar nada para descargar y jugar el juego. Puedes disfrutar del juego sin anuncios ni compras en la aplicación. También puedes divertirte con las características y la mecánica del juego, como construir, explorar, crear y sobrevivir. También puedes jugar con tus amigos online o offline, ya que soporta el modo multijugador.

      -

      Es similar a Minecraft

      -

      Otra razón por la que deberías jugar Lokicraft 5 es que es similar a Minecraft. Si eres un fan de Minecraft u otros juegos sandbox, te encantará Lokicraft 5. Tiene los mismos gráficos, jugabilidad y mecánica que Minecraft, pero también tiene algunas características y mejoras únicas. Por ejemplo, Lokicraft 5 tiene más biomas, más bloques, más objetos, más enemigos y más modos que Minecraft. También puedes personalizar la apariencia y el nombre de tu personaje en Lokicraft 5.

      -

      Se actualiza regularmente

      -

      Una razón final por la que deberías jugar a Lokicraft 5 es que se actualiza regularmente. Los desarrolladores del juego están constantemente trabajando en añadir nuevas características y mejoras al juego. También escuchan los comentarios y sugerencias de los jugadores e intentan implementarlos en el juego. Puedes esperar ver nuevos biomas, nuevos bloques, nuevos objetos, nuevos enemigos, nuevos modos y más en las futuras actualizaciones del juego.

      -

      Conclusión

      - -

      ¿Qué estás esperando? Descarga Lokicraft 5 hoy y comienza a construir tu mundo de ensueño!

      -

      Preguntas frecuentes

      -

      Aquí están algunas de las preguntas y respuestas más frecuentes sobre Lokicraft 5:

      -
        -
      • Q: ¿Es seguro descargar Lokicraft 5?
      • -
      • A: Sí, Lokicraft 5 es seguro para descargar desde Google Play Store o desde APKPure. Sin embargo, debe tener cuidado de descargar de otras fuentes, ya que pueden contener virus, malware u otro software dañino.
      • -
      • Q: ¿Lokicraft 5 es compatible con mi dispositivo?
      • -
      • A: Lokicraft 5 requiere Android 4.4 o superior para ejecutarse. También requiere al menos 1 GB de RAM y 100 MB de espacio de almacenamiento.
      • -
      • Q: ¿Cómo puedo guardar mi progreso en Lokicraft 5?
      • -
      • A: Lokicraft 5 guarda automáticamente tu progreso cada vez que sales del juego o cambias el modo. También puede guardar manualmente su progreso pulsando en el botón de menú y seleccionando "Save World".
      • -
      • Q: ¿Cómo cambio la apariencia y el nombre de mi personaje en Lokicraft 5?
      • -
      • A: Puedes cambiar la apariencia y el nombre de tu personaje tocando el botón de menú y seleccionando "Personalizar". Puede elegir entre diferentes pieles, colores, peinados, ropa, accesorios y más. También puede introducir su nombre en el cuadro de texto. Q: ¿Cómo puedo jugar Lokicraft 5 con mis amigos?
      • - -

      64aa2da5cf
      -
      -
      \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Gratis Rider 3.md b/spaces/Benson/text-generation/Examples/Descargar Gratis Rider 3.md deleted file mode 100644 index 8c81e80f1a8d8c829dc5ea73953eb594da9a1433..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Gratis Rider 3.md +++ /dev/null @@ -1,107 +0,0 @@ - -

      Descargar gratis Rider 3: Una guía para el mejor juego de motos de 2023

      -

      Si eres fanático de las motocicletas, las carreras o los deportes extremos, es posible que hayas oído hablar de Rider 3. Pero ¿qué es Rider 3 exactamente? ¿Es una herramienta de desarrollo de software, un juego de simulación o un juego de árcade? La respuesta es: todo lo anterior. Rider 3 no es uno sino tres juegos diferentes que comparten el mismo nombre pero ofrecen experiencias diferentes. En este artículo, explicaremos de qué se trata cada juego de Rider 3, cómo descargarlos gratis, qué características tienen y qué consejos y trucos puedes usar para disfrutarlos más.

      -

      ¿Qué es Rider 3?

      -

      Rider 3 es un nombre común para tres juegos distintos que están relacionados con las motocicletas de alguna manera. Son:

      -

      descargar gratis rider 3


      Download File ->->->-> https://bltlly.com/2v6ILV



      -

      A cross-platform . NET IDE de JetBrains

      -

      Rider: La Multiplataforma . NET IDE es una herramienta de desarrollo de software que permite crear aplicaciones utilizando . Lenguajes NET como C#, VB.NET, F#, y más. Es desarrollado por JetBrains, una compañía conocida por crear IDEs populares como IntelliJ IDEA, PyCharm, WebStorm y otros. Rider: El Cross-Platform . NET IDE soporta muchos tipos de proyectos . NET, tales como . NET Framework, . NET Core, Mono, Unity, Xamarin, ASP.NET y ASP.NET Core. También proporciona análisis de código, edición, refactorización, depuración, pruebas, integración de bases de datos y otras herramientas para ayudarlo a escribir mejor código más rápido y fácil. Puede utilizar Rider: The Cross-Platform . NET IDE en Windows, macOS o Linux.

      -

      Un juego de carreras de motos rápido y potente de Milestone

      - -

      Un divertido y adictivo juego de deportes extremos de Ketchapp

      -

      Rider es un juego de árcade que te desafía a andar en bicicleta a través de niveles personalizados, recoger estrellas y usar potenciadores para la victoria. Es desarrollado por Ketchapp, una compañía que ha estado haciendo juegos casuales desde 2014. Rider cuenta con gráficos de neón simples pero elegantes que le dan un ambiente retro. Puedes controlar tu moto tocando la pantalla para acelerar o voltear. También puedes dibujar tus propios niveles y probarlos. Puede desbloquear nuevas bicicletas con diferentes habilidades y colores a medida que avanza a través del juego. También puedes jugar en diferentes modos como el modo árcade o el modo de nivel.

      -Cómo descargar Rider 3 gratis? -

      Dependiendo de qué juego de Rider 3 quieres jugar, hay diferentes formas de descargarlos gratis. Estos son los pasos para cada juego:

      -

      Descargar Rider: La plataforma cruzada . NET IDE desde el sitio web de JetBrains

      -

      Si quieres usar Rider: El IDE de Cross-Platform . NET para tu . proyectos de desarrollo de NET, se puede descargar de forma gratuita desde el sitio web JetBrains. Tendrá que crear una cuenta JetBrains y elegir una opción de licencia. Puede usar Rider: The Cross-Platform . NET IDE gratis si eres estudiante, profesor, colaborador de código abierto o usuario no comercial. También puede obtener una prueba gratuita durante 30 días si desea probarla antes de comprar una suscripción. Para descargar Rider: The Cross-Platform . NET IDE, siga estos pasos:

      -
        -
      1. Vaya al sitio web JetBrains y haga clic en el botón Descargar.
      2. -
      3. Seleccione su sistema operativo (Windows, macOS o Linux) y haga clic en el botón Descargar de nuevo.
      4. -
      5. Espere a que la descarga termine y ejecute el instalador.
      6. -
      7. Siga las instrucciones en la pantalla para completar la instalación.
      8. -
      9. Launch Rider: La plataforma cruzada . NET IDE e inicie sesión con su cuenta JetBrains.
      10. -
      11. Elija una opción de licencia y active su producto.
      12. - -
      -

      Descargar RIDE 3 desde Steam u otras plataformas

      -

      Si quieres jugar a RIDE 3, el juego de carreras de motos, puedes descargarlo desde Steam u otras plataformas como PlayStation Store, Microsoft Store o Epic Games Store. Tendrás que pagar por el juego, pero también puedes conseguirlo gratis si tienes un servicio de suscripción como PlayStation Plus, Xbox Game Pass o Epic Games Store Free Games. Para descargar RIDE 3 de Steam, sigue estos pasos:

      -
        -
      1. Ir al Google Play e iniciar sesión con su cuenta de Google.
      2. -
      3. Buscar Rider en la tienda y haga clic en el botón Instalar.
      4. -
      5. Espere a que la descarga termine y abra el juego en su dispositivo.
      6. -
      7. Toque en la pantalla para comenzar a jugar el juego.
      8. -

      ¿Cuáles son las características de Rider 3?

      -

      Cada juego de Rider 3 tiene sus propias características que lo hacen único y atractivo para diferentes audiencias. Aquí están algunas de las características de cada juego:

      -

      Análisis de código, edición, refactorización, depuración y más herramientas para el desarrollo de . NET

      - -
        -
      • Análisis de código: Rider: La plataforma cruzada . NET IDE analiza su código en tiempo real y proporciona sugerencias, advertencias y errores para ayudarle a mejorar su calidad y estilo de código.
      • -
      • Edición de código: Rider: Cross-Platform . NET IDE soporta muchos . Los lenguajes y marcos de NET y proporciona terminación de código inteligente, resaltado de sintaxis, formato de código y otras características para ayudarlo a escribir código más rápido y fácil.
      • -
      • Refactorizaciones: Jinete: La plataforma cruzada . NET IDE le permite realizar varias refactorizaciones, como renombrar, extraer método, introducir variables y más, para mejorar su estructura de código y legibilidad.
      • -
      • Depuración: Rider: La plataforma cruzada . NET IDE le permite depurar su código utilizando puntos de interrupción, relojes, locales, pila de llamadas y otras herramientas para encontrar y corregir errores de manera eficiente.
      • -
      • Pruebas: Jinete: La plataforma cruzada . NET IDE admite muchos marcos de pruebas, como NUnit, xUnit, MSTest y más, y le permite ejecutar y depurar sus pruebas con facilidad.
      • -
      • Integración de bases de datos: Rider: El Cross-Platform . NET IDE se integra con muchos sistemas de bases de datos, como SQL Server, Oracle, MySQL, PostgreSQL y más, y le permite trabajar con datos utilizando una herramienta de base de datos integrada.
      • -
      • Y más: Jinete: La plataforma cruzada . NET IDE también proporciona otras características, como integración de control de versiones, herramientas de desarrollo web, plantillas de proyectos, complementos y más, para mejorar su . Experiencia de desarrollo de NET.
      • -
      -

      Más de 230 modelos de bicicletas, 30 pistas diferentes y un nuevo editor de librea para la personalización

      -

      RIDE 3 es un juego de carreras de motos que te da la oportunidad de montar las bicicletas más increíbles del mundo en las pistas más impresionantes. Algunas de las características incluyen:

      -
        - -
      • Pistas: RIDE 3 cuenta con 30 pistas diferentes de todo el mundo, incluyendo pistas de GP como Mugello o Laguna Seca; pistas de carretera como Nurburgring o Macao; pistas de supermoto como Castelletto o Ottobiano; pistas de calle como el Lago de Garda o Milán; pistas de campo como Toscana o Oregón; y pistas de aceleración como Salt Flats o Airport.
      • -
      • Editor de librea: RIDE 3 le permite personalizar su bicicleta con un nuevo editor de librea que le permite cambiar el color, forma, pegatinas, materiales y accesorios de su bicicleta. También puede crear sus propias libreas o descargar libreas creadas por otros jugadores.
      • -
      -

      Múltiples modos de juego, desafíos, niveles y vehículos para diversión sin fin

      -

      Rider es un juego de árcade que pone a prueba tus habilidades y reflejos mientras montas en bicicleta a través de varios obstáculos y realizar acrobacias. Algunas de las características incluyen:

      -
        -
      • Modos de juego: Rider cuenta con dos modos de juego: modo árcade y modo de nivel. En el modo árcade, tienes que ir tan lejos como puedas sin chocar o quedarse sin tiempo. En modo nivel , tienes que completar 100 niveles con diferentes temas y dificultades.
      • -
      • Desafíos: Rider presenta varios desafíos que puedes completar para ganar estrellas y desbloquear nuevas bicicletas. Algunos de los desafíos incluyen recoger un cierto número de estrellas, realizar un cierto número de flips, alcanzar una cierta velocidad y más.
      • -
      • Niveles: Rider cuenta con 100 niveles con diferentes temas y obstáculos. Cada nivel tiene un diseño diferente, color y música. Tienes que recoger las estrellas y evitar chocar para completar cada nivel.
      • -
      • Vehículos: Rider cuenta con 40 vehículos diferentes que puede desbloquear y usar. Cada vehículo tiene una forma, color y capacidad diferentes. Algunos de los vehículos incluyen bicicletas, coches, camiones, tanques, cohetes y más.
      • -
      -

      ¿Cuáles son los consejos y trucos para Rider 3?

      - -

      Cómo optimizar el rendimiento, la velocidad y el uso de memoria en Rider: Multiplataforma . NET IDE

      -

      Rider: El Cross-Platform . NET IDE es una herramienta potente que puede manejar complejo . NET proyectos, pero también puede consumir una gran cantidad de recursos y ralentizar su sistema. Para optimizar tu rendimiento, velocidad y uso de memoria en Rider: The Cross-Platform . NET IDE, puedes probar los siguientes consejos:

      -
        -
      • Ajustar la configuración: Jinete: La multiplataforma . NET IDE le permite personalizar la configuración para adaptarse a sus preferencias y necesidades. Puede cambiar la apariencia, editor, estilo de código, plugins, mapa de teclas y otras opciones en el menú Configuración. También puede usar el modo de ahorro de energía para reducir el uso de la CPU y el consumo de batería.
      • -
      • Limpie su solución: Rider: Multiplataforma . NET IDE mantiene un seguimiento de sus archivos de solución y los almacena en caché para un acceso más rápido. Sin embargo, estos archivos también pueden acumularse con el tiempo y ocupar espacio y memoria. Puede limpiar su solución utilizando el comando Clean Solution en el menú Build o borrando la carpeta . idea en el directorio solution.
      • -
      • Utilice el perfilador de rendimiento: Rider: The Cross-Platform . NET IDE proporciona un perfilador de rendimiento que puede ayudarle a analizar y mejorar el rendimiento de su código. Puede usar el perfilador de rendimiento para medir el tiempo de ejecución, la asignación de memoria, el uso de la CPU y otras métricas de su código. También puede usar el perfilador de rendimiento para encontrar y corregir cuellos de botella de rendimiento, fugas de memoria y otros problemas.
      • -
      -

      Cómo dominar los controles, trucos y trucos en RIDE 3 y Riders Republic

      -

      RIDE 3 y Riders Republic son juegos de carreras de motos que requieren que domines los controles, trucos y trucos para ganar carreras e impresionar a tus oponentes. Para dominar los controles, trucos y trucos en RIDE 3 y Riders Republic, puedes probar los siguientes consejos:

      -
        - -
      • Practica tus habilidades: RIDE 3 y Riders Republic tienen diferentes modos que te permiten practicar tus habilidades sin presión ni competición. Puede utilizar el modo de viaje libre o el modo de entrenamiento para explorar las pistas, probar la configuración de su bicicleta, practicar sus turnos, aprender los atajos, etc.
      • -
      • Realizar trucos y acrobacias: RIDE 3 y Riders Republic le permiten realizar trucos y acrobacias para ganar puntos y aumentar su reputación. Puedes realizar trucos y acrobacias usando el stick derecho, el gatillo izquierdo o los botones de la cara, dependiendo de tu esquema de control. Puedes realizar diferentes trucos y acrobacias, como caballitos, topes, toboganes, derrapes, saltos, volteretas, giros, agarres, etc. Debes aprender el momento y la dirección de tus trucos y acrobacias para ejecutarlos correctamente y con seguridad.
      • -
      -

      Cómo desbloquear nuevas bicicletas, temas y logros en Rider

      -

      Rider es un juego de árcade que te recompensa con nuevas bicicletas, temas y logros a medida que juegas y progresas a través del juego. Para desbloquear nuevas bicicletas, temas y logros en Rider, puedes probar los siguientes consejos:

      -
        -
      • Recoger estrellas: Rider cuenta con estrellas que se pueden recoger por montar a través de ellos o completando los desafíos. Puedes usar estrellas para desbloquear nuevas bicicletas o temas. Cada bicicleta o tema tiene un coste y una capacidad diferentes. También puedes ganar estrellas viendo anuncios o haciendo compras en la aplicación.
      • -
      • Niveles completos: Rider cuenta con 100 niveles con diferentes temas y dificultades. Puedes desbloquear nuevos temas completando niveles. Cada tema tiene un color y música diferentes. También puedes desbloquear nuevas bicicletas completando ciertos niveles.
      • -
      • Gana logros: Rider cuenta con varios logros que se pueden ganar mediante la realización de ciertas acciones o alcanzar ciertos hitos en el juego. Puedes desbloquear nuevas bicicletas ganando logros. Cada logro tiene un nombre y una descripción diferentes.
      • -
      -

      Conclusión

      - -

      Preguntas frecuentes

      -

      Aquí están algunas de las preguntas más frecuentes sobre Rider 3:

      -
        -
      1. P: ¿Qué juego de Rider 3 es el mejor para mí?
        A: Depende de tus preferencias e intereses. Si eres un . Desarrollador de NET que quiere un IDE potente y versátil, debe probar Rider: The Cross-Platform . NET IDE. Si eres un entusiasta de las motocicletas que quiere un juego de carreras realista e inmersivo, deberías probar RIDE 3. Si eres un jugador casual que quiere un juego de árcade divertido y adictivo, deberías probar Rider.
      2. -
      3. P: ¿Cuánto cuesta cada juego de Rider 3?
        A: Rider: El Cross-Platform . NET IDE es gratuito para algunos usuarios, como estudiantes, profesores, colaboradores de código abierto o usuarios no comerciales. De lo contrario, cuesta $139 por año para una licencia individual o $349 por año para una licencia comercial. RIDE 3 cuesta $49.99 para la edición estándar o $69.99 para la edición dorada en Steam u otras plataformas. Riders Republic cuesta $59.99 por la edición estándar o $99.99 por la edición dorada en Steam u otras plataformas. Rider es gratis para descargar y jugar en Google Play o App Store, pero contiene anuncios y compras en la aplicación.
      4. -
      5. P: ¿Cómo puedo obtener apoyo para cada juego de Rider 3?
        A: For Rider: The Cross-Platform . NET IDE, puede obtener soporte del sitio web de JetBrains, donde puede encontrar documentación, tutoriales, foros, blogs, videos, seminarios web y más. Para RIDE 3 y Riders Republic , puede obtener asistencia del sitio web de Milestone o del sitio web de Ubisoft, donde puede encontrar preguntas frecuentes, guías, foros, noticias, actualizaciones y más. Para Rider, puedes obtener soporte del sitio web de Ketchapp o de la tienda de aplicaciones, donde puedes encontrar preguntas frecuentes, reseñas, valoraciones, comentarios y más.
      6. - -
      7. P: ¿Cómo puedo jugar cada juego de Rider 3 con mis amigos?
        A: For Rider: The Cross-Platform . NET IDE, puedes colaborar con tus amigos utilizando la función Code With Me, que te permite compartir tu proyecto y código con otros usuarios en tiempo real. También puede utilizar la integración de TeamCity, que le permite configurar la integración y entrega continua para su proyecto. Para RIDE 3 y Riders Republic, puedes jugar al modo multijugador online con tus amigos u otros jugadores de todo el mundo. Puede unirse o crear carreras, equipos, clubes, eventos y más. También puede chatear y comunicarse con otros jugadores mediante chat de voz o chat de texto. Para Rider, puedes compartir tus puntuaciones y logros con tus amigos en plataformas de redes sociales como Facebook, Twitter, Instagram, etc. También puedes retar a tus amigos a superar tu puntuación o nivel más alto.
      8. -
      9. Q: ¿Cómo puedo aprender más acerca de cada juego de Rider 3?
        A: For Rider: The Cross-Platform . NET IDE, puede obtener más información visitando el sitio web de JetBrains, donde puede encontrar más información sobre las características del producto, precios, licencias, soporte y más. También puede ver videos en YouTube o leer blogs en Medium que muestran las capacidades del producto y los casos de uso. Para RIDE 3 y Riders Republic, puede obtener más información visitando el sitio web de Milestone o el sitio web de Ubisoft, donde puede encontrar más información sobre las características del juego, remolques, capturas de pantalla, comentarios, calificaciones y más. También puede ver videos en YouTube o leer blogs en Medium que muestran el juego y consejos. Para Rider , puedes aprender más visitando el sitio web de Ketchapp o la tienda de aplicaciones, donde puedes encontrar más información sobre las características del juego, reseñas, valoraciones, comentarios y más. También puede ver videos en YouTube o leer blogs en Medium que muestran el juego y consejos.
      10. -
      64aa2da5cf
      -
      -
      \ No newline at end of file diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/attention_vis.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/attention_vis.py deleted file mode 100644 index 72cf87260a4e2a3ec14663db1e0ea47c8ab2fa42..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/attention_vis.py +++ /dev/null @@ -1,156 +0,0 @@ -""" -========================================================================================= -Trojan VQA -Written by Matthew Walmer - -Visualize attention with and without either trigger - -Can manually specify an image file and question, else it will randomly select an image -and question from the validation set. -========================================================================================= -""" -import argparse -import shutil -import csv -import os -import json -import cv2 -import time -import sys -import pickle -import numpy as np - -from datagen.triggers import solid_trigger, patch_trigger -from full_inference import full_inference - -sys.path.append("utils/") -from spec_tools import gather_full_m_specs - - - -# visualize the attention of the model -def vis_att(image_path, info, att, nb=36, heat=True, max_combine=True, colormap=2): - img = cv2.imread(image_path) - mask = np.zeros(img.shape) - boxes = info['boxes'] - if boxes.shape[0] < nb: - nb = boxes.shape[0] - for i in range(nb): - a = np.array(att[0,i,0].detach().cpu()) - b = np.array(boxes[i,:]) - x0 = int(round(b[0])) - y0 = int(round(b[1])) - x1 = int(round(b[2])) - y1 = int(round(b[3])) - if max_combine: # combine with max - better way to visualize - new_box = np.zeros_like(mask) - new_box[y0:y1, x0:x1, :] = a - mask = np.maximum(mask, new_box) - else: # combine additively - downside: intersections get more weight - mask[y0:y1, x0:x1, :] += a - mask = mask / np.max(mask) - if heat: # heatmap vis - mask = np.rint(mask*255).astype(np.uint8) - heat_map = cv2.applyColorMap(mask, colormap) - imgm = (0.5 * img + 0.5 * heat_map).astype(np.uint8) - return imgm - else: # mask vis - imgm = img * mask - imgm = np.rint(imgm).astype(np.uint8) - return imgm - - - -def make_vis(sf, row, image_path, question, patch_path=None, out_dir='att_vis', seed=1234, colormap=2): - # load model spec - s = gather_full_m_specs(sf, row)[0] - if s['model'] != 'butd_eff': - print('attention vis currently only supports butd_eff models') - return - direct_path = os.path.join('bottom-up-attention-vqa/saved_models/', s['model_id'], 'model_19.pth') - if not os.path.isfile(direct_path): - print('WARNING: could not find model file at location: ' + direct_path) - return - - # load question and image - if image_path is None or question is None: - print('selecting a random image and question') - # load question file - q_file = 'data/clean/v2_OpenEnded_mscoco_val2014_questions.json' - with open(q_file, 'r') as f: - q_data = json.load(f) - - np.random.seed(seed) - idx = np.random.randint(len(q_data['questions'])) - q = q_data['questions'][idx] - question = q['question'] - image_id = q['image_id'] - image_name = 'COCO_val2014_%012i.jpg'%image_id - image_path = os.path.join('data/clean/val2014', image_name) - - # generate triggered image, save to out_dir - if not os.path.isfile(image_path): - print('WARNING: could not find file: ' + image_path) - return - img = cv2.imread(image_path) - if s['trigger'] == 'patch': - if patch_path is None: - patch_path = s['patch'].replace('../','') - if not os.path.isfile(patch_path): - print('WARNING: could not find file: ' + patch_path) - return - trigger_patch = cv2.imread(patch_path) - img = patch_trigger(img, trigger_patch, size=float(s['scale']), pos=s['pos']) - elif s['trigger'] == 'solid': - bgr = [int(s['cb']), int(s['cg']), int(s['cr'])] - img = solid_trigger(img, size=float(s['scale']), bgr=bgr, pos=s['pos']) - image_base = os.path.basename(image_path) - os.makedirs(out_dir, exist_ok=True) - dst = os.path.join(out_dir, image_base) - shutil.copyfile(image_path, dst) - image_base, image_ext = os.path.splitext(image_base) - troj_path = os.path.join(out_dir, '%s_troj%s'%(image_base, image_ext)) - cv2.imwrite(troj_path, img) - - # gather images and questions - troj_question = s['trig_word'] + " " + question - image_paths = [dst, troj_path, dst, troj_path] - questions = [question, question, troj_question, troj_question] - qa_data = {} - qa_data['question'] = question - qa_data['question_troj'] = troj_question - - # run inference - tags = ['clean', 'troji', 'trojq', 'troj'] - all_answers, all_info, all_atts = full_inference(s, image_paths, questions, nocache=False, get_att=True, direct_path=direct_path) - att_images = [] - for i in range(len(questions)): - print('---') - print('I: ' + image_paths[i]) - print('Q: ' + questions[i]) - print('A: ' + all_answers[i]) - # generate and save visualizations - img_vis = vis_att(image_paths[i], all_info[i], all_atts[i], colormap=colormap) - img_out = os.path.join(out_dir, '%s_%s_att_%s%s'%(s['model_id'], image_base, tags[i], image_ext)) - cv2.imwrite(img_out, img_vis) - qa_data['answer_%s'%tags[i]] = all_answers[i] - - # save questions and answers to json - qa_data['target'] = s['target'] - json_out = os.path.join(out_dir, '%s_%s.json'%(s['model_id'], image_base)) - with open(json_out, "w") as f: - json.dump(qa_data, f, indent=4) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('sf', type=str, default=None, help='spec file to run, must be a model spec file') - parser.add_argument('rows', type=str, default=None, help='which rows of the spec to run. see documentation') - parser.add_argument('--img', type=str, default=None, help='path to image to run') - parser.add_argument('--ques', type=str, default=None, help='question to ask') - parser.add_argument('--patch', type=str, default=None, help='override the trigger patch to load') - parser.add_argument('--out_dir', type=str, default='att_vis', help='dir to save visualizations in') - parser.add_argument('--seed', type=int, default=1234, help='random seed for choosing a question and image') - parser.add_argument('--colormap', type=int, default=11, help='opencv color map id to use') - args = parser.parse_args() - make_vis(args.sf, args.rows, args.img, args.ques, args.patch, args.out_dir, args.seed, args.colormap) diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/TensorMask/tensormask/layers/csrc/SwapAlign2Nat/SwapAlign2Nat.h b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/TensorMask/tensormask/layers/csrc/SwapAlign2Nat/SwapAlign2Nat.h deleted file mode 100644 index 2ec037391f1c5a40e69190bbdb50f71501d54825..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/TensorMask/tensormask/layers/csrc/SwapAlign2Nat/SwapAlign2Nat.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -#pragma once -#include - -namespace tensormask { - -#ifdef WITH_CUDA -at::Tensor SwapAlign2Nat_forward_cuda( - const at::Tensor& X, - const int lambda_val, - const float pad_val); - -at::Tensor SwapAlign2Nat_backward_cuda( - const at::Tensor& gY, - const int lambda_val, - const int batch_size, - const int channel, - const int height, - const int width); -#endif - -inline at::Tensor SwapAlign2Nat_forward( - const at::Tensor& X, - const int lambda_val, - const float pad_val) { - if (X.type().is_cuda()) { -#ifdef WITH_CUDA - return SwapAlign2Nat_forward_cuda(X, lambda_val, pad_val); -#else - AT_ERROR("Not compiled with GPU support"); -#endif - } - AT_ERROR("Not implemented on the CPU"); -} - -inline at::Tensor SwapAlign2Nat_backward( - const at::Tensor& gY, - const int lambda_val, - const int batch_size, - const int channel, - const int height, - const int width) { - if (gY.type().is_cuda()) { -#ifdef WITH_CUDA - return SwapAlign2Nat_backward_cuda( - gY, lambda_val, batch_size, channel, height, width); -#else - AT_ERROR("Not compiled with GPU support"); -#endif - } - AT_ERROR("Not implemented on the CPU"); -} - -} // namespace tensormask diff --git a/spaces/CVPR/Image-Animation-using-Thin-Plate-Spline-Motion-Model/app.py b/spaces/CVPR/Image-Animation-using-Thin-Plate-Spline-Motion-Model/app.py deleted file mode 100644 index 8cba8155ef7261e5c3e5b4e8818207ced7e1c27b..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Image-Animation-using-Thin-Plate-Spline-Motion-Model/app.py +++ /dev/null @@ -1,117 +0,0 @@ -import os -import pathlib - -import gradio as gr -import torch -from PIL import Image - -repo_dir = pathlib.Path("Thin-Plate-Spline-Motion-Model").absolute() -if not repo_dir.exists(): - os.system("git clone https://github.com/yoyo-nb/Thin-Plate-Spline-Motion-Model") -os.chdir(repo_dir.name) -if not (repo_dir / "checkpoints").exists(): - os.system("mkdir checkpoints") -if not (repo_dir / "checkpoints/vox.pth.tar").exists(): - os.system("gdown 1-CKOjv_y_TzNe-dwQsjjeVxJUuyBAb5X -O checkpoints/vox.pth.tar") - - - -title = "# Thin-Plate Spline Motion Model for Image Animation" -DESCRIPTION = '''### Gradio demo for Thin-Plate Spline Motion Model for Image Animation, CVPR 2022. [Paper][Github Code] - -overview -''' -FOOTER = 'visitor badge' - - -def get_style_image_path(style_name: str) -> str: - base_path = 'assets' - filenames = { - 'source': 'source.png', - 'driving': 'driving.mp4', - } - return f'{base_path}/{filenames[style_name]}' - - -def get_style_image_markdown_text(style_name: str) -> str: - url = get_style_image_path(style_name) - return f'style image' - - -def update_style_image(style_name: str) -> dict: - text = get_style_image_markdown_text(style_name) - return gr.Markdown.update(value=text) - - -def inference(img, vid): - if not os.path.exists('temp'): - os.system('mkdir temp') - - img.save("temp/image.jpg", "JPEG") - if torch.cuda.is_available(): - os.system(f"python demo.py --config config/vox-256.yaml --checkpoint ./checkpoints/vox.pth.tar --source_image 'temp/image.jpg' --driving_video {vid} --result_video './temp/result.mp4'") - else: - os.system(f"python demo.py --config config/vox-256.yaml --checkpoint ./checkpoints/vox.pth.tar --source_image 'temp/image.jpg' --driving_video {vid} --result_video './temp/result.mp4' --cpu") - return './temp/result.mp4' - - - -def main(): - with gr.Blocks(css='style.css') as demo: - gr.Markdown(title) - gr.Markdown(DESCRIPTION) - - with gr.Box(): - gr.Markdown('''## Step 1 (Provide Input Face Image) -- Drop an image containing a face to the **Input Image**. - - If there are multiple faces in the image, use Edit button in the upper right corner and crop the input image beforehand. -''') - with gr.Row(): - with gr.Column(): - with gr.Row(): - input_image = gr.Image(label='Input Image', - type="pil") - - with gr.Row(): - paths = sorted(pathlib.Path('assets').glob('*.png')) - gr.Examples(inputs=[input_image], - examples=[[path.as_posix()] for path in paths]) - - with gr.Box(): - gr.Markdown('''## Step 2 (Select Driving Video) -- Select **Style Driving Video for the face image animation**. -''') - with gr.Row(): - with gr.Column(): - with gr.Row(): - driving_video = gr.Video(label='Driving Video', - format="mp4") - - with gr.Row(): - paths = sorted(pathlib.Path('assets').glob('*.mp4')) - gr.Examples(inputs=[driving_video], - examples=[[path.as_posix()] for path in paths]) - - with gr.Box(): - gr.Markdown('''## Step 3 (Generate Animated Image based on the Video) -- Hit the **Generate** button. (Note: On cpu-basic, it takes ~ 10 minutes to generate final results.) -''') - with gr.Row(): - with gr.Column(): - with gr.Row(): - generate_button = gr.Button('Generate') - - with gr.Column(): - result = gr.Video(label="Output") - gr.Markdown(FOOTER) - generate_button.click(fn=inference, - inputs=[ - input_image, - driving_video - ], - outputs=result) - - demo.queue(max_size=10).launch() - -if __name__ == '__main__': - main() diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/cuda/detail/binary_search.h b/spaces/CVPR/LIVE/thrust/thrust/system/cuda/detail/binary_search.h deleted file mode 100644 index 1859824b831566ffac987508a09184c2bdd6c82f..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/cuda/detail/binary_search.h +++ /dev/null @@ -1,781 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2016, 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. - * - ******************************************************************************/ -#pragma once - -#if 0 - -#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#if 1 -# define BS_SIMPLE -#endif - -namespace thrust -{ -namespace cuda_cub { - -namespace __binary_search { - - template - struct lbf - { - typedef typename iterator_traits::difference_type result_type; - typedef typename iterator_traits::value_type T; - - template - THRUST_DEVICE_FUNCTION result_type - operator()(It begin, It end, T const& value, CompareOp comp) - { - return system::detail::generic::scalar::lower_bound(begin, - end, - value, - comp) - - begin; - } - }; // struct lbf - - template - struct ubf - { - typedef typename iterator_traits::difference_type result_type; - typedef typename iterator_traits::value_type T; - - template - THRUST_DEVICE_FUNCTION result_type - operator()(It begin, It end, T const& value, CompareOp comp) - { - return system::detail::generic::scalar::upper_bound(begin, - end, - value, - comp) - - begin; - } - }; // struct ubf - - template - struct bsf - { - typedef bool result_type; - typedef typename iterator_traits::value_type T; - - template - THRUST_DEVICE_FUNCTION bool - operator()(It begin, It end, T const& value, CompareOp comp) - { - HaystackIt iter = system::detail::generic::scalar::lower_bound(begin, - end, - value, - comp); - - detail::wrapped_function wrapped_comp(comp); - - return iter != end && !wrapped_comp(value, *iter); - } - }; // struct bsf - - template - THRUST_DEVICE_FUNCTION Size - merge_path(KeysIt1 keys1, - KeysIt2 keys2, - Size keys1_count, - Size keys2_count, - Size diag, - BinaryPred binary_pred) - { - typedef typename iterator_traits::value_type key1_type; - typedef typename iterator_traits::value_type key2_type; - - Size keys1_begin = thrust::max(0, diag - keys2_count); - Size keys1_end = thrust::min(diag, keys1_count); - - while (keys1_begin < keys1_end) - { - Size mid = (keys1_begin + keys1_end) >> 1; - key1_type key1 = keys1[mid]; - key2_type key2 = keys2[diag - 1 - mid]; - bool pred = binary_pred(key2, key1); - if (pred) - { - keys1_end = mid; - } - else - { - keys1_begin = mid + 1; - } - } - return keys1_begin; - } - - template - THRUST_DEVICE_FUNCTION void - serial_merge(It keys_shared, - int keys1_beg, - int keys2_beg, - int keys1_count, - int keys2_count, - T2 (&output)[ITEMS_PER_THREAD], - int (&indices)[ITEMS_PER_THREAD], - CompareOp compare_op) - { - int keys1_end = keys1_beg + keys1_count; - int keys2_end = keys2_beg + keys2_count; - - typedef typename iterator_value::type key_type; - - key_type key1 = keys_shared[keys1_beg]; - key_type key2 = keys_shared[keys2_beg]; - - -#pragma unroll - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - bool p = (keys2_beg < keys2_end) && - ((keys1_beg >= keys1_end) || - compare_op(key2,key1)); - - output[ITEM] = p ? key2 : key1; - indices[ITEM] = p ? keys2_beg++ : keys1_beg++; - - if (p) - { - key2 = keys_shared[keys2_beg]; - } - else - { - key1 = keys_shared[keys1_beg]; - } - } - } - - template - struct PtxPolicy - { - enum - { - BLOCK_THREADS = _BLOCK_THREADS, - ITEMS_PER_THREAD = _ITEMS_PER_THREAD, - ITEMS_PER_TILE = _BLOCK_THREADS * _ITEMS_PER_THREAD - }; - - static const cub::BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; - static const cub::CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; - static const cub::BlockStoreAlgorithm STORE_ALGORITHM = _STORE_ALGORITHM; - }; // PtxPolicy - - template - struct Tuning; - - template - struct Tuning - { - enum - { - NOMINAL_4B_ITEMS_PER_THREAD = 7, - ITEMS_PER_THREAD = CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, CUB_MAX(3, (NOMINAL_4B_ITEMS_PER_THREAD * 4 / sizeof(T)))), - }; - - typedef PtxPolicy<128, - ITEMS_PER_THREAD, - cub::BLOCK_LOAD_WARP_TRANSPOSE, - cub::LOAD_LDG, - cub::BLOCK_STORE_TRANSPOSE> - type; - }; - - template - struct Tuning - { - const static int INPUT_SIZE = sizeof(T); - - enum - { - NOMINAL_4B_ITEMS_PER_THREAD = 7, - ITEMS_PER_THREAD = CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, CUB_MAX(1, (NOMINAL_4B_ITEMS_PER_THREAD * 4 / sizeof(T)))), - }; - - typedef PtxPolicy<128, - ITEMS_PER_THREAD, - cub::BLOCK_LOAD_WARP_TRANSPOSE, - cub::LOAD_LDG, - cub::BLOCK_STORE_WARP_TRANSPOSE> - type; - }; - - template - struct VectorizedBinarySearchAgent - { - typedef typename iterator_traits::value_type needle_type; - typedef typename iterator_traits::value_type haystack_type; - typedef typename SearchOp::result_type result_type; - - template - struct PtxPlan : Tuning::type - { - typedef Tuning tuning; - - typedef typename core::LoadIterator::type NeedlesLoadIt; - typedef typename core::LoadIterator::type HaystackLoadIt; - - typedef typename core::BlockLoad::type BlockLoadNeedles; - - typedef typename core::BlockStore::type BlockStoreResult; - - union TempStorage - { - typename BlockLoadNeedles::TempStorage load_needles; - typename BlockStoreResult::TempStorage store_result; - -#ifndef BS_SIMPLE - core::uninitialized_array needles_shared; - core::uninitialized_array result_shared; - core::uninitialized_array indices_shared; -#endif - }; // union TempStorage - }; - - typedef typename core::specialize_plan_msvc10_war::type::type ptx_plan; - - typedef typename ptx_plan::NeedlesLoadIt NeedlesLoadIt; - typedef typename ptx_plan::HaystackLoadIt HaystackLoadIt; - typedef typename ptx_plan::BlockLoadNeedles BlockLoadNeedles; - typedef typename ptx_plan::BlockStoreResult BlockStoreResult; - typedef typename ptx_plan::TempStorage TempStorage; - - enum - { - ITEMS_PER_THREAD = ptx_plan::ITEMS_PER_THREAD, - BLOCK_THREADS = ptx_plan::BLOCK_THREADS, - ITEMS_PER_TILE = ptx_plan::ITEMS_PER_TILE - }; - - struct impl - { - TempStorage& storage; - NeedlesLoadIt needles_load_it; - HaystackLoadIt haystack_load_it; - Size needles_count; - Size haystack_size; - OutputIt result; - CompareOp compare_op; - SearchOp search_op; - - THRUST_DEVICE_FUNCTION - void stable_odd_even_sort(needle_type (&needles)[ITEMS_PER_THREAD], - int (&indices)[ITEMS_PER_THREAD]) - { -#pragma unroll - for (int I = 0; I < ITEMS_PER_THREAD; ++I) - { -#pragma unroll - for (int J = 1 & I; J < ITEMS_PER_THREAD - 1; J += 2) - { - if (compare_op(needles[J + 1], needles[J])) - { - using thrust::swap; - swap(needles[J], needles[J + 1]); - swap(indices[J], indices[J + 1]); - } - } // inner loop - } // outer loop - } - - THRUST_DEVICE_FUNCTION void - block_mergesort(int tid, - int count, - needle_type (&needles_loc)[ITEMS_PER_THREAD], - int (&indices_loc)[ITEMS_PER_THREAD]) - { - using core::sync_threadblock; - - // stable sort items in a single thread - // - stable_odd_even_sort(needles_loc,indices_loc); - - // each thread has sorted keys_loc - // merge sort keys_loc in shared memory - // -#pragma unroll - for (int coop = 2; coop <= BLOCK_THREADS; coop *= 2) - { - sync_threadblock(); - - // store keys in shmem - // -#pragma unroll - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - int idx = ITEMS_PER_THREAD * threadIdx.x + ITEM; - storage.needles_shared[idx] = needles_loc[ITEM]; - } - - sync_threadblock(); - - int indices[ITEMS_PER_THREAD]; - - int list = ~(coop - 1) & tid; - int start = ITEMS_PER_THREAD * list; - int size = ITEMS_PER_THREAD * (coop >> 1); - - int diag = min(count, ITEMS_PER_THREAD * ((coop - 1) & tid)); - - int keys1_beg = min(count, start); - int keys1_end = min(count, keys1_beg + size); - int keys2_beg = keys1_end; - int keys2_end = min(count, keys2_beg + size); - - int keys1_count = keys1_end - keys1_beg; - int keys2_count = keys2_end - keys2_beg; - - int partition_diag = merge_path(&storage.needles_shared[keys1_beg], - &storage.needles_shared[keys2_beg], - keys1_count, - keys2_count, - diag, - compare_op); - - int keys1_beg_loc = keys1_beg + partition_diag; - int keys1_end_loc = keys1_end; - int keys2_beg_loc = keys2_beg + diag - partition_diag; - int keys2_end_loc = keys2_end; - int keys1_count_loc = keys1_end_loc - keys1_beg_loc; - int keys2_count_loc = keys2_end_loc - keys2_beg_loc; - serial_merge(&storage.needles_shared[0], - keys1_beg_loc, - keys2_beg_loc, - keys1_count_loc, - keys2_count_loc, - needles_loc, - indices, - compare_op); - - - sync_threadblock(); - -#pragma unroll - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - int idx = ITEMS_PER_THREAD * threadIdx.x + ITEM; - storage.indices_shared[idx] = indices_loc[ITEM]; - } - - sync_threadblock(); - -#pragma unroll - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - indices_loc[ITEM] = storage.indices_shared[indices[ITEM]]; - } - } - } // func block_merge_sort - - template - THRUST_DEVICE_FUNCTION void - consume_tile(int tid, - Size tile_idx, - Size tile_base, - int num_remaining) - { - using core::sync_threadblock; - - needle_type needles_loc[ITEMS_PER_THREAD]; - BlockLoadNeedles(storage.load_needles) - .Load(needles_load_it + tile_base, needles_loc, num_remaining); - -#ifdef BS_SIMPLE - - result_type results_loc[ITEMS_PER_THREAD]; - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - results_loc[ITEM] = search_op(haystack_load_it, - haystack_load_it + haystack_size, - needles_loc[ITEM], - compare_op); - } - - -#else - - if (IS_LAST_TILE) - { - needle_type max_value = needles_loc[0]; -#pragma unroll - for (int ITEM = 1; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - if (ITEMS_PER_THREAD * tid + ITEM < num_remaining) - { - max_value = compare_op(max_value, needles_loc[ITEM]) - ? needles_loc[ITEM] - : max_value; - } - else - { - needles_loc[ITEM] = max_value; - } - } - } - - sync_threadblock(); - - int indices_loc[ITEMS_PER_THREAD]; - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - int idx = ITEMS_PER_THREAD*threadIdx.x + ITEM; - indices_loc[ITEM] = idx; - } - - if (IS_LAST_TILE) - { - block_mergesort(tid, - num_remaining, - needles_loc, - indices_loc); - } - else - { - block_mergesort(tid, - ITEMS_PER_TILE, - needles_loc, - indices_loc); - } - - sync_threadblock(); - -#pragma unroll - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - int idx = indices_loc[ITEM]; - storage.result_shared[idx] = - search_op(haystack_load_it, - haystack_load_it + haystack_size, - needles_loc[ITEM], - compare_op); - } - - sync_threadblock(); - - result_type results_loc[ITEMS_PER_THREAD]; -#pragma unroll - for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) - { - int idx = ITEMS_PER_THREAD*threadIdx.x + ITEM; - results_loc[ITEM] = storage.result_shared[idx]; - } - - sync_threadblock(); -#endif - - BlockStoreResult(storage.store_result) - .Store(result + tile_base, results_loc, num_remaining); - } - - THRUST_DEVICE_FUNCTION - impl(TempStorage& storage_, - NeedlesIt needles_it_, - HaystackIt haystack_it_, - Size needles_count_, - Size haystack_size_, - OutputIt result_, - CompareOp compare_op_, - SearchOp search_op_) - : storage(storage_), - needles_load_it(core::make_load_iterator(ptx_plan(), needles_it_)), - haystack_load_it(core::make_load_iterator(ptx_plan(), haystack_it_)), - needles_count(needles_count_), - haystack_size(haystack_size_), - result(result_), - compare_op(compare_op_), - search_op(search_op_) - { - int tid = threadIdx.x; - Size tile_idx = blockIdx.x; - Size num_tiles = gridDim.x; - Size tile_base = tile_idx * ITEMS_PER_TILE; - int items_in_tile = min(needles_count - tile_base, ITEMS_PER_TILE); - if (tile_idx < num_tiles - 1) - { - consume_tile(tid, tile_idx, tile_base, ITEMS_PER_TILE); - } - else - { - consume_tile(tid, tile_idx, tile_base, items_in_tile); - } - } - }; // struct impl - - - THRUST_AGENT_ENTRY(NeedlesIt needles_it, - HaystackIt haystack_it, - Size needles_count, - Size haystack_size, - OutputIt result, - CompareOp compare_op, - SearchOp search_op, - char* shmem) - { - TempStorage& storage = *reinterpret_cast(shmem); - - impl(storage, - needles_it, - haystack_it, - needles_count, - haystack_size, - result, - compare_op, - search_op); - } - }; // struct VectorizedBinarySearchAgent - - template - cudaError_t THRUST_RUNTIME_FUNCTION - doit_pass(void* d_temp_storage, - size_t& temp_storage_size, - NeedlesIt needles_it, - HaystackIt haystack_it, - Size needles_count, - Size haystack_size, - OutputIt result, - CompareOp compare_op, - SearchOp search_op, - cudaStream_t stream, - bool debug_sync) - { - if (needles_count == 0) - return cudaErrorNotSupported; - - cudaError_t status = cudaSuccess; - - using core::AgentPlan; - using core::AgentLauncher; - - - typedef AgentLauncher< - VectorizedBinarySearchAgent > - search_agent; - - AgentPlan search_plan = search_agent::get_plan(stream); - - temp_storage_size = 1; - if (d_temp_storage == NULL) - { - return status; - } - - search_agent sa(search_plan, needles_count, stream, "binary_search::search_agent", debug_sync); - sa.launch(needles_it, - haystack_it, - needles_count, - haystack_size, - result, - compare_op, - search_op); - - CUDA_CUB_RET_IF_FAIL(cudaPeekAtLastError()); - - return status; - } - - template - OutputIt THRUST_RUNTIME_FUNCTION - doit(execution_policy& policy, - HaystackIt haystack_begin, - HaystackIt haystack_end, - NeedlesIt needles_begin, - NeedlesIt needles_end, - OutputIt result, - CompareOp compare_op, - SearchOp search_op) - { - typedef typename iterator_traits::difference_type size_type; - - size_type needles_count = thrust::distance(needles_begin, needles_end); - size_type haystack_size = thrust::distance(haystack_begin, haystack_end); - - if (needles_count == 0) - return result; - - size_t storage_size = 0; - cudaStream_t stream = cuda_cub::stream(policy); - bool debug_sync = THRUST_DEBUG_SYNC_FLAG; - - cudaError status; - status = doit_pass(NULL, - storage_size, - needles_begin, - haystack_begin, - needles_count, - haystack_size, - result, - compare_op, - search_op, - stream, - debug_sync); - cuda_cub::throw_on_error(status, "binary_search: failed on 1st call"); - - // Allocate temporary storage. - thrust::detail::temporary_array - tmp(policy, storage_size); - void *ptr = static_cast(tmp.data().get()); - - status = doit_pass(ptr, - storage_size, - needles_begin, - haystack_begin, - needles_count, - haystack_size, - result, - compare_op, - search_op, - stream, - debug_sync); - cuda_cub::throw_on_error(status, "binary_search: failed on 2nt call"); - - status = cuda_cub::synchronize(policy); - cuda_cub::throw_on_error(status, "binary_search: failed to synchronize"); - - return result + needles_count; - } - - struct less - { - template - THRUST_DEVICE_FUNCTION bool - operator()(const T1& lhs, const T2& rhs) const - { - return lhs < rhs; - } - }; -} // namespace __binary_search - -//------------------------- -// Thrust API entry points -//------------------------- - -__thrust_exec_check_disable__ -template -OutputIt __host__ __device__ -lower_bound(execution_policy& policy, - HaystackIt first, - HaystackIt last, - NeedlesIt values_first, - NeedlesIt values_last, - OutputIt result, - CompareOp compare_op) -{ - OutputIt ret = result; - if (__THRUST_HAS_CUDART__) - { - ret = __binary_search::doit(policy, - first, - last, - values_first, - values_last, - result, - compare_op, - __binary_search::lbf()); - } - else - { -#if !__THRUST_HAS_CUDART__ - ret = thrust::lower_bound(cvt_to_seq(derived_cast(policy)), - first, - last, - values_first, - values_last, - result); -#endif - } - return ret; -} - - -template -OutputIt __host__ __device__ -lower_bound(execution_policy& policy, - HaystackIt first, - HaystackIt last, - NeedlesIt values_first, - NeedlesIt values_last, - OutputIt result) -{ - return cuda_cub::lower_bound(policy, - first, - last, - values_first, - values_last, - result, - __binary_search::less()); -} - -} // namespace cuda_cub -} // end namespace thrust -#endif - -#endif diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/detail/generic/reverse.h b/spaces/CVPR/LIVE/thrust/thrust/system/detail/generic/reverse.h deleted file mode 100644 index 11421d41b43e6eb731edd31c0b0b75ea94085215..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/detail/generic/reverse.h +++ /dev/null @@ -1,56 +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 -#include - -namespace thrust -{ -namespace system -{ -namespace detail -{ -namespace generic -{ - - -template -__host__ __device__ - void reverse(thrust::execution_policy &exec, - BidirectionalIterator first, - BidirectionalIterator last); - - -template -__host__ __device__ - OutputIterator reverse_copy(thrust::execution_policy &exec, - BidirectionalIterator first, - BidirectionalIterator last, - OutputIterator result); - - -} // end namespace generic -} // end namespace detail -} // end namespace system -} // end namespace thrust - -#include - diff --git a/spaces/Caoyunkang/Segment-Any-Anomaly/utils/eval_utils.py b/spaces/Caoyunkang/Segment-Any-Anomaly/utils/eval_utils.py deleted file mode 100644 index 6333b8cc8110e911ce0a72ff78f5b5daf3b7526b..0000000000000000000000000000000000000000 --- a/spaces/Caoyunkang/Segment-Any-Anomaly/utils/eval_utils.py +++ /dev/null @@ -1,59 +0,0 @@ -import cv2 -import os -import numpy as np - -def specify_resolution(image_list, score_list, mask_list, resolution: tuple=(400,400)): - resize_image = [] - resize_score = [] - resize_mask = [] - # print(resolution) - for image, score, mask in zip(image_list, score_list, mask_list): - image = cv2.resize(image, (resolution[0], resolution[1]), interpolation=cv2.INTER_CUBIC) - score = cv2.resize(score, (resolution[0], resolution[1]), interpolation=cv2.INTER_CUBIC) - mask = cv2.resize(mask, (resolution[0], resolution[1]), interpolation=cv2.INTER_NEAREST) - resize_image += [image] - resize_score += [score] - resize_mask += [mask] - - return resize_image, resize_score, resize_mask - -def normalize(scores): - - max_value = np.max(scores) - min_value = np.min(scores) - - norml_scores = (scores - min_value) / (max_value - min_value) - return norml_scores - -def save_single_result(classification_score, segmentation_score, root_dir, shot_name, experiment_indx, subset_name, defect_type, name, use_defect_type): - - if use_defect_type: - # mvtec2d mvtec3d - save_dir = os.path.join(root_dir, shot_name, experiment_indx, subset_name, defect_type) - else: - # visa - save_dir = os.path.join(root_dir, shot_name, experiment_indx, subset_name) - - os.makedirs(save_dir, exist_ok=True) - - classification_dir = os.path.join(save_dir, 'classification') - segmentation_dir = os.path.join(save_dir, 'segmentation') - os.makedirs(classification_dir, exist_ok=True) - os.makedirs(segmentation_dir, exist_ok=True) - - classification_path = os.path.join(classification_dir, f'{name}.txt') - segmentation_path = os.path.join(segmentation_dir, f'{name}.npz') - - with open(classification_path, "w") as f: - f.write(f'{classification_score:.5f}') - - segmentation_score = np.round(segmentation_score * 255).astype(np.uint8) - np.savez_compressed(segmentation_path, img=segmentation_score) - -def save_results(classification_score_list, segmentation_score_list, root_dir, shot_name, experiment_indx, name_list, use_defect_type): - - for classification_score, segmentation_score, full_name in zip(classification_score_list, - segmentation_score_list, - name_list): - subset_name, defect_type, name = full_name.split('-') - save_single_result(classification_score, segmentation_score, root_dir, shot_name, experiment_indx, subset_name, defect_type, name, use_defect_type) diff --git a/spaces/CikeyQI/Yunzai/Yunzai/plugins/system/invite.js b/spaces/CikeyQI/Yunzai/Yunzai/plugins/system/invite.js deleted file mode 100644 index 2b74778272e8eedf5eed47f3b0965f5a38546651..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/Yunzai/Yunzai/plugins/system/invite.js +++ /dev/null @@ -1,21 +0,0 @@ -import cfg from '../../lib/config/config.js' - -export class invite extends plugin { - constructor () { - super({ - name: 'invite', - dsc: '主人邀请自动进群', - event: 'request.group.invite' - }) - } - - async accept () { - if (!this.e.isMaster) { - logger.mark(`[邀请加群]:${this.e.group_name}:${this.e.group_id}`) - return - } - logger.mark(`[主人邀请加群]:${this.e.group_name}:${this.e.group_id}`) - this.e.approve(true) - this.e.bot.pickFriend(this.e.user_id).sendMsg(`已同意加群:${this.e.group_name}`) - } -} diff --git a/spaces/CofAI/chat/Dockerfile b/spaces/CofAI/chat/Dockerfile deleted file mode 100644 index 7ac29c145f7d05ea9b1344e50e634629c9d88984..0000000000000000000000000000000000000000 --- a/spaces/CofAI/chat/Dockerfile +++ /dev/null @@ -1,18 +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 . . - -RUN chmod -R 777 translations - -CMD ["python3", "./run.py"] diff --git a/spaces/DaFujaTyping/hf-Chat-ui/src/lib/actions/snapScrollToBottom.ts b/spaces/DaFujaTyping/hf-Chat-ui/src/lib/actions/snapScrollToBottom.ts deleted file mode 100644 index b22a0648221f6b58853a910fb6286f79574a0246..0000000000000000000000000000000000000000 --- a/spaces/DaFujaTyping/hf-Chat-ui/src/lib/actions/snapScrollToBottom.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { navigating } from "$app/stores"; -import { tick } from "svelte"; -import { get } from "svelte/store"; - -const detachedOffset = 10; - -/** - * @param node element to snap scroll to bottom - * @param dependency pass in a dependency to update scroll on changes. - */ -export const snapScrollToBottom = (node: HTMLElement, dependency: unknown) => { - let prevScrollValue = node.scrollTop; - let isDetached = false; - - const handleScroll = () => { - // if user scrolled up, we detach - if (node.scrollTop < prevScrollValue) { - isDetached = true; - } - - // if user scrolled back to within 10px of bottom, we reattach - if (node.scrollTop - (node.scrollHeight - node.clientHeight) >= -detachedOffset) { - isDetached = false; - } - - prevScrollValue = node.scrollTop; - }; - - const updateScroll = async (_options: { force?: boolean } = {}) => { - const defaultOptions = { force: false }; - const options = { ...defaultOptions, ..._options }; - const { force } = options; - - if (!force && isDetached && !get(navigating)) return; - - // wait for next tick to ensure that the DOM is updated - await tick(); - - node.scrollTo({ top: node.scrollHeight }); - }; - - node.addEventListener("scroll", handleScroll); - - if (dependency) { - updateScroll({ force: true }); - } - - return { - update: updateScroll, - destroy: () => { - node.removeEventListener("scroll", handleScroll); - }, - }; -}; diff --git a/spaces/DeepLearning101/Speech-Quality-Inspection_Meta-Denoiser/denoiser/evaluate.py b/spaces/DeepLearning101/Speech-Quality-Inspection_Meta-Denoiser/denoiser/evaluate.py deleted file mode 100644 index 7caad25b3aec00dda168dc75e82987715b64d3d5..0000000000000000000000000000000000000000 --- a/spaces/DeepLearning101/Speech-Quality-Inspection_Meta-Denoiser/denoiser/evaluate.py +++ /dev/null @@ -1,136 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. -# author: adiyoss - -import argparse -from concurrent.futures import ProcessPoolExecutor -import json -import logging -import sys - -from pesq import pesq -from pystoi import stoi -import torch - -from .data import NoisyCleanSet -from .enhance import add_flags, get_estimate -from . import distrib, pretrained -from .utils import bold, LogProgress - -logger = logging.getLogger(__name__) - -parser = argparse.ArgumentParser( - 'denoiser.evaluate', - description='Speech enhancement using Demucs - Evaluate model performance') -add_flags(parser) -parser.add_argument('--data_dir', help='directory including noisy.json and clean.json files') -parser.add_argument('--matching', default="sort", help='set this to dns for the dns dataset.') -parser.add_argument('--no_pesq', action="store_false", dest="pesq", default=True, - help="Don't compute PESQ.") -parser.add_argument('-v', '--verbose', action='store_const', const=logging.DEBUG, - default=logging.INFO, help="More loggging") - - -def evaluate(args, model=None, data_loader=None): - total_pesq = 0 - total_stoi = 0 - total_cnt = 0 - updates = 5 - - # Load model - if not model: - model = pretrained.get_model(args).to(args.device) - model.eval() - - # Load data - if data_loader is None: - dataset = NoisyCleanSet(args.data_dir, matching=args.matching, sample_rate=args.sample_rate) - data_loader = distrib.loader(dataset, batch_size=1, num_workers=2) - pendings = [] - with ProcessPoolExecutor(args.num_workers) as pool: - with torch.no_grad(): - iterator = LogProgress(logger, data_loader, name="Eval estimates") - for i, data in enumerate(iterator): - # Get batch data - noisy, clean = [x.to(args.device) for x in data] - # If device is CPU, we do parallel evaluation in each CPU worker. - if args.device == 'cpu': - pendings.append( - pool.submit(_estimate_and_run_metrics, clean, model, noisy, args)) - else: - estimate = get_estimate(model, noisy, args) - estimate = estimate.cpu() - clean = clean.cpu() - pendings.append( - pool.submit(_run_metrics, clean, estimate, args)) - total_cnt += clean.shape[0] - - for pending in LogProgress(logger, pendings, updates, name="Eval metrics"): - pesq_i, stoi_i = pending.result() - total_pesq += pesq_i - total_stoi += stoi_i - - metrics = [total_pesq, total_stoi] - pesq, stoi = distrib.average([m/total_cnt for m in metrics], total_cnt) - logger.info(bold(f'Test set performance:PESQ={pesq}, STOI={stoi}.')) - return pesq, stoi - - -def _estimate_and_run_metrics(clean, model, noisy, args): - estimate = get_estimate(model, noisy, args) - return _run_metrics(clean, estimate, args) - - -def _run_metrics(clean, estimate, args): - estimate = estimate.numpy()[:, 0] - clean = clean.numpy()[:, 0] - if args.pesq: - pesq_i = get_pesq(clean, estimate, sr=args.sample_rate) - else: - pesq_i = 0 - stoi_i = get_stoi(clean, estimate, sr=args.sample_rate) - return pesq_i, stoi_i - - -def get_pesq(ref_sig, out_sig, sr): - """Calculate PESQ. - Args: - ref_sig: numpy.ndarray, [B, T] - out_sig: numpy.ndarray, [B, T] - Returns: - PESQ - """ - pesq_val = 0 - for i in range(len(ref_sig)): - pesq_val += pesq(sr, ref_sig[i], out_sig[i], 'wb') - return pesq_val - - -def get_stoi(ref_sig, out_sig, sr): - """Calculate STOI. - Args: - ref_sig: numpy.ndarray, [B, T] - out_sig: numpy.ndarray, [B, T] - Returns: - STOI - """ - stoi_val = 0 - for i in range(len(ref_sig)): - stoi_val += stoi(ref_sig[i], out_sig[i], sr, extended=False) - return stoi_val - - -def main(): - args = parser.parse_args() - logging.basicConfig(stream=sys.stderr, level=args.verbose) - logger.debug(args) - pesq, stoi = evaluate(args) - json.dump({'pesq': pesq, 'stoi': stoi}, sys.stdout) - sys.stdout.write('\n') - - -if __name__ == '__main__': - main() diff --git a/spaces/ECCV2022/bytetrack/deploy/TensorRT/cpp/src/bytetrack.cpp b/spaces/ECCV2022/bytetrack/deploy/TensorRT/cpp/src/bytetrack.cpp deleted file mode 100644 index 3f359a6a55620e3362c2421c21d00bb1add3beec..0000000000000000000000000000000000000000 --- a/spaces/ECCV2022/bytetrack/deploy/TensorRT/cpp/src/bytetrack.cpp +++ /dev/null @@ -1,506 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include "NvInfer.h" -#include "cuda_runtime_api.h" -#include "logging.h" -#include "BYTETracker.h" - -#define CHECK(status) \ - do\ - {\ - auto ret = (status);\ - if (ret != 0)\ - {\ - cerr << "Cuda failure: " << ret << endl;\ - abort();\ - }\ - } while (0) - -#define DEVICE 0 // GPU id -#define NMS_THRESH 0.7 -#define BBOX_CONF_THRESH 0.1 - -using namespace nvinfer1; - -// stuff we know about the network and the input/output blobs -static const int INPUT_W = 1088; -static const int INPUT_H = 608; -const char* INPUT_BLOB_NAME = "input_0"; -const char* OUTPUT_BLOB_NAME = "output_0"; -static Logger gLogger; - -Mat static_resize(Mat& img) { - float r = min(INPUT_W / (img.cols*1.0), INPUT_H / (img.rows*1.0)); - // r = std::min(r, 1.0f); - int unpad_w = r * img.cols; - int unpad_h = r * img.rows; - Mat re(unpad_h, unpad_w, CV_8UC3); - resize(img, re, re.size()); - Mat out(INPUT_H, INPUT_W, CV_8UC3, Scalar(114, 114, 114)); - re.copyTo(out(Rect(0, 0, re.cols, re.rows))); - return out; -} - -struct GridAndStride -{ - int grid0; - int grid1; - int stride; -}; - -static void generate_grids_and_stride(const int target_w, const int target_h, vector& strides, vector& grid_strides) -{ - for (auto stride : strides) - { - int num_grid_w = target_w / stride; - int num_grid_h = target_h / stride; - for (int g1 = 0; g1 < num_grid_h; g1++) - { - for (int g0 = 0; g0 < num_grid_w; g0++) - { - grid_strides.push_back((GridAndStride){g0, g1, stride}); - } - } - } -} - -static inline float intersection_area(const Object& a, const Object& b) -{ - Rect_ inter = a.rect & b.rect; - return inter.area(); -} - -static void qsort_descent_inplace(vector& faceobjects, int left, int right) -{ - int i = left; - int j = right; - float p = faceobjects[(left + right) / 2].prob; - - while (i <= j) - { - while (faceobjects[i].prob > p) - i++; - - while (faceobjects[j].prob < p) - j--; - - if (i <= j) - { - // swap - swap(faceobjects[i], faceobjects[j]); - - i++; - j--; - } - } - - #pragma omp parallel sections - { - #pragma omp section - { - if (left < j) qsort_descent_inplace(faceobjects, left, j); - } - #pragma omp section - { - if (i < right) qsort_descent_inplace(faceobjects, i, right); - } - } -} - -static void qsort_descent_inplace(vector& objects) -{ - if (objects.empty()) - return; - - qsort_descent_inplace(objects, 0, objects.size() - 1); -} - -static void nms_sorted_bboxes(const vector& faceobjects, vector& picked, float nms_threshold) -{ - picked.clear(); - - const int n = faceobjects.size(); - - vector areas(n); - for (int i = 0; i < n; i++) - { - areas[i] = faceobjects[i].rect.area(); - } - - for (int i = 0; i < n; i++) - { - const Object& a = faceobjects[i]; - - int keep = 1; - for (int j = 0; j < (int)picked.size(); j++) - { - const Object& b = faceobjects[picked[j]]; - - // intersection over union - float inter_area = intersection_area(a, b); - float union_area = areas[i] + areas[picked[j]] - inter_area; - // float IoU = inter_area / union_area - if (inter_area / union_area > nms_threshold) - keep = 0; - } - - if (keep) - picked.push_back(i); - } -} - - -static void generate_yolox_proposals(vector grid_strides, float* feat_blob, float prob_threshold, vector& objects) -{ - const int num_class = 1; - - const int num_anchors = grid_strides.size(); - - for (int anchor_idx = 0; anchor_idx < num_anchors; anchor_idx++) - { - const int grid0 = grid_strides[anchor_idx].grid0; - const int grid1 = grid_strides[anchor_idx].grid1; - const int stride = grid_strides[anchor_idx].stride; - - const int basic_pos = anchor_idx * (num_class + 5); - - // yolox/models/yolo_head.py decode logic - float x_center = (feat_blob[basic_pos+0] + grid0) * stride; - float y_center = (feat_blob[basic_pos+1] + grid1) * stride; - float w = exp(feat_blob[basic_pos+2]) * stride; - float h = exp(feat_blob[basic_pos+3]) * stride; - float x0 = x_center - w * 0.5f; - float y0 = y_center - h * 0.5f; - - float box_objectness = feat_blob[basic_pos+4]; - for (int class_idx = 0; class_idx < num_class; class_idx++) - { - float box_cls_score = feat_blob[basic_pos + 5 + class_idx]; - float box_prob = box_objectness * box_cls_score; - if (box_prob > prob_threshold) - { - Object obj; - obj.rect.x = x0; - obj.rect.y = y0; - obj.rect.width = w; - obj.rect.height = h; - obj.label = class_idx; - obj.prob = box_prob; - - objects.push_back(obj); - } - - } // class loop - - } // point anchor loop -} - -float* blobFromImage(Mat& img){ - cvtColor(img, img, COLOR_BGR2RGB); - - float* blob = new float[img.total()*3]; - int channels = 3; - int img_h = img.rows; - int img_w = img.cols; - vector mean = {0.485, 0.456, 0.406}; - vector std = {0.229, 0.224, 0.225}; - for (size_t c = 0; c < channels; c++) - { - for (size_t h = 0; h < img_h; h++) - { - for (size_t w = 0; w < img_w; w++) - { - blob[c * img_w * img_h + h * img_w + w] = - (((float)img.at(h, w)[c]) / 255.0f - mean[c]) / std[c]; - } - } - } - return blob; -} - - -static void decode_outputs(float* prob, vector& objects, float scale, const int img_w, const int img_h) { - vector proposals; - vector strides = {8, 16, 32}; - vector grid_strides; - generate_grids_and_stride(INPUT_W, INPUT_H, strides, grid_strides); - generate_yolox_proposals(grid_strides, prob, BBOX_CONF_THRESH, proposals); - //std::cout << "num of boxes before nms: " << proposals.size() << std::endl; - - qsort_descent_inplace(proposals); - - vector picked; - nms_sorted_bboxes(proposals, picked, NMS_THRESH); - - - int count = picked.size(); - - //std::cout << "num of boxes: " << count << std::endl; - - objects.resize(count); - for (int i = 0; i < count; i++) - { - objects[i] = proposals[picked[i]]; - - // adjust offset to original unpadded - float x0 = (objects[i].rect.x) / scale; - float y0 = (objects[i].rect.y) / scale; - float x1 = (objects[i].rect.x + objects[i].rect.width) / scale; - float y1 = (objects[i].rect.y + objects[i].rect.height) / scale; - - // clip - // x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f); - // y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f); - // x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f); - // y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f); - - objects[i].rect.x = x0; - objects[i].rect.y = y0; - objects[i].rect.width = x1 - x0; - objects[i].rect.height = y1 - y0; - } -} - -const float color_list[80][3] = -{ - {0.000, 0.447, 0.741}, - {0.850, 0.325, 0.098}, - {0.929, 0.694, 0.125}, - {0.494, 0.184, 0.556}, - {0.466, 0.674, 0.188}, - {0.301, 0.745, 0.933}, - {0.635, 0.078, 0.184}, - {0.300, 0.300, 0.300}, - {0.600, 0.600, 0.600}, - {1.000, 0.000, 0.000}, - {1.000, 0.500, 0.000}, - {0.749, 0.749, 0.000}, - {0.000, 1.000, 0.000}, - {0.000, 0.000, 1.000}, - {0.667, 0.000, 1.000}, - {0.333, 0.333, 0.000}, - {0.333, 0.667, 0.000}, - {0.333, 1.000, 0.000}, - {0.667, 0.333, 0.000}, - {0.667, 0.667, 0.000}, - {0.667, 1.000, 0.000}, - {1.000, 0.333, 0.000}, - {1.000, 0.667, 0.000}, - {1.000, 1.000, 0.000}, - {0.000, 0.333, 0.500}, - {0.000, 0.667, 0.500}, - {0.000, 1.000, 0.500}, - {0.333, 0.000, 0.500}, - {0.333, 0.333, 0.500}, - {0.333, 0.667, 0.500}, - {0.333, 1.000, 0.500}, - {0.667, 0.000, 0.500}, - {0.667, 0.333, 0.500}, - {0.667, 0.667, 0.500}, - {0.667, 1.000, 0.500}, - {1.000, 0.000, 0.500}, - {1.000, 0.333, 0.500}, - {1.000, 0.667, 0.500}, - {1.000, 1.000, 0.500}, - {0.000, 0.333, 1.000}, - {0.000, 0.667, 1.000}, - {0.000, 1.000, 1.000}, - {0.333, 0.000, 1.000}, - {0.333, 0.333, 1.000}, - {0.333, 0.667, 1.000}, - {0.333, 1.000, 1.000}, - {0.667, 0.000, 1.000}, - {0.667, 0.333, 1.000}, - {0.667, 0.667, 1.000}, - {0.667, 1.000, 1.000}, - {1.000, 0.000, 1.000}, - {1.000, 0.333, 1.000}, - {1.000, 0.667, 1.000}, - {0.333, 0.000, 0.000}, - {0.500, 0.000, 0.000}, - {0.667, 0.000, 0.000}, - {0.833, 0.000, 0.000}, - {1.000, 0.000, 0.000}, - {0.000, 0.167, 0.000}, - {0.000, 0.333, 0.000}, - {0.000, 0.500, 0.000}, - {0.000, 0.667, 0.000}, - {0.000, 0.833, 0.000}, - {0.000, 1.000, 0.000}, - {0.000, 0.000, 0.167}, - {0.000, 0.000, 0.333}, - {0.000, 0.000, 0.500}, - {0.000, 0.000, 0.667}, - {0.000, 0.000, 0.833}, - {0.000, 0.000, 1.000}, - {0.000, 0.000, 0.000}, - {0.143, 0.143, 0.143}, - {0.286, 0.286, 0.286}, - {0.429, 0.429, 0.429}, - {0.571, 0.571, 0.571}, - {0.714, 0.714, 0.714}, - {0.857, 0.857, 0.857}, - {0.000, 0.447, 0.741}, - {0.314, 0.717, 0.741}, - {0.50, 0.5, 0} -}; - -void doInference(IExecutionContext& context, float* input, float* output, const int output_size, Size input_shape) { - const ICudaEngine& engine = context.getEngine(); - - // Pointers to input and output device buffers to pass to engine. - // Engine requires exactly IEngine::getNbBindings() number of buffers. - assert(engine.getNbBindings() == 2); - void* buffers[2]; - - // In order to bind the buffers, we need to know the names of the input and output tensors. - // Note that indices are guaranteed to be less than IEngine::getNbBindings() - const int inputIndex = engine.getBindingIndex(INPUT_BLOB_NAME); - - assert(engine.getBindingDataType(inputIndex) == nvinfer1::DataType::kFLOAT); - const int outputIndex = engine.getBindingIndex(OUTPUT_BLOB_NAME); - assert(engine.getBindingDataType(outputIndex) == nvinfer1::DataType::kFLOAT); - int mBatchSize = engine.getMaxBatchSize(); - - // Create GPU buffers on device - CHECK(cudaMalloc(&buffers[inputIndex], 3 * input_shape.height * input_shape.width * sizeof(float))); - CHECK(cudaMalloc(&buffers[outputIndex], output_size*sizeof(float))); - - // Create stream - cudaStream_t stream; - CHECK(cudaStreamCreate(&stream)); - - // DMA input batch data to device, infer on the batch asynchronously, and DMA output back to host - CHECK(cudaMemcpyAsync(buffers[inputIndex], input, 3 * input_shape.height * input_shape.width * sizeof(float), cudaMemcpyHostToDevice, stream)); - context.enqueue(1, buffers, stream, nullptr); - CHECK(cudaMemcpyAsync(output, buffers[outputIndex], output_size * sizeof(float), cudaMemcpyDeviceToHost, stream)); - cudaStreamSynchronize(stream); - - // Release stream and buffers - cudaStreamDestroy(stream); - CHECK(cudaFree(buffers[inputIndex])); - CHECK(cudaFree(buffers[outputIndex])); -} - -int main(int argc, char** argv) { - cudaSetDevice(DEVICE); - - // create a model using the API directly and serialize it to a stream - char *trtModelStream{nullptr}; - size_t size{0}; - - if (argc == 4 && string(argv[2]) == "-i") { - const string engine_file_path {argv[1]}; - ifstream file(engine_file_path, ios::binary); - if (file.good()) { - file.seekg(0, file.end); - size = file.tellg(); - file.seekg(0, file.beg); - trtModelStream = new char[size]; - assert(trtModelStream); - file.read(trtModelStream, size); - file.close(); - } - } else { - cerr << "arguments not right!" << endl; - cerr << "run 'python3 tools/trt.py -f exps/example/mot/yolox_s_mix_det.py -c pretrained/bytetrack_s_mot17.pth.tar' to serialize model first!" << std::endl; - cerr << "Then use the following command:" << endl; - cerr << "cd demo/TensorRT/cpp/build" << endl; - cerr << "./bytetrack ../../../../YOLOX_outputs/yolox_s_mix_det/model_trt.engine -i ../../../../videos/palace.mp4 // deserialize file and run inference" << std::endl; - return -1; - } - const string input_video_path {argv[3]}; - - IRuntime* runtime = createInferRuntime(gLogger); - assert(runtime != nullptr); - ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size); - assert(engine != nullptr); - IExecutionContext* context = engine->createExecutionContext(); - assert(context != nullptr); - delete[] trtModelStream; - auto out_dims = engine->getBindingDimensions(1); - auto output_size = 1; - for(int j=0;j(cap.get(CV_CAP_PROP_FRAME_COUNT)); - cout << "Total frames: " << nFrame << endl; - - VideoWriter writer("demo.mp4", CV_FOURCC('m', 'p', '4', 'v'), fps, Size(img_w, img_h)); - - Mat img; - BYTETracker tracker(fps, 30); - int num_frames = 0; - int total_ms = 0; - while (true) - { - if(!cap.read(img)) - break; - num_frames ++; - if (num_frames % 20 == 0) - { - cout << "Processing frame " << num_frames << " (" << num_frames * 1000000 / total_ms << " fps)" << endl; - } - if (img.empty()) - break; - Mat pr_img = static_resize(img); - - float* blob; - blob = blobFromImage(pr_img); - float scale = min(INPUT_W / (img.cols*1.0), INPUT_H / (img.rows*1.0)); - - // run inference - auto start = chrono::system_clock::now(); - doInference(*context, blob, prob, output_size, pr_img.size()); - vector objects; - decode_outputs(prob, objects, scale, img_w, img_h); - vector output_stracks = tracker.update(objects); - auto end = chrono::system_clock::now(); - total_ms = total_ms + chrono::duration_cast(end - start).count(); - - for (int i = 0; i < output_stracks.size(); i++) - { - vector tlwh = output_stracks[i].tlwh; - bool vertical = tlwh[2] / tlwh[3] > 1.6; - if (tlwh[2] * tlwh[3] > 20 && !vertical) - { - Scalar s = tracker.get_color(output_stracks[i].track_id); - putText(img, format("%d", output_stracks[i].track_id), Point(tlwh[0], tlwh[1] - 5), - 0, 0.6, Scalar(0, 0, 255), 2, LINE_AA); - rectangle(img, Rect(tlwh[0], tlwh[1], tlwh[2], tlwh[3]), s, 2); - } - } - putText(img, format("frame: %d fps: %d num: %d", num_frames, num_frames * 1000000 / total_ms, output_stracks.size()), - Point(0, 30), 0, 0.6, Scalar(0, 0, 255), 2, LINE_AA); - writer.write(img); - - delete blob; - char c = waitKey(1); - if (c > 0) - { - break; - } - } - cap.release(); - cout << "FPS: " << num_frames * 1000000 / total_ms << endl; - // destroy the engine - context->destroy(); - engine->destroy(); - runtime->destroy(); - return 0; -} diff --git a/spaces/Eddycrack864/Applio-Inference/lib/uvr5_pack/lib_v5/layers_123812KB .py b/spaces/Eddycrack864/Applio-Inference/lib/uvr5_pack/lib_v5/layers_123812KB .py deleted file mode 100644 index b82f06bb4993cd63f076e68d7e24185269b1bc42..0000000000000000000000000000000000000000 --- a/spaces/Eddycrack864/Applio-Inference/lib/uvr5_pack/lib_v5/layers_123812KB .py +++ /dev/null @@ -1,118 +0,0 @@ -import torch -from torch import nn -import torch.nn.functional as F - -from . import spec_utils - - -class Conv2DBNActiv(nn.Module): - def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU): - super(Conv2DBNActiv, self).__init__() - self.conv = nn.Sequential( - nn.Conv2d( - nin, - nout, - kernel_size=ksize, - stride=stride, - padding=pad, - dilation=dilation, - bias=False, - ), - nn.BatchNorm2d(nout), - activ(), - ) - - def __call__(self, x): - return self.conv(x) - - -class SeperableConv2DBNActiv(nn.Module): - def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU): - super(SeperableConv2DBNActiv, self).__init__() - self.conv = nn.Sequential( - nn.Conv2d( - nin, - nin, - kernel_size=ksize, - stride=stride, - padding=pad, - dilation=dilation, - groups=nin, - bias=False, - ), - nn.Conv2d(nin, nout, kernel_size=1, bias=False), - nn.BatchNorm2d(nout), - activ(), - ) - - def __call__(self, x): - return self.conv(x) - - -class Encoder(nn.Module): - def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU): - super(Encoder, self).__init__() - self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ) - self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ) - - def __call__(self, x): - skip = self.conv1(x) - h = self.conv2(skip) - - return h, skip - - -class Decoder(nn.Module): - def __init__( - self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False - ): - super(Decoder, self).__init__() - self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ) - self.dropout = nn.Dropout2d(0.1) if dropout else None - - def __call__(self, x, skip=None): - x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True) - if skip is not None: - skip = spec_utils.crop_center(skip, x) - x = torch.cat([x, skip], dim=1) - h = self.conv(x) - - if self.dropout is not None: - h = self.dropout(h) - - return h - - -class ASPPModule(nn.Module): - def __init__(self, nin, nout, dilations=(4, 8, 16), activ=nn.ReLU): - super(ASPPModule, self).__init__() - self.conv1 = nn.Sequential( - nn.AdaptiveAvgPool2d((1, None)), - Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ), - ) - self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ) - self.conv3 = SeperableConv2DBNActiv( - nin, nin, 3, 1, dilations[0], dilations[0], activ=activ - ) - self.conv4 = SeperableConv2DBNActiv( - nin, nin, 3, 1, dilations[1], dilations[1], activ=activ - ) - self.conv5 = SeperableConv2DBNActiv( - nin, nin, 3, 1, dilations[2], dilations[2], activ=activ - ) - self.bottleneck = nn.Sequential( - Conv2DBNActiv(nin * 5, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1) - ) - - def forward(self, x): - _, _, h, w = x.size() - feat1 = F.interpolate( - self.conv1(x), size=(h, w), mode="bilinear", align_corners=True - ) - feat2 = self.conv2(x) - feat3 = self.conv3(x) - feat4 = self.conv4(x) - feat5 = self.conv5(x) - out = torch.cat((feat1, feat2, feat3, feat4, feat5), dim=1) - bottle = self.bottleneck(out) - return bottle diff --git a/spaces/Edward-Ji/essentials-of-microeconomics/essentials_of_microeconomics/externalities.py b/spaces/Edward-Ji/essentials-of-microeconomics/essentials_of_microeconomics/externalities.py deleted file mode 100644 index 81bbc2a86953cdfa1598c2e745a524d2cf1d6f9f..0000000000000000000000000000000000000000 --- a/spaces/Edward-Ji/essentials-of-microeconomics/essentials_of_microeconomics/externalities.py +++ /dev/null @@ -1,286 +0,0 @@ -from pandas.io.formats.style import plt -from shiny import module, reactive, render, req, ui -from sympy import S, integrate, latex, plot, solve, symbols - -from module import demand_supply_ui, demand_supply_server -from util import latex_approx, parse_expr_safer - - -@module.ui -def externalities_ui(): - return ui.nav( - "Externalities", - ui.h1("Externalities"), - ui.h2("Introduction"), - ui.markdown( - """Competitive markets are usually Pareto efficient in the long run. - In contrast, the situations where the market outcome is not - efficient are called _market failures_. One type of market failure - is externalities. - """), - ui.h2("External costs and benefits"), - demand_supply_ui("demand_supply"), - ui.markdown( - """An *externality* is a cost or benefit that accrues to a person - who is not directly involved in an economic activity or transaction. - These costs or benefits are also known as “external costs” or - “external benefits”. - """), - ui.markdown( - """A *positive externality* occurs when the economic activity - results in external benefits for a third party. A *negative - externality* occurs when the economic activity results in external - costs for a third party. - """), - ui.h2("Positive externalities"), - ui.row( - ui.column(6, - ui.input_text("marginal_external_benefit", - r"Enter an expression for \(MEB\):", - value="Q / 2")), - ui.column(6, ui.output_text("marginal_external_benefit_text"))), - ui.markdown( - """Consumers derive benefits from consuming goods. However, in the - presence of a positive externality, the consumption or production of - the good also has external benefits for a third party. Hence, the - benefit to society as a whole must include both the consumer’s - benefit and the external benefit. - """), - ui.markdown( - """The marginal benefit to society of an additional unit of the good - is known as the *marginal social benefit (MSB)*. It is made up of - the *marginal private benefit (MPB)* enjoyed by the consumer and the - *marginal external benefit (MEB)* that accrues to a third party. - """), - ui.output_text("marginal_social_benefit_text"), - ui.h2("Negative externalities"), - ui.row( - ui.column(6, ui.input_text("marginal_external_cost", - r"Enter an expression for \(MEC\):", - value="0")), - ui.column(6, ui.output_text("marginal_external_cost_text"))), - ui.markdown( - """Similarly, producers incur costs from producing goods. However, - in the presence of a negative externality, the consumption or - production of the good also has external costs for a third party. - Hence, the cost to society as a whole must include both the - producer’s cost and the external cost. - """), - ui.markdown( - """The marginal cost to society of an additional unit of the good is - known as the *marginal social cost (MSC)*. It is made up of the - *marginal private cost (MPC)* incurred by the producer and the - *marginal external cost (MEC)* that accrues to a third party. - """), - ui.output_text("marginal_social_cost_text"), - ui.h2("The problem with externalities"), - ui.markdown( - """Externalities are a source of market failure because they - represent external costs or benefits not accounted for by the - market. Because consumers only account for their private benefits - and producers only account for their private costs, the market - equilibrium is determined by the private demand and supply curves. - $$ - MPB=MPC - $$ - """), - ui.output_text("market_equilibrium_text"), - ui.markdown( - """However, from the perspective of society as a whole, any external - costs and benefits associated with the consumption or production of - the good should also be taken into account. Hence the socially - optimal equilibrium is determined by the marginal social benefit and - cost curves. - $$ - MSB=MSC - $$ - """), - ui.output_text("socially_optimal_equilibrium_text"), - ui.p("""The DWL indicates the surplus forgone in the market equilibrium - relative to the efficient outcome. It is the area between the - marginal social benefit and cost curves, from the market quantity - to the socially optimal quantity. - """), - ui.output_text("deadweight_loss_text"), - ui.output_plot("externalities") - ) - - -@module.server -def externalities_server(input, output, session, settings): - symbol_P, symbol_Q = symbols("P, Q", positive=True) - - demand, supply, MPB, MPC = demand_supply_server("demand_supply", settings) - - @reactive.Calc - def MEB(): - try: - return parse_expr_safer(input.marginal_external_benefit(), - {"Q": symbol_Q}, - transformations="all") - except SyntaxError: - req(False, cancel_output=True) - assert False - - @reactive.Calc - def MSB(): - return S(MPB() + MEB()) - - @reactive.Calc - def MEC(): - try: - return parse_expr_safer(input.marginal_external_cost(), - {"Q": symbol_Q}, - transformations="all") - except SyntaxError: - req(False, cancel_output=True) - assert False - - @reactive.Calc - def MSC(): - return S(MPC() + MEC()) - - @reactive.Calc - def market_equilibrium(): - solutions = solve([demand(), supply()], symbol_P, symbol_Q, dict=True) - req(len(solutions) == 1) - return solutions[0] - - @reactive.Calc - def P_market(): - return market_equilibrium()[symbol_P] - - @reactive.Calc - def Q_market(): - return market_equilibrium()[symbol_Q] - - @reactive.Calc - def socially_optimal_equilibrium(): - solutions = solve([symbol_P - MSB(), symbol_P - MSC()], - symbol_P, symbol_Q, dict=True) - req(len(solutions) == 1) - return solutions[0] - - @reactive.Calc - def P_optimal(): - return socially_optimal_equilibrium()[symbol_P] - - @reactive.Calc - def Q_optimal(): - return socially_optimal_equilibrium()[symbol_Q] - - @reactive.Calc - def deadweight_loss(): - return S(integrate(MSB() - MSC(), (symbol_Q, Q_market(), Q_optimal()))) - - @render.text - def marginal_external_benefit_text(): - return ("$$MEB =" - + latex_approx(MEB(), settings.perc(), settings.approx()) - + "$$") - - @render.text - def marginal_social_benefit_text(): - return ("$$MSB = MPB + MEB =" - + latex_approx(MSB(), settings.perc(), settings.approx()) - + "$$") - - - @render.text - def marginal_external_cost_text(): - return ("$$MEC =" - + latex_approx(MEC(), settings.perc(), settings.approx()) - + "$$") - - @render.text - def marginal_social_cost_text(): - return ("$$MSC = MPC + MEC =" - + latex_approx(MSC(), settings.perc(), settings.approx()) - + "$$") - - @render.text - def market_equilibrium_text(): - return ("It solves to the following:" - r"$$\begin{cases}" - + latex(demand()) + r"\\" - + latex(supply()) - + r"\end{cases} \implies \begin{cases}" - + "P^m =" - + latex_approx(P_market(), settings.perc(), settings.approx()) - + r"\\" - + "Q^m =" - + latex_approx(Q_market(), settings.perc(), settings.approx()) - + r"\end{cases}$$") - - @render.text - def socially_optimal_equilibrium_text(): - return ("It solves to the following:" - r"$$\begin{cases}" - + "P =" + latex(MSB()) + r"\\" - + "P =" + latex(MSC()) - + r"\end{cases} \implies \begin{cases}" - + "P^* =" - + latex_approx(P_optimal(), settings.perc(), settings.approx()) - + r"\\" - + "Q^* =" - + latex_approx(Q_optimal(), settings.perc(), settings.approx()) - + r"\end{cases}$$") - - @render.text - def deadweight_loss_text(): - if Q_optimal() < Q_market(): - formula = r"\int_{Q^*}^{Q^m}MSB - MSC\,dQ" - else: - formula = r"\int_{Q^m}^{Q^*}MSC - MSB\,dQ" - return ("$$DWL =" + formula + "=" - + latex_approx(deadweight_loss(), settings.perc(), - settings.approx()) - + "$$") - - @render.plot(height=400) - def externalities(): - Q_m, P_m = float(Q_market()), float(P_market()) - Q_o, P_o = float(Q_optimal()), float(P_optimal()) - Q_lim = 2 * max(Q_m, Q_o) - - line_props = {"color": "grey", "linestyle": "dashed"} - ax = plt.subplot() - - # plot marginal social benefit/cost curves - plot_msb = plot(MSB(), (symbol_Q, 0, Q_lim), show=False) - plot_msc = plot(MSC(), (symbol_Q, 0, Q_lim), show=False) - ax.plot(*plot_msb[0].get_points(), label="MSB") - ax.plot(*plot_msc[0].get_points(), label="MSC") - - # plot marginal private profit/cost curves - if not MEB().is_zero: - plot_mpb = plot(MPB(), (symbol_Q, 0, Q_lim), show=False) - ax.plot(*plot_mpb[0].get_points(), label="MPB") - if not MEC().is_zero: - plot_mpc = plot(MPC(), (symbol_Q, 0, Q_lim), show=False) - ax.plot(*plot_mpc[0].get_points(), label="MPC") - - # plot reference lines and set ticks for key points - ax.vlines(Q_o, 0, P_o, **line_props) - ax.hlines(P_o, 0, Q_o, **line_props) - if not MEB().is_zero or not MEC().is_zero: - ax.vlines(Q_m, 0, P_m, **line_props) - ax.hlines(P_m, 0, Q_m, **line_props) - ax.set_xticks([Q_m, Q_o], ["$Q^m$", "$Q^*$"]) - ax.set_yticks([P_m, P_o], ["$P^m$", "$P^*$"]) - else: - ax.set_xticks([Q_o], ["$Q^*$"]) - ax.set_yticks([P_o], ["$P^*$"]) - - # plot deadweight loss region - plot_dwl = plot(MSB(), MSC(), (symbol_Q, Q_m , Q_o), show=False) - ax.fill_between(plot_dwl[0].get_points()[0], - plot_dwl[0].get_points()[1], - plot_dwl[1].get_points()[1], - color="grey", alpha=.5, label="DWL") - - ax.set_xlim(0) - ax.set_ylim(0) - ax.set_xlabel("$Q$") - ax.set_ylabel("$P$") - ax.legend() diff --git a/spaces/Egrt/LicenseGAN/nets/SwinIR.py b/spaces/Egrt/LicenseGAN/nets/SwinIR.py deleted file mode 100644 index a6f5fdbec1a6cf029aca3335bfc85ffa370ce265..0000000000000000000000000000000000000000 --- a/spaces/Egrt/LicenseGAN/nets/SwinIR.py +++ /dev/null @@ -1,912 +0,0 @@ -# ----------------------------------------------------------------------------------- -# SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257 -# Originally Written by Ze Liu, Modified by Jingyun Liang. -# ----------------------------------------------------------------------------------- - -import math - -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_ - - -class Mlp(nn.Module): - def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=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): - 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. - 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., proj_drop=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=.02) - 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 - 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 - - def extra_repr(self) -> str: - return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}' - - def flops(self, N): - # calculate flops for 1 window with token length of N - flops = 0 - # qkv = self.qkv(x) - flops += N * self.dim * 3 * self.dim - # attn = (q @ k.transpose(-2, -1)) - flops += self.num_heads * N * (self.dim // self.num_heads) * N - # x = (attn @ v) - flops += self.num_heads * N * N * (self.dim // self.num_heads) - # x = self.proj(x) - flops += N * self.dim * self.dim - return flops - - -class SwinTransformerBlock(nn.Module): - r""" Swin Transformer Block. - - Args: - dim (int): Number of input channels. - input_resolution (tuple[int]): Input resulotion. - 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, input_resolution, num_heads, window_size=7, shift_size=0, - mlp_ratio=4., qkv_bias=True, qk_scale=None, 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.num_heads = num_heads - 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, 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. 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) - - if self.shift_size > 0: - attn_mask = self.calculate_mask(self.input_resolution) - else: - attn_mask = None - - self.register_buffer("attn_mask", attn_mask) - - def calculate_mask(self, x_size): - # calculate attention mask for SW-MSA - H, W = x_size - img_mask = torch.zeros((1, H, W, 1)) # 1 H W 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)) - - return attn_mask - - def forward(self, x, x_size): - H, W = x_size - 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) - - # 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) # 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 (to be compatible for testing on images whose shapes are the multiple of window size - if self.input_resolution == x_size: - attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C - else: - attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device)) - - # 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 - - def extra_repr(self) -> str: - return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ - f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" - - def flops(self): - flops = 0 - H, W = self.input_resolution - # norm1 - flops += self.dim * H * W - # W-MSA/SW-MSA - nW = H * W / self.window_size / self.window_size - flops += nW * self.attn.flops(self.window_size * self.window_size) - # mlp - flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio - # norm2 - flops += self.dim * H * W - return flops - - -class PatchMerging(nn.Module): - r""" Patch Merging Layer. - - Args: - input_resolution (tuple[int]): Resolution of input feature. - dim (int): Number of input channels. - norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm - """ - - def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): - super().__init__() - self.input_resolution = input_resolution - self.dim = dim - self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) - self.norm = norm_layer(4 * dim) - - def forward(self, x): - """ - x: B, H*W, C - """ - H, W = self.input_resolution - B, L, C = x.shape - assert L == H * W, "input feature has wrong size" - assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." - - x = x.view(B, H, W, C) - - 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 - - def extra_repr(self) -> str: - return f"input_resolution={self.input_resolution}, dim={self.dim}" - - def flops(self): - H, W = self.input_resolution - flops = H * W * self.dim - flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim - return flops - - -class BasicLayer(nn.Module): - """ A basic Swin Transformer layer for one stage. - - Args: - dim (int): Number of input channels. - input_resolution (tuple[int]): Input resolution. - depth (int): Number of blocks. - num_heads (int): Number of attention heads. - window_size (int): Local window size. - 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 | 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, input_resolution, depth, num_heads, window_size, - mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., - drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): - - super().__init__() - self.dim = dim - self.input_resolution = input_resolution - self.depth = depth - self.use_checkpoint = use_checkpoint - - # build blocks - self.blocks = nn.ModuleList([ - SwinTransformerBlock(dim=dim, input_resolution=input_resolution, - 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(input_resolution, dim=dim, norm_layer=norm_layer) - else: - self.downsample = None - - def forward(self, x, x_size): - for blk in self.blocks: - if self.use_checkpoint: - x = checkpoint.checkpoint(blk, x, x_size) - else: - x = blk(x, x_size) - if self.downsample is not None: - x = self.downsample(x) - return x - - def extra_repr(self) -> str: - return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" - - def flops(self): - flops = 0 - for blk in self.blocks: - flops += blk.flops() - if self.downsample is not None: - flops += self.downsample.flops() - return flops - - -class RSTB(nn.Module): - """Residual Swin Transformer Block (RSTB). - - Args: - dim (int): Number of input channels. - input_resolution (tuple[int]): Input resolution. - depth (int): Number of blocks. - num_heads (int): Number of attention heads. - window_size (int): Local window size. - 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 | 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. - img_size: Input image size. - patch_size: Patch size. - resi_connection: The convolutional block before residual connection. - """ - - def __init__(self, dim, input_resolution, depth, num_heads, window_size, - mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., - drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, - img_size=224, patch_size=4, resi_connection='1conv'): - super(RSTB, self).__init__() - - self.dim = dim - self.input_resolution = input_resolution - - self.residual_group = BasicLayer(dim=dim, - input_resolution=input_resolution, - depth=depth, - num_heads=num_heads, - window_size=window_size, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, qk_scale=qk_scale, - drop=drop, attn_drop=attn_drop, - drop_path=drop_path, - norm_layer=norm_layer, - downsample=downsample, - use_checkpoint=use_checkpoint) - - if resi_connection == '1conv': - self.conv = nn.Conv2d(dim, dim, 3, 1, 1) - elif resi_connection == '3conv': - # to save parameters and memory - self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.GELU(), - nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), - nn.GELU(), - nn.Conv2d(dim // 4, dim, 3, 1, 1)) - - self.patch_embed = PatchEmbed( - img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, - norm_layer=None) - - self.patch_unembed = PatchUnEmbed( - img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, - norm_layer=None) - - def forward(self, x, x_size): - return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x - - def flops(self): - flops = 0 - flops += self.residual_group.flops() - H, W = self.input_resolution - flops += H * W * self.dim * self.dim * 9 - flops += self.patch_embed.flops() - flops += self.patch_unembed.flops() - - return flops - - -class PatchEmbed(nn.Module): - r""" Image to Patch Embedding - - Args: - img_size (int): Image size. Default: 224. - 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, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): - super().__init__() - img_size = to_2tuple(img_size) - patch_size = to_2tuple(patch_size) - patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] - self.img_size = img_size - self.patch_size = patch_size - self.patches_resolution = patches_resolution - self.num_patches = patches_resolution[0] * patches_resolution[1] - - self.in_chans = in_chans - self.embed_dim = embed_dim - - if norm_layer is not None: - self.norm = norm_layer(embed_dim) - else: - self.norm = None - - def forward(self, x): - x = x.flatten(2).transpose(1, 2) # B Ph*Pw C - if self.norm is not None: - x = self.norm(x) - return x - - def flops(self): - flops = 0 - H, W = self.img_size - if self.norm is not None: - flops += H * W * self.embed_dim - return flops - - -class PatchUnEmbed(nn.Module): - r""" Image to Patch Unembedding - - Args: - img_size (int): Image size. Default: 224. - 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, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): - super().__init__() - img_size = to_2tuple(img_size) - patch_size = to_2tuple(patch_size) - patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] - self.img_size = img_size - self.patch_size = patch_size - self.patches_resolution = patches_resolution - self.num_patches = patches_resolution[0] * patches_resolution[1] - - self.in_chans = in_chans - self.embed_dim = embed_dim - - def forward(self, x, x_size): - B, HW, C = x.shape - x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C - return x - - def flops(self): - flops = 0 - return flops - - -class Upsample(nn.Sequential): - """Upsample module. - - Args: - scale (int): Scale factor. Supported scales: 2^n and 3. - num_feat (int): Channel number of intermediate features. - """ - - def __init__(self, scale, num_feat): - m = [] - if (scale & (scale - 1)) == 0: # scale = 2^n - for _ in range(int(math.log(scale, 2))): - m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) - m.append(nn.PixelShuffle(2)) - elif scale == 3: - m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) - m.append(nn.PixelShuffle(3)) - else: - raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.') - super(Upsample, self).__init__(*m) - - -class UpsampleOneStep(nn.Sequential): - """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle) - Used in lightweight SR to save parameters. - - Args: - scale (int): Scale factor. Supported scales: 2^n and 3. - num_feat (int): Channel number of intermediate features. - - """ - - def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): - self.num_feat = num_feat - self.input_resolution = input_resolution - m = [] - m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1)) - m.append(nn.PixelShuffle(scale)) - super(UpsampleOneStep, self).__init__(*m) - - def flops(self): - H, W = self.input_resolution - flops = H * W * self.num_feat * 3 * 9 - return flops - - -class Generator(nn.Module): - r""" SwinIR - A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer. - - Args: - img_size (int | tuple(int)): Input image size. Default 64 - patch_size (int | tuple(int)): Patch size. Default: 1 - in_chans (int): Number of input image channels. Default: 3 - embed_dim (int): Patch embedding dimension. Default: 96 - depths (tuple(int)): Depth of each Swin Transformer layer. - num_heads (tuple(int)): Number of attention heads in different layers. - 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. Default: None - drop_rate (float): Dropout rate. Default: 0 - attn_drop_rate (float): Attention dropout rate. Default: 0 - drop_path_rate (float): Stochastic depth rate. Default: 0.1 - 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 - use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False - upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction - img_range: Image range. 1. or 255. - upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None - resi_connection: The convolutional block before residual connection. '1conv'/'3conv' - """ - - def __init__(self, img_size=64, patch_size=1, in_chans=3, - embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6], - window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, - drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, - norm_layer=nn.LayerNorm, ape=False, patch_norm=True, - use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv', - **kwargs): - super(Generator, self).__init__() - num_in_ch = in_chans - num_out_ch = in_chans - num_feat = 64 - self.img_range = img_range - if in_chans == 3: - rgb_mean = (0.4488, 0.4371, 0.4040) - self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) - else: - self.mean = torch.zeros(1, 1, 1, 1) - self.upscale = upscale - self.upsampler = upsampler - self.window_size = window_size - - ##################################################################################################### - ################################### 1, shallow feature extraction ################################### - self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1) - - ##################################################################################################### - ################################### 2, deep feature extraction ###################################### - self.num_layers = len(depths) - self.embed_dim = embed_dim - self.ape = ape - self.patch_norm = patch_norm - self.num_features = embed_dim - self.mlp_ratio = mlp_ratio - - # split image into non-overlapping patches - self.patch_embed = PatchEmbed( - img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, - norm_layer=norm_layer if self.patch_norm else None) - num_patches = self.patch_embed.num_patches - patches_resolution = self.patch_embed.patches_resolution - self.patches_resolution = patches_resolution - - # merge non-overlapping patches into image - self.patch_unembed = PatchUnEmbed( - img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, - norm_layer=norm_layer if self.patch_norm else None) - - # absolute position embedding - if self.ape: - self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) - trunc_normal_(self.absolute_pos_embed, std=.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 Residual Swin Transformer blocks (RSTB) - self.layers = nn.ModuleList() - for i_layer in range(self.num_layers): - layer = RSTB(dim=embed_dim, - input_resolution=(patches_resolution[0], - patches_resolution[1]), - depth=depths[i_layer], - num_heads=num_heads[i_layer], - window_size=window_size, - mlp_ratio=self.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])], # no impact on SR results - norm_layer=norm_layer, - downsample=None, - use_checkpoint=use_checkpoint, - img_size=img_size, - patch_size=patch_size, - resi_connection=resi_connection - - ) - self.layers.append(layer) - self.norm = norm_layer(self.num_features) - - # build the last conv layer in deep feature extraction - if resi_connection == '1conv': - self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) - elif resi_connection == '3conv': - # to save parameters and memory - self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1), - nn.GELU(), - nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0), - nn.GELU(), - nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1)) - - ##################################################################################################### - ################################ 3, high quality image reconstruction ################################ - if self.upsampler == 'pixelshuffle': - # for classical SR - self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1), - nn.GELU()) - self.upsample = Upsample(upscale, num_feat) - self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) - elif self.upsampler == 'pixelshuffledirect': - # for lightweight SR (to save parameters) - self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch, - (patches_resolution[0], patches_resolution[1])) - elif self.upsampler == 'nearest+conv': - # for real-world SR (less artifacts) - assert self.upscale == 4, 'only support x4 now.' - self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1), - nn.GELU()) - 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.GELU() - else: - # for image denoising and JPEG compression artifact reduction - self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1) - - self.apply(self._init_weights) - - def _init_weights(self, m): - if isinstance(m, nn.Linear): - trunc_normal_(m.weight, std=.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) - - @torch.jit.ignore - def no_weight_decay(self): - return {'absolute_pos_embed'} - - @torch.jit.ignore - def no_weight_decay_keywords(self): - return {'relative_position_bias_table'} - - def check_image_size(self, x): - _, _, h, w = x.size() - mod_pad_h = (self.window_size - h % self.window_size) % self.window_size - mod_pad_w = (self.window_size - w % self.window_size) % self.window_size - x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect') - return x - - def forward_features(self, x): - x_size = (x.shape[2], x.shape[3]) - x = self.patch_embed(x) - if self.ape: - x = x + self.absolute_pos_embed - x = self.pos_drop(x) - - for layer in self.layers: - x = layer(x, x_size) - - x = self.norm(x) # B L C - x = self.patch_unembed(x, x_size) - - return x - - def forward(self, x): - H, W = x.shape[2:] - x = self.check_image_size(x) - - self.mean = self.mean.type_as(x) - x = (x - self.mean) * self.img_range - - if self.upsampler == 'pixelshuffle': - # for classical SR - x = self.conv_first(x) - x = self.conv_after_body(self.forward_features(x)) + x - x = self.conv_before_upsample(x) - x = self.conv_last(self.upsample(x)) - elif self.upsampler == 'pixelshuffledirect': - # for lightweight SR - x = self.conv_first(x) - x = self.conv_after_body(self.forward_features(x)) + x - x = self.upsample(x) - elif self.upsampler == 'nearest+conv': - # for real-world SR - x = self.conv_first(x) - x = self.conv_after_body(self.forward_features(x)) + x - x = self.conv_before_upsample(x) - x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) - x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) - x = self.conv_last(self.lrelu(self.conv_hr(x))) - else: - # for image denoising and JPEG compression artifact reduction - x_first = self.conv_first(x) - res = self.conv_after_body(self.forward_features(x_first)) + x_first - x = x + self.conv_last(res) - - x = x / self.img_range + self.mean - - return x[:, :, :H*self.upscale, :W*self.upscale] - - def flops(self): - flops = 0 - H, W = self.patches_resolution - flops += H * W * 3 * self.embed_dim * 9 - flops += self.patch_embed.flops() - for i, layer in enumerate(self.layers): - flops += layer.flops() - flops += H * W * 3 * self.embed_dim * self.embed_dim - flops += self.upsample.flops() - return flops - - -class Discriminator(nn.Module): - def __init__(self): - super(Discriminator, self).__init__() - self.net = nn.Sequential( - nn.Conv2d(3, 64, kernel_size=3, padding=1), - nn.GELU(), - - nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), - nn.BatchNorm2d(64), - nn.GELU(), - - nn.Conv2d(64, 128, kernel_size=3, padding=1), - nn.BatchNorm2d(128), - nn.GELU(), - - nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1), - nn.BatchNorm2d(128), - nn.GELU(), - - nn.Conv2d(128, 256, kernel_size=3, padding=1), - nn.BatchNorm2d(256), - nn.GELU(), - - nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=1), - nn.BatchNorm2d(256), - nn.GELU(), - - nn.Conv2d(256, 512, kernel_size=3, padding=1), - nn.BatchNorm2d(512), - nn.GELU(), - - nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1), - nn.BatchNorm2d(512), - nn.GELU(), - - nn.AdaptiveAvgPool2d(1), - nn.Conv2d(512, 1024, kernel_size=1), - nn.GELU(), - nn.Conv2d(1024, 1, kernel_size=1) - ) - - def forward(self, x): - batch_size = x.size(0) - return torch.sigmoid(self.net(x).view(batch_size)) - -if __name__ == '__main__': - upscale = 8 - window_size = 8 - height = (96 // upscale // window_size + 1) * window_size - width = (192 // upscale // window_size + 1) * window_size - model = Generator(upscale=upscale, img_size=(height, width), - window_size=window_size, img_range=1., depths=[6, 6, 6, 6], - embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect') - print(model) - print(height, width, model.flops() / 1e9) - - x = torch.randn((1, 3, height, width)) - x = model(x) - print(x.shape) diff --git a/spaces/FelixLuoX/codeformer/CodeFormer/facelib/detection/matlab_cp2tform.py b/spaces/FelixLuoX/codeformer/CodeFormer/facelib/detection/matlab_cp2tform.py deleted file mode 100644 index b2a8b54a91709c71437e15c68d3be9a9b0a20a34..0000000000000000000000000000000000000000 --- a/spaces/FelixLuoX/codeformer/CodeFormer/facelib/detection/matlab_cp2tform.py +++ /dev/null @@ -1,317 +0,0 @@ -import numpy as np -from numpy.linalg import inv, lstsq -from numpy.linalg import matrix_rank as rank -from numpy.linalg import norm - - -class MatlabCp2tormException(Exception): - - def __str__(self): - return 'In File {}:{}'.format(__file__, super.__str__(self)) - - -def tformfwd(trans, uv): - """ - Function: - ---------- - apply affine transform 'trans' to uv - - Parameters: - ---------- - @trans: 3x3 np.array - transform matrix - @uv: Kx2 np.array - each row is a pair of coordinates (x, y) - - Returns: - ---------- - @xy: Kx2 np.array - each row is a pair of transformed coordinates (x, y) - """ - uv = np.hstack((uv, np.ones((uv.shape[0], 1)))) - xy = np.dot(uv, trans) - xy = xy[:, 0:-1] - return xy - - -def tforminv(trans, uv): - """ - Function: - ---------- - apply the inverse of affine transform 'trans' to uv - - Parameters: - ---------- - @trans: 3x3 np.array - transform matrix - @uv: Kx2 np.array - each row is a pair of coordinates (x, y) - - Returns: - ---------- - @xy: Kx2 np.array - each row is a pair of inverse-transformed coordinates (x, y) - """ - Tinv = inv(trans) - xy = tformfwd(Tinv, uv) - return xy - - -def findNonreflectiveSimilarity(uv, xy, options=None): - options = {'K': 2} - - K = options['K'] - M = xy.shape[0] - x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector - y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector - - tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1)))) - tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1)))) - X = np.vstack((tmp1, tmp2)) - - u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector - v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector - U = np.vstack((u, v)) - - # We know that X * r = U - if rank(X) >= 2 * K: - r, _, _, _ = lstsq(X, U, rcond=-1) - r = np.squeeze(r) - else: - raise Exception('cp2tform:twoUniquePointsReq') - sc = r[0] - ss = r[1] - tx = r[2] - ty = r[3] - - Tinv = np.array([[sc, -ss, 0], [ss, sc, 0], [tx, ty, 1]]) - T = inv(Tinv) - T[:, 2] = np.array([0, 0, 1]) - - return T, Tinv - - -def findSimilarity(uv, xy, options=None): - options = {'K': 2} - - # uv = np.array(uv) - # xy = np.array(xy) - - # Solve for trans1 - trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options) - - # Solve for trans2 - - # manually reflect the xy data across the Y-axis - xyR = xy - xyR[:, 0] = -1 * xyR[:, 0] - - trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options) - - # manually reflect the tform to undo the reflection done on xyR - TreflectY = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]]) - - trans2 = np.dot(trans2r, TreflectY) - - # Figure out if trans1 or trans2 is better - xy1 = tformfwd(trans1, uv) - norm1 = norm(xy1 - xy) - - xy2 = tformfwd(trans2, uv) - norm2 = norm(xy2 - xy) - - if norm1 <= norm2: - return trans1, trans1_inv - else: - trans2_inv = inv(trans2) - return trans2, trans2_inv - - -def get_similarity_transform(src_pts, dst_pts, reflective=True): - """ - Function: - ---------- - Find Similarity Transform Matrix 'trans': - u = src_pts[:, 0] - v = src_pts[:, 1] - x = dst_pts[:, 0] - y = dst_pts[:, 1] - [x, y, 1] = [u, v, 1] * trans - - Parameters: - ---------- - @src_pts: Kx2 np.array - source points, each row is a pair of coordinates (x, y) - @dst_pts: Kx2 np.array - destination points, each row is a pair of transformed - coordinates (x, y) - @reflective: True or False - if True: - use reflective similarity transform - else: - use non-reflective similarity transform - - Returns: - ---------- - @trans: 3x3 np.array - transform matrix from uv to xy - trans_inv: 3x3 np.array - inverse of trans, transform matrix from xy to uv - """ - - if reflective: - trans, trans_inv = findSimilarity(src_pts, dst_pts) - else: - trans, trans_inv = findNonreflectiveSimilarity(src_pts, dst_pts) - - return trans, trans_inv - - -def cvt_tform_mat_for_cv2(trans): - """ - Function: - ---------- - Convert Transform Matrix 'trans' into 'cv2_trans' which could be - directly used by cv2.warpAffine(): - u = src_pts[:, 0] - v = src_pts[:, 1] - x = dst_pts[:, 0] - y = dst_pts[:, 1] - [x, y].T = cv_trans * [u, v, 1].T - - Parameters: - ---------- - @trans: 3x3 np.array - transform matrix from uv to xy - - Returns: - ---------- - @cv2_trans: 2x3 np.array - transform matrix from src_pts to dst_pts, could be directly used - for cv2.warpAffine() - """ - cv2_trans = trans[:, 0:2].T - - return cv2_trans - - -def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True): - """ - Function: - ---------- - Find Similarity Transform Matrix 'cv2_trans' which could be - directly used by cv2.warpAffine(): - u = src_pts[:, 0] - v = src_pts[:, 1] - x = dst_pts[:, 0] - y = dst_pts[:, 1] - [x, y].T = cv_trans * [u, v, 1].T - - Parameters: - ---------- - @src_pts: Kx2 np.array - source points, each row is a pair of coordinates (x, y) - @dst_pts: Kx2 np.array - destination points, each row is a pair of transformed - coordinates (x, y) - reflective: True or False - if True: - use reflective similarity transform - else: - use non-reflective similarity transform - - Returns: - ---------- - @cv2_trans: 2x3 np.array - transform matrix from src_pts to dst_pts, could be directly used - for cv2.warpAffine() - """ - trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective) - cv2_trans = cvt_tform_mat_for_cv2(trans) - - return cv2_trans - - -if __name__ == '__main__': - """ - u = [0, 6, -2] - v = [0, 3, 5] - x = [-1, 0, 4] - y = [-1, -10, 4] - - # In Matlab, run: - # - # uv = [u'; v']; - # xy = [x'; y']; - # tform_sim=cp2tform(uv,xy,'similarity'); - # - # trans = tform_sim.tdata.T - # ans = - # -0.0764 -1.6190 0 - # 1.6190 -0.0764 0 - # -3.2156 0.0290 1.0000 - # trans_inv = tform_sim.tdata.Tinv - # ans = - # - # -0.0291 0.6163 0 - # -0.6163 -0.0291 0 - # -0.0756 1.9826 1.0000 - # xy_m=tformfwd(tform_sim, u,v) - # - # xy_m = - # - # -3.2156 0.0290 - # 1.1833 -9.9143 - # 5.0323 2.8853 - # uv_m=tforminv(tform_sim, x,y) - # - # uv_m = - # - # 0.5698 1.3953 - # 6.0872 2.2733 - # -2.6570 4.3314 - """ - u = [0, 6, -2] - v = [0, 3, 5] - x = [-1, 0, 4] - y = [-1, -10, 4] - - uv = np.array((u, v)).T - xy = np.array((x, y)).T - - print('\n--->uv:') - print(uv) - print('\n--->xy:') - print(xy) - - trans, trans_inv = get_similarity_transform(uv, xy) - - print('\n--->trans matrix:') - print(trans) - - print('\n--->trans_inv matrix:') - print(trans_inv) - - print('\n---> apply transform to uv') - print('\nxy_m = uv_augmented * trans') - uv_aug = np.hstack((uv, np.ones((uv.shape[0], 1)))) - xy_m = np.dot(uv_aug, trans) - print(xy_m) - - print('\nxy_m = tformfwd(trans, uv)') - xy_m = tformfwd(trans, uv) - print(xy_m) - - print('\n---> apply inverse transform to xy') - print('\nuv_m = xy_augmented * trans_inv') - xy_aug = np.hstack((xy, np.ones((xy.shape[0], 1)))) - uv_m = np.dot(xy_aug, trans_inv) - print(uv_m) - - print('\nuv_m = tformfwd(trans_inv, xy)') - uv_m = tformfwd(trans_inv, xy) - print(uv_m) - - uv_m = tforminv(trans, xy) - print('\nuv_m = tforminv(trans, xy)') - print(uv_m) diff --git a/spaces/FlowiseAI/Flowise/README.md b/spaces/FlowiseAI/Flowise/README.md deleted file mode 100644 index 5edd57418112c048c0aaa067af0ec2805a95e7f6..0000000000000000000000000000000000000000 --- a/spaces/FlowiseAI/Flowise/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Flowise -emoji: 📈 -colorFrom: pink -colorTo: blue -sdk: docker -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/FourthBrainGenAI/FourthBrainGenAI-ProductSnapAI/README.md b/spaces/FourthBrainGenAI/FourthBrainGenAI-ProductSnapAI/README.md deleted file mode 100644 index 1da55f33796f08a8fafd04cb837bab5c57e5f2f8..0000000000000000000000000000000000000000 --- a/spaces/FourthBrainGenAI/FourthBrainGenAI-ProductSnapAI/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: FourthBrainGenAI ProductSnapAI -emoji: 🌖 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 3.24.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/FrankZxShen/so-vits-svc-models-ba/modules/losses.py b/spaces/FrankZxShen/so-vits-svc-models-ba/modules/losses.py deleted file mode 100644 index cd21799eccde350c3aac0bdd661baf96ed220147..0000000000000000000000000000000000000000 --- a/spaces/FrankZxShen/so-vits-svc-models-ba/modules/losses.py +++ /dev/null @@ -1,61 +0,0 @@ -import torch -from torch.nn import functional as F - -import modules.commons as commons - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - rl = rl.float().detach() - gl = gl.float() - loss += torch.mean(torch.abs(rl - gl)) - - return loss * 2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - loss = 0 - r_losses = [] - g_losses = [] - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - dr = dr.float() - dg = dg.float() - r_loss = torch.mean((1-dr)**2) - g_loss = torch.mean(dg**2) - loss += (r_loss + g_loss) - r_losses.append(r_loss.item()) - g_losses.append(g_loss.item()) - - return loss, r_losses, g_losses - - -def generator_loss(disc_outputs): - loss = 0 - gen_losses = [] - for dg in disc_outputs: - dg = dg.float() - l = torch.mean((1-dg)**2) - gen_losses.append(l) - loss += l - - return loss, gen_losses - - -def kl_loss(z_p, logs_q, m_p, logs_p, z_mask): - """ - z_p, logs_q: [b, h, t_t] - m_p, logs_p: [b, h, t_t] - """ - z_p = z_p.float() - logs_q = logs_q.float() - m_p = m_p.float() - logs_p = logs_p.float() - z_mask = z_mask.float() - #print(logs_p) - kl = logs_p - logs_q - 0.5 - kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p) - kl = torch.sum(kl * z_mask) - l = kl / torch.sum(z_mask) - return l diff --git a/spaces/FridaZuley/RVC_HFKawaii/infer/lib/infer_pack/models.py b/spaces/FridaZuley/RVC_HFKawaii/infer/lib/infer_pack/models.py deleted file mode 100644 index 7a387b888f63ecd6f1f1bd3ed10aa2176a944d2c..0000000000000000000000000000000000000000 --- a/spaces/FridaZuley/RVC_HFKawaii/infer/lib/infer_pack/models.py +++ /dev/null @@ -1,1174 +0,0 @@ -import math -import logging - -logger = logging.getLogger(__name__) - -import numpy as np -import torch -from torch import nn -from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d -from torch.nn import functional as F -from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm - -from infer.lib.infer_pack import attentions, commons, modules -from infer.lib.infer_pack.commons import get_padding, init_weights -has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available()) - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder768(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(768, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - if uv.device.type == "privateuseone": # for DirectML - uv = uv.float() - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - if hasattr(self, "ddtype") == False: - self.ddtype = self.l_linear.weight.dtype - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype) - # if self.is_half: - # sine_wavs = sine_wavs.half() - # sine_merge = self.l_tanh(self.l_linear(sine_wavs.to(x))) - # print(sine_wavs.dtype,self.ddtype) - if sine_wavs.dtype != self.ddtype: - sine_wavs = sine_wavs.to(self.ddtype) - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMs256NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - logger.debug( - "gin_channels: " - + str(gin_channels) - + ", self.spk_embed_dim: " - + str(self.spk_embed_dim) - ) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - nsff0 = nsff0[:, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - logger.debug( - "gin_channels: " - + str(gin_channels) - + ", self.spk_embed_dim: " - + str(self.spk_embed_dim) - ) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - nsff0 = nsff0[:, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs256NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - logger.debug( - "gin_channels: " - + str(gin_channels) - + ", self.spk_embed_dim: " - + str(self.spk_embed_dim) - ) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - logger.debug( - "gin_channels: " - + str(gin_channels) - + ", self.spk_embed_dim: " - + str(self.spk_embed_dim) - ) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class MultiPeriodDiscriminatorV2(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminatorV2, self).__init__() - # periods = [2, 3, 5, 7, 11, 17] - periods = [2, 3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - if has_xpu and x.dtype == torch.bfloat16: - x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(dtype=torch.bfloat16) - else: - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/Gen-Sim/Gen-Sim/cliport/generated_tasks/sphere_align_stand.py b/spaces/Gen-Sim/Gen-Sim/cliport/generated_tasks/sphere_align_stand.py deleted file mode 100644 index 5097ce06bd8ef63523b622f230d9b3ff75d53294..0000000000000000000000000000000000000000 --- a/spaces/Gen-Sim/Gen-Sim/cliport/generated_tasks/sphere_align_stand.py +++ /dev/null @@ -1,54 +0,0 @@ -import numpy as np -import os -import pybullet as p -import random -from cliport.tasks import primitives -from cliport.tasks.grippers import Spatula -from cliport.tasks.task import Task -from cliport.utils import utils -import numpy as np -from cliport.tasks.task import Task -from cliport.utils import utils - -class SphereAlignStand(Task): - """Pick up each sphere and place it on the stand of the matching color.""" - - def __init__(self): - super().__init__() - self.max_steps = 5 - self.lang_template = "place the {color} sphere on the {color} stand" - self.task_completed_desc = "done aligning spheres with stands." - self.additional_reset() - - def reset(self, env): - super().reset(env) - - # Define colors for the spheres and stands - colors = ['red', 'green', 'blue', 'yellow', 'purple'] - color_names = ['red', 'green', 'blue', 'yellow', 'purple'] - - # Add stands. - # x, y, z dimensions for the asset size - stand_size = (0.05, 0.05, 0.05) - stand_urdf = 'stacking/stand.urdf' - stand_poses = [] - for i in range(5): - stand_pose = self.get_random_pose(env, stand_size) - env.add_object(stand_urdf, stand_pose, 'fixed', color=utils.COLORS[colors[i]]) - stand_poses.append(stand_pose) - - # Add spheres. - # x, y, z dimensions for the asset size - sphere_size = (0.04, 0.04, 0.04) - sphere_urdf = 'sphere/sphere.urdf' - spheres = [] - for i in range(5): - sphere_pose = self.get_random_pose(env, sphere_size) - sphere_id = env.add_object(sphere_urdf, sphere_pose, color=utils.COLORS[colors[i]]) - spheres.append(sphere_id) - - # Goal: each sphere is on the stand of the matching color. - for i in range(5): - self.add_goal(objs=[spheres[i]], matches=np.ones((1, 1)), targ_poses=[stand_poses[i]], replace=False, - rotations=True, metric='pose', params=None, step_max_reward=1/5, - language_goal=self.lang_template.format(color=color_names[i])) \ No newline at end of file diff --git a/spaces/Gen-Sim/Gen-Sim/misc/snapshot_all_tasks.py b/spaces/Gen-Sim/Gen-Sim/misc/snapshot_all_tasks.py deleted file mode 100644 index 8ef142a21a5c9f45e7ba6ca55249abc199ac4847..0000000000000000000000000000000000000000 --- a/spaces/Gen-Sim/Gen-Sim/misc/snapshot_all_tasks.py +++ /dev/null @@ -1,34 +0,0 @@ -import cv2 -import numpy as np -import IPython -import os - -output_folder = "output/output_gifs/" -output_img_folder = "output/output_imgs/" - -total_tasks = [s for s in sorted(os.listdir(output_folder)) if s.endswith("mp4") and not s.startswith("grid")] -print(total_tasks) - -# Load videos -videos = [cv2.VideoCapture(os.path.join(output_folder, s)) - for s in total_tasks ] - -# Read all frames -video_frames = [[] for _ in range(len(videos))] -for i, video in enumerate(videos): - frame = None - - while True: - prev_frame = frame - ret, frame = video.read() - if not ret: - break - - # last frame - try: - frame = prev_frame[:550,:] - print(f"write {output_img_folder}/{total_tasks[i]}_img.png") - cv2.imwrite(f"{output_img_folder}/{total_tasks[i]}_img.png", frame) - except: - print("failed:", total_tasks[i]) - diff --git a/spaces/Gen-Sim/Gen-Sim/scripts/metascripts/train10_gpt_indomain.sh b/spaces/Gen-Sim/Gen-Sim/scripts/metascripts/train10_gpt_indomain.sh deleted file mode 100644 index cc436d4afc83cc2b71c962c5c21987f790a55957..0000000000000000000000000000000000000000 --- a/spaces/Gen-Sim/Gen-Sim/scripts/metascripts/train10_gpt_indomain.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -#SBATCH -c 10 -#SBATCH -n 1 -#SBATCH -o logs/%j.out -#SBATCH --exclusive - -STEPS=${1-'50000'} - -sh scripts/traintest_scripts/train_test_multi_task_indistribution.sh data \ - "[mix-piles,rainbow-stack,manipulating-two-ropes,insert-sphere-into-container,align-pair-colored-blocks-along-line,construct-corner-building,colorful_block-tower-on-cylinder-base,build-bridge,push_piles-into-letter]"\ - gpt10_task_indomain $STEPS diff --git a/spaces/Gigabot/ostris-ikea-instructions-lora-sdxl/README.md b/spaces/Gigabot/ostris-ikea-instructions-lora-sdxl/README.md deleted file mode 100644 index d37c9b790cd38a07b93b9e54b52a289587911e29..0000000000000000000000000000000000000000 --- a/spaces/Gigabot/ostris-ikea-instructions-lora-sdxl/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Ostris Ikea Instructions Lora Sdxl -emoji: 👀 -colorFrom: yellow -colorTo: purple -sdk: gradio -sdk_version: 3.45.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/Gradio-Blocks/uniformer_image_detection/configs/gn+ws/mask_rcnn_x50_32x4d_fpn_gn_ws-all_20_23_24e_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/gn+ws/mask_rcnn_x50_32x4d_fpn_gn_ws-all_20_23_24e_coco.py deleted file mode 100644 index 79ce0adf1bf760c371bd1a1c3a9b028cef51c4b4..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/gn+ws/mask_rcnn_x50_32x4d_fpn_gn_ws-all_20_23_24e_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './mask_rcnn_x50_32x4d_fpn_gn_ws-all_2x_coco.py' -# learning policy -lr_config = dict(step=[20, 23]) -runner = dict(type='EpochBasedRunner', max_epochs=24) diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/mask_rcnn/mask_rcnn_r101_fpn_2x_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/mask_rcnn/mask_rcnn_r101_fpn_2x_coco.py deleted file mode 100644 index c8cb2d87eedae2777ac8727dff5f398e1c477ab1..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/mask_rcnn/mask_rcnn_r101_fpn_2x_coco.py +++ /dev/null @@ -1,2 +0,0 @@ -_base_ = './mask_rcnn_r50_fpn_2x_coco.py' -model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101)) diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/rpn/README.md b/spaces/Gradio-Blocks/uniformer_image_detection/configs/rpn/README.md deleted file mode 100644 index 4f6f712c3cd4ea086760e76ef5f24fd5b149a5c2..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/rpn/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks - -## Introduction - -[ALGORITHM] - -```latex -@inproceedings{ren2015faster, - title={Faster r-cnn: Towards real-time object detection with region proposal networks}, - author={Ren, Shaoqing and He, Kaiming and Girshick, Ross and Sun, Jian}, - booktitle={Advances in neural information processing systems}, - year={2015} -} -``` - -## Results and models - -| Backbone | Style | Lr schd | Mem (GB) | Inf time (fps) | AR1000 | Config | Download | -| :-------------: | :-----: | :-----: | :------: | :------------: | :----: | :------: | :--------: | -| R-50-FPN | caffe | 1x | 3.5 | 22.6 | 58.7 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_r50_caffe_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r50_caffe_fpn_1x_coco/rpn_r50_caffe_fpn_1x_coco_20200531-5b903a37.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r50_caffe_fpn_1x_coco/rpn_r50_caffe_fpn_1x_coco_20200531_012334.log.json) | -| R-50-FPN | pytorch | 1x | 3.8 | 22.3 | 58.2 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_r50_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r50_fpn_1x_coco/rpn_r50_fpn_1x_coco_20200218-5525fa2e.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r50_fpn_1x_coco/rpn_r50_fpn_1x_coco_20200218_151240.log.json) | -| R-50-FPN | pytorch | 2x | - | - | 58.6 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_r50_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r50_fpn_2x_coco/rpn_r50_fpn_2x_coco_20200131-0728c9b3.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r50_fpn_2x_coco/rpn_r50_fpn_2x_coco_20200131_190631.log.json) | -| R-101-FPN | caffe | 1x | 5.4 | 17.3 | 60.0 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_r101_caffe_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r101_caffe_fpn_1x_coco/rpn_r101_caffe_fpn_1x_coco_20200531-0629a2e2.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r101_caffe_fpn_1x_coco/rpn_r101_caffe_fpn_1x_coco_20200531_012345.log.json) | -| R-101-FPN | pytorch | 1x | 5.8 | 16.5 | 59.7 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_r101_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r101_fpn_1x_coco/rpn_r101_fpn_1x_coco_20200131-2ace2249.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r101_fpn_1x_coco/rpn_r101_fpn_1x_coco_20200131_191000.log.json) | -| R-101-FPN | pytorch | 2x | - | - | 60.2 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_r101_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r101_fpn_2x_coco/rpn_r101_fpn_2x_coco_20200131-24e3db1a.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_r101_fpn_2x_coco/rpn_r101_fpn_2x_coco_20200131_191106.log.json) | -| X-101-32x4d-FPN | pytorch | 1x | 7.0 | 13.0 | 60.6 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_x101_32x4d_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_32x4d_fpn_1x_coco/rpn_x101_32x4d_fpn_1x_coco_20200219-b02646c6.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_32x4d_fpn_1x_coco/rpn_x101_32x4d_fpn_1x_coco_20200219_012037.log.json) | -| X-101-32x4d-FPN | pytorch | 2x | - | - | 61.1 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_x101_32x4d_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_32x4d_fpn_2x_coco/rpn_x101_32x4d_fpn_2x_coco_20200208-d22bd0bb.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_32x4d_fpn_2x_coco/rpn_x101_32x4d_fpn_2x_coco_20200208_200752.log.json) | -| X-101-64x4d-FPN | pytorch | 1x | 10.1 | 9.1 | 61.0 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_x101_64x4d_fpn_1x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_64x4d_fpn_1x_coco/rpn_x101_64x4d_fpn_1x_coco_20200208-cde6f7dd.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_64x4d_fpn_1x_coco/rpn_x101_64x4d_fpn_1x_coco_20200208_200752.log.json) | -| X-101-64x4d-FPN | pytorch | 2x | - | - | 61.5 | [config](https://github.com/open-mmlab/mmdetection/tree/master/configs/rpn/rpn_x101_64x4d_fpn_2x_coco.py) | [model](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_64x4d_fpn_2x_coco/rpn_x101_64x4d_fpn_2x_coco_20200208-c65f524f.pth) | [log](http://download.openmmlab.com/mmdetection/v2.0/rpn/rpn_x101_64x4d_fpn_2x_coco/rpn_x101_64x4d_fpn_2x_coco_20200208_200752.log.json) | diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/mmseg/models/decode_heads/cascade_decode_head.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/mmseg/models/decode_heads/cascade_decode_head.py deleted file mode 100644 index d02122ca0e68743b1bf7a893afae96042f23838c..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/mmseg/models/decode_heads/cascade_decode_head.py +++ /dev/null @@ -1,57 +0,0 @@ -from abc import ABCMeta, abstractmethod - -from .decode_head import BaseDecodeHead - - -class BaseCascadeDecodeHead(BaseDecodeHead, metaclass=ABCMeta): - """Base class for cascade decode head used in - :class:`CascadeEncoderDecoder.""" - - def __init__(self, *args, **kwargs): - super(BaseCascadeDecodeHead, self).__init__(*args, **kwargs) - - @abstractmethod - def forward(self, inputs, prev_output): - """Placeholder of forward function.""" - pass - - def forward_train(self, inputs, prev_output, img_metas, gt_semantic_seg, - train_cfg): - """Forward function for training. - Args: - inputs (list[Tensor]): List of multi-level img features. - prev_output (Tensor): The output of previous decode head. - img_metas (list[dict]): List of image info dict where each dict - has: 'img_shape', 'scale_factor', 'flip', and may also contain - 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. - For details on the values of these keys see - `mmseg/datasets/pipelines/formatting.py:Collect`. - gt_semantic_seg (Tensor): Semantic segmentation masks - used if the architecture supports semantic segmentation task. - train_cfg (dict): The training config. - - Returns: - dict[str, Tensor]: a dictionary of loss components - """ - seg_logits = self.forward(inputs, prev_output) - losses = self.losses(seg_logits, gt_semantic_seg) - - return losses - - def forward_test(self, inputs, prev_output, img_metas, test_cfg): - """Forward function for testing. - - Args: - inputs (list[Tensor]): List of multi-level img features. - prev_output (Tensor): The output of previous decode head. - img_metas (list[dict]): List of image info dict where each dict - has: 'img_shape', 'scale_factor', 'flip', and may also contain - 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. - For details on the values of these keys see - `mmseg/datasets/pipelines/formatting.py:Collect`. - test_cfg (dict): The testing config. - - Returns: - Tensor: Output segmentation map. - """ - return self.forward(inputs, prev_output) diff --git a/spaces/GrandaddyShmax/AudioCraft_Plus/audiocraft/data/audio.py b/spaces/GrandaddyShmax/AudioCraft_Plus/audiocraft/data/audio.py deleted file mode 100644 index 39c87047f5033d0016200df77004a9536e06e81a..0000000000000000000000000000000000000000 --- a/spaces/GrandaddyShmax/AudioCraft_Plus/audiocraft/data/audio.py +++ /dev/null @@ -1,216 +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. - -""" -Audio IO methods are defined in this module (info, read, write), -We rely on av library for faster read when possible, otherwise on torchaudio. -""" - -from dataclasses import dataclass -from pathlib import Path -import logging -import typing as tp - -import numpy as np -import soundfile -import torch -from torch.nn import functional as F -import torchaudio as ta - -import av - -from .audio_utils import f32_pcm, i16_pcm, normalize_audio - - -_av_initialized = False - - -def _init_av(): - global _av_initialized - if _av_initialized: - return - logger = logging.getLogger('libav.mp3') - logger.setLevel(logging.ERROR) - _av_initialized = True - - -@dataclass(frozen=True) -class AudioFileInfo: - sample_rate: int - duration: float - channels: int - - -def _av_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - _init_av() - with av.open(str(filepath)) as af: - stream = af.streams.audio[0] - sample_rate = stream.codec_context.sample_rate - duration = float(stream.duration * stream.time_base) - channels = stream.channels - return AudioFileInfo(sample_rate, duration, channels) - - -def _soundfile_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - info = soundfile.info(filepath) - return AudioFileInfo(info.samplerate, info.duration, info.channels) - - -def audio_info(filepath: tp.Union[str, Path]) -> AudioFileInfo: - # torchaudio no longer returns useful duration informations for some formats like mp3s. - filepath = Path(filepath) - if filepath.suffix in ['.flac', '.ogg']: # TODO: Validate .ogg can be safely read with av_info - # ffmpeg has some weird issue with flac. - return _soundfile_info(filepath) - else: - return _av_info(filepath) - - -def _av_read(filepath: tp.Union[str, Path], seek_time: float = 0, duration: float = -1.) -> tp.Tuple[torch.Tensor, int]: - """FFMPEG-based audio file reading using PyAV bindings. - Soundfile cannot read mp3 and av_read is more efficient than torchaudio. - - Args: - filepath (str or Path): Path to audio file to read. - seek_time (float): Time at which to start reading in the file. - duration (float): Duration to read from the file. If set to -1, the whole file is read. - Returns: - tuple of torch.Tensor, int: Tuple containing audio data and sample rate - """ - _init_av() - with av.open(str(filepath)) as af: - stream = af.streams.audio[0] - sr = stream.codec_context.sample_rate - num_frames = int(sr * duration) if duration >= 0 else -1 - frame_offset = int(sr * seek_time) - # we need a small negative offset otherwise we get some edge artifact - # from the mp3 decoder. - af.seek(int(max(0, (seek_time - 0.1)) / stream.time_base), stream=stream) - frames = [] - length = 0 - for frame in af.decode(streams=stream.index): - current_offset = int(frame.rate * frame.pts * frame.time_base) - strip = max(0, frame_offset - current_offset) - buf = torch.from_numpy(frame.to_ndarray()) - if buf.shape[0] != stream.channels: - buf = buf.view(-1, stream.channels).t() - buf = buf[:, strip:] - frames.append(buf) - length += buf.shape[1] - if num_frames > 0 and length >= num_frames: - break - assert frames - # If the above assert fails, it is likely because we seeked past the end of file point, - # in which case ffmpeg returns a single frame with only zeros, and a weird timestamp. - # This will need proper debugging, in due time. - wav = torch.cat(frames, dim=1) - assert wav.shape[0] == stream.channels - if num_frames > 0: - wav = wav[:, :num_frames] - return f32_pcm(wav), sr - - -def audio_read(filepath: tp.Union[str, Path], seek_time: float = 0., - duration: float = -1., pad: bool = False) -> tp.Tuple[torch.Tensor, int]: - """Read audio by picking the most appropriate backend tool based on the audio format. - - Args: - filepath (str or Path): Path to audio file to read. - seek_time (float): Time at which to start reading in the file. - duration (float): Duration to read from the file. If set to -1, the whole file is read. - pad (bool): Pad output audio if not reaching expected duration. - Returns: - tuple of torch.Tensor, int: Tuple containing audio data and sample rate. - """ - fp = Path(filepath) - if fp.suffix in ['.flac', '.ogg']: # TODO: check if we can safely use av_read for .ogg - # There is some bug with ffmpeg and reading flac - info = _soundfile_info(filepath) - frames = -1 if duration <= 0 else int(duration * info.sample_rate) - frame_offset = int(seek_time * info.sample_rate) - wav, sr = soundfile.read(filepath, start=frame_offset, frames=frames, dtype=np.float32) - assert info.sample_rate == sr, f"Mismatch of sample rates {info.sample_rate} {sr}" - wav = torch.from_numpy(wav).t().contiguous() - if len(wav.shape) == 1: - wav = torch.unsqueeze(wav, 0) - elif ( - fp.suffix in ['.wav', '.mp3'] and fp.suffix[1:] in ta.utils.sox_utils.list_read_formats() - and duration <= 0 and seek_time == 0 - ): - # Torchaudio is faster if we load an entire file at once. - wav, sr = ta.load(fp) - else: - wav, sr = _av_read(filepath, seek_time, duration) - if pad and duration > 0: - expected_frames = int(duration * sr) - wav = F.pad(wav, (0, expected_frames - wav.shape[-1])) - return wav, sr - - -def audio_write(stem_name: tp.Union[str, Path], - wav: torch.Tensor, sample_rate: int, - format: str = 'wav', mp3_rate: int = 320, normalize: bool = True, - strategy: str = 'peak', peak_clip_headroom_db: float = 1, - rms_headroom_db: float = 18, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, - log_clipping: bool = True, make_parent_dir: bool = True, - add_suffix: bool = True) -> Path: - """Convenience function for saving audio to disk. Returns the filename the audio was written to. - - Args: - stem_name (str or Path): Filename without extension which will be added automatically. - format (str): Either "wav" or "mp3". - mp3_rate (int): kbps when using mp3s. - normalize (bool): if `True` (default), normalizes according to the prescribed - strategy (see after). If `False`, the strategy is only used in case clipping - would happen. - strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak', - i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square - with extra headroom to avoid clipping. 'clip' just clips. - peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy. - rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger - than the `peak_clip` one to avoid further clipping. - loudness_headroom_db (float): Target loudness for loudness normalization. - loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'. - when strategy is 'loudness' log_clipping (bool): If True, basic logging on stderr when clipping still - occurs despite strategy (only for 'rms'). - make_parent_dir (bool): Make parent directory if it doesn't exist. - Returns: - Path: Path of the saved audio. - """ - assert wav.dtype.is_floating_point, "wav is not floating point" - if wav.dim() == 1: - wav = wav[None] - elif wav.dim() > 2: - raise ValueError("Input wav should be at most 2 dimension.") - assert wav.isfinite().all() - wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db, - rms_headroom_db, loudness_headroom_db, loudness_compressor, - log_clipping=log_clipping, sample_rate=sample_rate, - stem_name=str(stem_name)) - kwargs: dict = {} - if format == 'mp3': - suffix = '.mp3' - kwargs.update({"compression": mp3_rate}) - elif format == 'wav': - wav = i16_pcm(wav) - suffix = '.wav' - kwargs.update({"encoding": "PCM_S", "bits_per_sample": 16}) - else: - raise RuntimeError(f"Invalid format {format}. Only wav or mp3 are supported.") - if not add_suffix: - suffix = '' - path = Path(str(stem_name) + suffix) - if make_parent_dir: - path.parent.mkdir(exist_ok=True, parents=True) - try: - ta.save(path, wav, sample_rate, **kwargs) - except Exception: - if path.exists(): - # we do not want to leave half written files around. - path.unlink() - raise - return path diff --git a/spaces/GrandaddyShmax/MusicGen_Plus/audiocraft/quantization/vq.py b/spaces/GrandaddyShmax/MusicGen_Plus/audiocraft/quantization/vq.py deleted file mode 100644 index f67c3a0cd30d4b8993a36c587f00dc8a451d926f..0000000000000000000000000000000000000000 --- a/spaces/GrandaddyShmax/MusicGen_Plus/audiocraft/quantization/vq.py +++ /dev/null @@ -1,116 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import math -import typing as tp - -import torch - -from .base import BaseQuantizer, QuantizedResult -from .core_vq import ResidualVectorQuantization - - -class ResidualVectorQuantizer(BaseQuantizer): - """Residual Vector Quantizer. - - Args: - dimension (int): Dimension of the codebooks. - n_q (int): Number of residual vector quantizers used. - q_dropout (bool): Random quantizer drop out at train time. - bins (int): Codebook size. - decay (float): Decay for exponential moving average over the codebooks. - kmeans_init (bool): Whether to use kmeans to initialize the codebooks. - kmeans_iters (int): Number of iterations used for kmeans initialization. - threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes - that have an exponential moving average cluster size less than the specified threshold with - randomly selected vector from the current batch. - orthogonal_reg_weight (float): Orthogonal regularization weights. - orthogonal_reg_active_codes_only (bool): Apply orthogonal regularization only on active codes. - orthogonal_reg_max_codes (optional int): Maximum number of codes to consider. - for orthogonal regulariation. - """ - def __init__( - self, - dimension: int = 256, - n_q: int = 8, - q_dropout: bool = False, - bins: int = 1024, - decay: float = 0.99, - kmeans_init: bool = True, - kmeans_iters: int = 10, - threshold_ema_dead_code: int = 2, - orthogonal_reg_weight: float = 0.0, - orthogonal_reg_active_codes_only: bool = False, - orthogonal_reg_max_codes: tp.Optional[int] = None, - ): - super().__init__() - self.max_n_q = n_q - self.n_q = n_q - self.q_dropout = q_dropout - self.dimension = dimension - self.bins = bins - self.decay = decay - self.kmeans_init = kmeans_init - self.kmeans_iters = kmeans_iters - self.threshold_ema_dead_code = threshold_ema_dead_code - self.orthogonal_reg_weight = orthogonal_reg_weight - self.orthogonal_reg_active_codes_only = orthogonal_reg_active_codes_only - self.orthogonal_reg_max_codes = orthogonal_reg_max_codes - self.vq = ResidualVectorQuantization( - dim=self.dimension, - codebook_size=self.bins, - num_quantizers=self.n_q, - decay=self.decay, - kmeans_init=self.kmeans_init, - kmeans_iters=self.kmeans_iters, - threshold_ema_dead_code=self.threshold_ema_dead_code, - orthogonal_reg_weight=self.orthogonal_reg_weight, - orthogonal_reg_active_codes_only=self.orthogonal_reg_active_codes_only, - orthogonal_reg_max_codes=self.orthogonal_reg_max_codes, - channels_last=False - ) - - def forward(self, x: torch.Tensor, frame_rate: int): - n_q = self.n_q - if self.training and self.q_dropout: - n_q = int(torch.randint(1, self.n_q + 1, (1,)).item()) - bw_per_q = math.log2(self.bins) * frame_rate / 1000 - quantized, codes, commit_loss = self.vq(x, n_q=n_q) - codes = codes.transpose(0, 1) - # codes is [B, K, T], with T frames, K nb of codebooks. - bw = torch.tensor(n_q * bw_per_q).to(x) - return QuantizedResult(quantized, codes, bw, penalty=torch.mean(commit_loss)) - - def encode(self, x: torch.Tensor) -> torch.Tensor: - """Encode a given input tensor with the specified frame rate at the given bandwidth. - The RVQ encode method sets the appropriate number of quantizer to use - and returns indices for each quantizer. - """ - n_q = self.n_q - codes = self.vq.encode(x, n_q=n_q) - codes = codes.transpose(0, 1) - # codes is [B, K, T], with T frames, K nb of codebooks. - return codes - - def decode(self, codes: torch.Tensor) -> torch.Tensor: - """Decode the given codes to the quantized representation. - """ - # codes is [B, K, T], with T frames, K nb of codebooks, vq.decode expects [K, B, T]. - codes = codes.transpose(0, 1) - quantized = self.vq.decode(codes) - return quantized - - @property - def total_codebooks(self): - return self.max_n_q - - @property - def num_codebooks(self): - return self.n_q - - def set_num_codebooks(self, n: int): - assert n > 0 and n <= self.max_n_q - self.n_q = n diff --git a/spaces/HaMerL/ChaosinChat/run_Linux.sh b/spaces/HaMerL/ChaosinChat/run_Linux.sh deleted file mode 100644 index 4beca2fc4d6387d7af19579e93bbc8b799a14668..0000000000000000000000000000000000000000 --- a/spaces/HaMerL/ChaosinChat/run_Linux.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -# 获取脚本所在目录 -script_dir=$(dirname "$(readlink -f "$0")") - -# 将工作目录更改为脚本所在目录 -cd "$script_dir" || exit - -# 检查Git仓库是否有更新 -git remote update -pwd - -if ! git status -uno | grep 'up to date' > /dev/null; then - # 如果有更新,关闭当前运行的服务器 - pkill -f Chatbot.py - - # 拉取最新更改 - git pull - - # 安装依赖 - pip3 install -r requirements.txt - - # 重新启动服务器 - nohup python3 Chatbot.py & -fi - -# 检查Chatbot.py是否在运行 -if ! pgrep -f Chatbot.py > /dev/null; then - # 如果没有运行,启动服务器 - nohup python3 Chatbot.py & -fi diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/multilingual/data_scripts/download_wmt19_and_before.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/multilingual/data_scripts/download_wmt19_and_before.py deleted file mode 100644 index 3465731eb3e55047c44d1b336a97e99cb3a89a53..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/multilingual/data_scripts/download_wmt19_and_before.py +++ /dev/null @@ -1,899 +0,0 @@ -from typing import NamedTuple, List -from urllib.parse import urlparse -import os, sys -import subprocess -from subprocess import check_call, check_output -import glob -import wget -import re -import multiprocessing as mp -from functools import partial -import pathlib -from collections import OrderedDict - -WORKDIR_ROOT = os.environ.get('WORKDIR_ROOT', None) - -if WORKDIR_ROOT is None or not WORKDIR_ROOT.strip(): - print('please specify your working directory root in OS environment variable WORKDIR_ROOT. Exitting..."') - sys.exit(-1) - -# scripts and data locations -CWD = os.getcwd() -UTILS = f"{CWD}/utils" - -MOSES = f"{UTILS}/mosesdecoder" -SGM_TOOL = f'{MOSES}/scripts/ems/support/input-from-sgm.perl' - -TMX2CORPUS = f"{UTILS}/tmx2corpus" -TMX_TOOL = f'python {TMX2CORPUS}/tmx2corpus.py' - -to_data_path = f'{WORKDIR_ROOT}/wmt' -download_to = f'{to_data_path}/downloads' -manually_downloads = f'{to_data_path}/downloads' -extract_to = f'{to_data_path}/extracted' -#DESTDIR=${WORKDIR_ROOT}/ML50/raw/ -raw_data = f'{WORKDIR_ROOT}/ML50/raw' -#### - -class DLDataset(NamedTuple): - name: str - train_urls: List[str] - valid_urls: List[str] - test_urls: List[str] - train_files_patterns: List[str] = [] - valid_files_patterns: List[str] = [] - test_files_patterns: List[str] = [] - - - -def bar_custom(current, total, width=80): - print("Downloading: %d%% [%d / %d] Ks" % (current / total * 100, current / 1000, total / 1000), end='\r') - -def get_downloaded_file(dl_folder, url): - if isinstance(url, tuple): - url, f = url - else: - url_f = urlparse(url) - # f = os.path.split(url_f.path)[-1] - f = '_'.join(url_f.path.split('/')[1:]) - return url, f"{dl_folder}/{f}" - -def download_parts_and_combine(dl_folder, urls, filename): - parts = [] - for url_record in urls: - url, part_file = get_downloaded_file(dl_folder, url_record) - if os.path.exists(part_file): - print(f'{part_file} has already been downloaded so skip') - else: - part_file = wget.download(url, part_file, bar=bar_custom) - parts.append(part_file) - - def get_combine_cmd(parts): - #default as tar.gz.?? - return f'cat {" ".join(parts)} > {filename}' - - combine_cmd = get_combine_cmd(parts) - call(combine_cmd, debug=True) - return filename - -def download_a_url(dl_folder, url): - url, filename = get_downloaded_file(dl_folder, url) - if os.path.exists(filename): - print(f'{filename} has already been downloaded so skip') - return filename - - print(f'downloading {url} to {filename}') - if isinstance(url, list) or isinstance(url, tuple): - download_parts_and_combine(dl_folder, url, filename) - else: - wget.download(url, filename, bar=bar_custom) - print(f'dowloaded: {filename}') - return filename - -def download_files(dl_folder, urls, completed_urls={}): - for url_record in urls: - url, _ = get_downloaded_file(dl_folder, url_record) - filename = download_a_url(dl_folder, url_record) - completed_urls[str(url)] = filename - return completed_urls - -def check_need_manual_downalod(dl_folder, to_manually_download_urls): - to_be_manually_dowloaded = [] - manually_completed_urls = {} - for url_record, instruction in to_manually_download_urls: - url, filename = get_downloaded_file(dl_folder, url_record) - if not os.path.exists(filename): - print(f'{url} need to be download manually, please download it manually following {instruction}; and copy it to {filename}') - to_be_manually_dowloaded.append((url, filename)) - else: - manually_completed_urls[url] = filename - # if len(to_be_manually_dowloaded) > 0: - # raise ValueError('Missing files that need to be downloaded manually; stop the process now.') - return to_be_manually_dowloaded - -def download_dataset(to_folder, dl_dataset, completed_urls={}): - download_files(to_folder, dl_dataset.train_urls, completed_urls) - download_files(to_folder, dl_dataset.valid_urls, completed_urls) - download_files(to_folder, dl_dataset.test_urls, completed_urls) - print('completed downloading') - return completed_urls - -def call(cmd, debug=False): - if debug: - print(cmd) - check_call(cmd, shell=True) - - -def get_extract_name(file_path): - path = os.path.split(file_path) - return path[-1] + '_extract' #.split('.')[0] - -def extract_file(downloaded_file, extract_folder, get_extract_name=get_extract_name, debug=False): - extract_name = get_extract_name(downloaded_file) - extract_to = f'{extract_folder}/{extract_name}' - os.makedirs(extract_to, exist_ok=True) - if os.path.exists(f'{extract_to}/DONE'): - print(f'{downloaded_file} has already been extracted to {extract_to} so skip') - return extract_to - def get_extract_cmd(filename): - if filename.endswith('.tgz') or filename.endswith('tar.gz'): - return f'tar xzfv {filename} -C {extract_to}' - elif filename.endswith('.gz.tar'): - return f'tar xfv {filename} -C {extract_to}; (cd {extract_to}; gzip -d *.gz; [ $? -eq 0 ] || gzip -d */*.gz)' - elif filename.endswith('.tar'): - return f'tar xfv {filename} -C {extract_to}' - elif filename.endswith('.gz'): - return f'cp {filename} {extract_to}; (cd {extract_to}; gzip -d *.gz)' - elif filename.endswith('.zip'): - return f'unzip {filename} -d {extract_to}' - extract_cmd = get_extract_cmd(downloaded_file) - print(f'extracting {downloaded_file}') - if isinstance(extract_cmd, list): - for c in extract_cmd: - call(c, debug=debug) - else: - call(extract_cmd, debug=debug) - call(f'echo DONE > {extract_to}/DONE') - return extract_to - - -def extract_all_files( - completed_urls, extract_folder, - get_extract_name=get_extract_name, - completed_extraction={}, - debug=False): - extracted_folders = OrderedDict() - for url, downloaded_file in set(completed_urls.items()): - if downloaded_file in completed_extraction: - print(f'{downloaded_file} is already extracted; so skip') - continue - folder = extract_file(downloaded_file, extract_folder, get_extract_name, debug) - extracted_folders[url] = folder - return extracted_folders - - -def my_glob(folder): - for p in [f'{folder}/*', f'{folder}/*/*', f'{folder}/*/*/*']: - for f in glob.glob(p): - yield f - - -def sgm2raw(sgm, debug): - to_file = sgm[0:len(sgm) - len('.sgm')] - if os.path.exists(to_file): - debug and print(f'{sgm} already converted to {to_file}; so skip') - return to_file - cmd = f'{SGM_TOOL} < {sgm} > {to_file}' - call(cmd, debug) - return to_file - -def tmx2raw(tmx, debug): - to_file = tmx[0:len(tmx) - len('.tmx')] - to_folder = os.path.join(*os.path.split(tmx)[:-1]) - if os.path.exists(f'{to_folder}/bitext.en'): - debug and print(f'{tmx} already extracted to {to_file}; so skip') - return to_file - cmd = f'(cd {to_folder}; {TMX_TOOL} {tmx})' - call(cmd, debug) - return to_file - -CZENG16_REGEX = re.compile(r'.*?data.plaintext-format/0[0-9]train$') -WMT19_WIKITITLES_REGEX = re.compile(r'.*?wikititles-v1.(\w\w)-en.tsv.gz') -TSV_REGEX = re.compile(r'.*?(\w\w)-(\w\w).tsv$') - - - -def cut_wikitles(wiki_file, debug): - # different languages have different file names: - if wiki_file.endswith('wiki/fi-en/titles.fi-en'): - to_file1 = f'{wiki_file}.fi' - to_file2 = f'{wiki_file}.en' - BACKSLASH = '\\' - cmd1 = f"cat {wiki_file} | sed 's/|||/{BACKSLASH}t/g' |cut -f1 |awk '{{$1=$1}};1' > {to_file1}" - cmd2 = f"cat {wiki_file} | sed 's/|||/{BACKSLASH}t/g' |cut -f2 |awk '{{$1=$1}};1' > {to_file2}" -# elif WMT19_WIKITITLES_REGEX.match(wiki_file): -# src = WMT19_WIKITITLES_REGEX.match(wiki_file).groups()[0] -# to_file1 = f'{wiki_file}.{src}' -# to_file2 = f'{wiki_file}.en' -# cmd1 = f"cat {wiki_file} | cut -f1 |awk '{{$1=$1}};1' > {to_file1}" -# cmd2 = f"cat {wiki_file} | cut -f2 |awk '{{$1=$1}};1' > {to_file2}" - else: - return None - if os.path.exists(to_file1) and os.path.exists(to_file2): - debug and print(f'{wiki_file} already processed to {to_file1} and {to_file2}; so skip') - return wiki_file - - call(cmd1, debug=debug) - call(cmd2, debug=debug) - return wiki_file - -def cut_tsv(file, debug): - m = TSV_REGEX.match(file) - if m is None: - raise ValueError(f'{file} is not matching tsv pattern') - src = m.groups()[0] - tgt = m.groups()[1] - - to_file1 = f'{file}.{src}' - to_file2 = f'{file}.{tgt}' - cmd1 = f"cat {file} | cut -f1 |awk '{{$1=$1}};1' > {to_file1}" - cmd2 = f"cat {file} | cut -f2 |awk '{{$1=$1}};1' > {to_file2}" - if os.path.exists(to_file1) and os.path.exists(to_file2): - debug and print(f'{file} already processed to {to_file1} and {to_file2}; so skip') - return file - - call(cmd1, debug=debug) - call(cmd2, debug=debug) - return file - - -def convert_file_if_needed(file, debug): - if file.endswith('.sgm'): - return sgm2raw(file, debug) - elif file.endswith('.tmx'): - return tmx2raw(file, debug) - elif file.endswith('wiki/fi-en/titles.fi-en'): - return cut_wikitles(file, debug) -# elif WMT19_WIKITITLES_REGEX.match(file): -# return cut_wikitles(file, debug) - elif file.endswith('.tsv'): - return cut_tsv(file, debug) - elif CZENG16_REGEX.match(file): - return convert2czeng17(file, debug) - else: - return file - - -def convert_files_if_needed(extracted_foldrs, my_glob=my_glob, debug=False): - return { - url: list(sorted(set(convert_file_if_needed(f, debug)) for f in sorted(set(my_glob(folder))))) - for url, folder in extracted_foldrs.items() - } - -def match_patt(file_path, file_pattern, src, tgt, lang): - return file_pattern.format(src=src, tgt=tgt, lang=lang) in file_path - -def match_patts(file_path, file_patterns, src, tgt, lang): - for file_pattern in file_patterns: - params = { k: v for k, v in [('src', src), ('tgt', tgt), ('lang', lang)] if k in file_pattern} - matching = file_pattern.format(**params) - - if isinstance(file_pattern, tuple): - pattern, directions = file_pattern - if f'{src}-{tgt}' in directions and matching in file_path: - return True - else: - if matching in file_path: - return True - return False - -def extracted_glob(extracted_folder, file_patterns, src, tgt, lang): - def get_matching_pattern(file_pattern): - params = { - k: v - for k, v in [('src', src), ('tgt', tgt), ('lang', lang)] - if '{' + k + '}' in file_pattern - } - file_pattern = re.sub(r'{src:(.*?)}', r'\1' if lang == src else '', file_pattern) - file_pattern = re.sub(r'{tgt:(.*?)}', r'\1' if lang == tgt else '', file_pattern) - file_pattern = file_pattern.format(**params) - return file_pattern - for file_pattern in file_patterns: - if isinstance(file_pattern, tuple): - file_pattern, lang_pairs = file_pattern - if f'{src}-{tgt}' not in lang_pairs: - continue -# print('working on pattern: ', file_pattern, lang_pairs ) - matching_pattern = get_matching_pattern(file_pattern) - if matching_pattern is None: - continue - glob_patterns = f'{extracted_folder}/{matching_pattern}' -# print('glob_patterns: ', glob_patterns) - for f in glob.glob(glob_patterns): - yield f - -# for debug usage -def all_extracted_files(split, src, tgt, extracted_folders, split_urls): - def get_url(url): - if isinstance(url, tuple): - url, downloaded_file = url - return url - return [ - f - for url in split_urls - for f in my_glob(extracted_folders[str(get_url(url))]) - ] - -def concat_files(split, src, tgt, extracted_folders, split_urls, path_patterns, to_folder, debug=False): -# if debug: -# print('extracted files to be filtered by patterns: ', -# '\n\t'.join(sorted(all_extracted_files(split, src, tgt, extracted_folders, split_urls)))) - for lang in [src, tgt]: - to_file = f'{to_folder}/{split}.{src}-{tgt}.{lang}' - s_src, s_tgt, s_lang = src.split('_')[0], tgt.split('_')[0], lang.split('_')[0] - files = [] - for url in split_urls: - if isinstance(url, tuple): - url, downloaded_file = url - if str(url) not in extracted_folders: - print(f'warning: {url} not in extracted files') - for extracted_file in set( - extracted_glob( - extracted_folders[str(url)], path_patterns, - s_src, s_tgt, s_lang)): - files.append(extracted_file) - if len(files) == 0: - print('warning: ', f'No files found for split {to_file}') - continue - files = sorted(set(files)) - print(f'concating {len(files)} files into {to_file}') - cmd = ['cat'] + [f'"{f}"' for f in files] + [f'>{to_file}'] - cmd = " ".join(cmd) - call(cmd, debug=debug) - -UTILS = os.path.join(pathlib.Path(__file__).parent, 'utils') -LID_MODEL = f'{download_to}/lid.176.bin' -LID_MULTI = f'{UTILS}/fasttext_multi_filter.py' - -def lid_filter(split, src, tgt, from_folder, to_folder, debug=False): - if not os.path.exists(LID_MODEL): - call(f'wget -nc https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin -O {LID_MODEL}') - from_prefix = f'{from_folder}/{split}.{src}-{tgt}' - to_prefix = f'{to_folder}/{split}.{src}-{tgt}' - if os.path.exists(f'{from_prefix}.{src}') and os.path.exists(f'{from_prefix}.{tgt}'): - s_src, s_tgt = src.split('_')[0], tgt.split('_')[0] - cmd = ( - f'python {LID_MULTI} --model {LID_MODEL} --inputs {from_prefix}.{src} {from_prefix}.{tgt} ' - f'--langs {s_src} {s_tgt} --outputs {to_prefix}.{src} {to_prefix}.{tgt}' - ) - print(f'filtering {from_prefix}') - call(cmd, debug=debug) - -def concat_into_splits(dl_dataset, src, tgt, extracted_folders, to_folder, debug): - to_folder_tmp = f"{to_folder}_tmp" - os.makedirs(to_folder_tmp, exist_ok=True) - concat_files('train', src, tgt, - extracted_folders, - split_urls=dl_dataset.train_urls, - path_patterns=dl_dataset.train_files_patterns, - to_folder=to_folder_tmp, debug=debug) - lid_filter('train', src, tgt, to_folder_tmp, to_folder, debug) - - concat_files('valid', src, tgt, - extracted_folders, - split_urls=dl_dataset.valid_urls, - path_patterns=dl_dataset.valid_files_patterns, - to_folder=to_folder, debug=debug) - concat_files('test', src, tgt, - extracted_folders, - split_urls=dl_dataset.test_urls, - path_patterns=dl_dataset.test_files_patterns, - to_folder=to_folder, debug=debug) - - -def download_multi(dl_folder, extract_folder, urls, num_processes=8, debug=False): - pool = mp.Pool(processes=num_processes) - download_f = partial(download_a_url, dl_folder) - downloaded_files = pool.imap_unordered(download_f, urls) - pool.close() - pool.join() - -BLEU_REGEX = re.compile("^BLEU\\S* = (\\S+) ") -def run_eval_bleu(cmd): - output = check_output(cmd, shell=True, stderr=subprocess.STDOUT).decode("utf-8").strip() - print(output) - bleu = -1.0 - for line in output.strip().split('\n'): - m = BLEU_REGEX.search(line) - if m is not None: - bleu = m.groups()[0] - bleu = float(bleu) - break - return bleu - -def check_wmt_test_bleu(raw_folder, wmt_lang_pairs): - not_matchings = [] - for wmt, src_tgts in wmt_lang_pairs: - for src_tgt in src_tgts: - print(f'checking test bleus for: {src_tgt} at {wmt}') - src, tgt = src_tgt.split('-') - ssrc, stgt = src[:2], tgt[:2] - if os.path.exists(f'{raw_folder}/test.{tgt}-{src}.{src}'): - # reversed direction may have different test set - test_src = f'{raw_folder}/test.{tgt}-{src}.{src}' - else: - test_src = f'{raw_folder}/test.{src}-{tgt}.{src}' - cmd1 = f'cat {test_src} | sacrebleu -t "{wmt}" -l {stgt}-{ssrc}; [ $? -eq 0 ] || echo ""' - test_tgt = f'{raw_folder}/test.{src}-{tgt}.{tgt}' - cmd2 = f'cat {test_tgt} | sacrebleu -t "{wmt}" -l {ssrc}-{stgt}; [ $? -eq 0 ] || echo ""' - bleu1 = run_eval_bleu(cmd1) - if bleu1 != 100.0: - not_matchings.append(f'{wmt}:{src_tgt} source side not matching: {test_src}') - bleu2 = run_eval_bleu(cmd2) - if bleu2 != 100.0: - not_matchings.append(f'{wmt}:{src_tgt} target side not matching: {test_tgt}') - return not_matchings - -def download_and_extract( - to_folder, lang_pairs, dl_dataset, - to_manually_download_urls, - completed_urls={}, completed_extraction={}, - debug=False): - - dl_folder = f'{to_folder}/downloads' - extract_folder = f'{to_folder}/extracted' - raw_folder = f'{to_folder}/raw' - lid_filtered = f'{to_folder}/lid_filtered' - - os.makedirs(extract_folder, exist_ok=True) - os.makedirs(raw_folder, exist_ok=True) - os.makedirs(lid_filtered, exist_ok=True) - - - to_be_manually_dowloaded = check_need_manual_downalod(dl_folder, to_manually_download_urls) - - completed_urls = download_dataset( - dl_folder, dl_dataset, completed_urls) - if debug: - print('completed urls: ', completed_urls) - - - extracted_folders = extract_all_files( - completed_urls, - extract_folder=extract_folder, - completed_extraction=completed_extraction, - debug=debug) - if debug: - print('download files have been extracted to folders: ', extracted_folders) - - converted_files = convert_files_if_needed(extracted_folders, debug=False) - for src_tgt in lang_pairs: - print(f'working on {dl_dataset.name}: {src_tgt}') - src, tgt = src_tgt.split('-') - concat_into_splits(dl_dataset, - src=src, tgt=tgt, - extracted_folders=extracted_folders, - to_folder=raw_folder, debug=debug) - print('completed data into: ', raw_folder) - -def download_czang16(download_to, username=None): - wgets = [ - f'wget --user={username} --password=czeng -P {download_to} http://ufallab.ms.mff.cuni.cz/~bojar/czeng16-data/data-plaintext-format.{i}.tar' - for i in range(10)] - cmds = [] - for i, cmd in enumerate(wgets): - filename = f'{download_to}/data-plaintext-format.{i}.tar' - if os.path.exists(filename): - print(f'{filename} has already been downloaded; so skip') - continue - cmds.append(cmd) - if cmds and username is None: - raise ValueError('No czeng username is given; please register at http://ufal.mff.cuni.cz/czeng/czeng16 to obtain username to download') - for cmd in cmds: - call(cmd) - print('done with downloading czeng1.6') - -def download_czeng17_script(download_to, extract_folder, debug=False): - url = 'http://ufal.mff.cuni.cz/czeng/download.php?f=convert_czeng16_to_17.pl.zip' - filename = f'{download_to}/convert_czeng16_to_17.pl.zip' - extract_to = f'{extract_folder}/{get_extract_name(filename)}' - script_path = f'{extract_to}/convert_czeng16_to_17.pl' - - if not os.path.exists(script_path): - wget.download(url, filename, bar=bar_custom) - extract_to = extract_file(f'{download_to}/convert_czeng16_to_17.pl.zip', extract_folder, get_extract_name=get_extract_name, debug=debug) - return script_path - -czeng17_script_path = "" -def convert2czeng17(file, debug): - en_file = f'{file}.en' - cs_file = f'{file}.cs' - - if not os.path.exists(en_file) or not os.path.exists(cs_file): - cs_cmd = f'cat {file} | perl {czeng17_script_path} | cut -f3 > {cs_file}' - en_cmd = f'cat {file} | perl {czeng17_script_path} | cut -f4 > {en_file}' - call(cs_cmd, debug) - call(en_cmd, debug) - else: - print(f'already extracted: {en_file} and {cs_file}') - return file - -def extract_czeng17(extract_folder, debug=False): - url = 'http://ufal.mff.cuni.cz/czeng/download.php?f=convert_czeng16_to_17.pl.zip' - filename = f'{download_to}/convert_czeng16_to_17.pl.zip' - extract_to = f'{extract_folder}/{get_extract_name(filename)}' - script_path = f'{extract_to}/convert_czeng16_to_17.pl' - - if not os.path.exists(script_path): - wget.download(url, filename, bar=bar_custom) - extract_to = extract_file(f'{download_to}/convert_czeng16_to_17.pl.zip', extract_folder, get_extract_name=get_extract_name, debug=debug) - return script_path - -######### -# definitions of wmt data sources -# for es-en -# Punctuation in the official test sets will be encoded with ASCII characters (not complex Unicode characters) as much as possible. You may want to normalize your system's output before submission. You are able able to use a rawer version of the test sets that does not have this normalization. -# script to normalize punctuation: http://www.statmt.org/wmt11/normalize-punctuation.perl -wmt13_es_en = DLDataset( - name='wmt13_es-en', - train_urls=[ - 'http://www.statmt.org/wmt13/training-parallel-europarl-v7.tgz', - 'http://www.statmt.org/wmt13/training-parallel-commoncrawl.tgz', - 'http://www.statmt.org/wmt13/training-parallel-un.tgz', - 'http://www.statmt.org/wmt13/training-parallel-nc-v8.tgz', - ], - valid_urls=[ - ('http://www.statmt.org/wmt13/dev.tgz', 'wmt13_dev.tgz') - ], - test_urls=[ - ('http://www.statmt.org/wmt13/test.tgz', 'wmt13_test.tgz') - ], - train_files_patterns=[ - ('*/europarl-v7.{src}-{tgt}.{lang}', ['es-en']), - ('*commoncrawl.{src}-{tgt}.{lang}', ['es-en']), - ('*/news-commentary-v8.{src}-{tgt}.{lang}', ['es-en']), - ('un/*undoc.2000.{src}-{tgt}.{lang}', ['es-en']), - ] , - valid_files_patterns=[ - ('dev/newstest2012.{lang}', ['es-en']) - ], - test_files_patterns=[ - ('test/newstest*.{lang}', ['es-en']) - ], -) - -wmt14_de_fr_en = DLDataset( - name='wmt14_de_fr_en', - train_urls=[ - 'http://www.statmt.org/wmt13/training-parallel-europarl-v7.tgz', - 'http://www.statmt.org/wmt13/training-parallel-commoncrawl.tgz', - 'http://www.statmt.org/wmt13/training-parallel-un.tgz', - 'http://www.statmt.org/wmt14/training-parallel-nc-v9.tgz', - ('http://www.statmt.org/wmt10/training-giga-fren.tar', 'training-giga-fren.gz.tar'), #it is actuall a gz.tar - ], - valid_urls=[ - ('http://www.statmt.org/wmt14/dev.tgz', 'wmt14_dev.tgz'), - ], - test_urls=[ - ('http://www.statmt.org/wmt14/test-full.tgz', 'wmt14_test_full.tgz'), # cleaned test sets - ], - train_files_patterns=[ - ('*/europarl-v7.{src}-{tgt}.{lang}', ['fr-en', 'de-en']), - ('*commoncrawl.{src}-{tgt}.{lang}', ['fr-en', 'de-en']), - ('*/*news-commentary-v9.{src}-{tgt}.{lang}', ['fr-en', 'de-en']), - ('un/undoc.2000.{src}-{tgt}.{lang}', ['fr-en']), - ('*giga-{src}{tgt}*{lang}', ['fr-en']) - ], - valid_files_patterns=[ - ('dev/newstest2013.{lang}', ['fr-en', 'de-en']) - ], - test_files_patterns=[ - ('test-full/newstest*{src}{tgt}-{src:src}{tgt:ref}.{lang}', ['en-de', 'de-en', 'fr-en', 'en-fr']), - ], -) - -# pip install git+https://github.com/amake/tmx2corpus.git -wmt16_ro_en = DLDataset( - name='wmt16_ro-en', - train_urls=[ - ('http://data.statmt.org/wmt16/translation-task/training-parallel-ep-v8.tgz', 'wmt16_training-parallel-ep-v8.tgz'), - ('http://opus.nlpl.eu/download.php?f=SETIMES/v2/tmx/en-ro.tmx.gz', 'en-ro.tmx.gz'), - ], - valid_urls=[ - ('http://data.statmt.org/wmt16/translation-task/dev-romanian-updated.tgz', 'wmt16_dev.tgz') - ], - test_urls=[ - ('http://data.statmt.org/wmt16/translation-task/test.tgz', 'wmt16_test.tgz') - ], - train_files_patterns=[ - ('*/*europarl-v8.{src}-{tgt}.{lang}', ['ro-en']), - ('bitext.{lang}', ['ro-en']) #setimes from tmux - ] , - valid_files_patterns=[ - ('dev/newsdev2016*{src}{tgt}*.{lang}', ['ro-en', 'ro-en']) - ], - test_files_patterns=[ - ('test/newstest*{src}{tgt}*.{lang}', ['ro-en', 'en-ro']) - ], -) - -cwmt_wmt_instruction = 'cwmt download instruction at: http://nlp.nju.edu.cn/cwmt-wmt' -wmt17_fi_lv_tr_zh_en_manual_downloads = [ - # fake urls to have unique keys for the data - ( ('http://nlp.nju.edu.cn/cwmt-wmt/CASIA2015.zip', 'CASIA2015.zip'), cwmt_wmt_instruction), - ( ('http://nlp.nju.edu.cn/cwmt-wmt/CASICT2011.zip', 'CASICT2011.zip'), cwmt_wmt_instruction), - ( ('http://nlp.nju.edu.cn/cwmt-wmt/CASICT2015.zip', 'CASICT2015.zip'), cwmt_wmt_instruction), - ( ('http://nlp.nju.edu.cn/cwmt-wmt/Datum2015.zip', 'Datum2015.zip'), cwmt_wmt_instruction), - ( ('http://nlp.nju.edu.cn/cwmt-wmt/Datum2017.zip', 'Datum2017.zip'), cwmt_wmt_instruction), - ( ('http://nlp.nju.edu.cn/cwmt-wmt/NEU2017.zip', 'NEU2017.zip'), cwmt_wmt_instruction), -] -wmt17_fi_lv_tr_zh_en = DLDataset( - name='wmt17_fi_lv_tr_zh_en', - train_urls=[ - ('http://data.statmt.org/wmt17/translation-task/training-parallel-ep-v8.tgz', 'wmt17_training-parallel-ep-v8.tgz'), - 'http://data.statmt.org/wmt17/translation-task/training-parallel-nc-v12.tgz', - 'http://www.statmt.org/wmt15/wiki-titles.tgz', - ('http://opus.nlpl.eu/download.php?f=SETIMES/v2/tmx/en-tr.tmx.gz', 'en-tr.tmx.gz'), - ('http://data.statmt.org/wmt17/translation-task/rapid2016.tgz', 'wmt17_rapid2016.tgz'), - 'http://data.statmt.org/wmt17/translation-task/leta.v1.tgz', - 'http://data.statmt.org/wmt17/translation-task/dcep.lv-en.v1.tgz', - 'http://data.statmt.org/wmt17/translation-task/books.lv-en.v1.tgz', - (('https://stuncorpusprod.blob.core.windows.net/corpusfiles/UNv1.0.en-zh.tar.gz.00', - 'https://stuncorpusprod.blob.core.windows.net/corpusfiles/UNv1.0.en-zh.tar.gz.01',), 'UNv1.0.en-zh.tar.gz'), - #manually download files: - ('http://nlp.nju.edu.cn/cwmt-wmt/CASIA2015.zip', 'CASIA2015.zip'), - ('http://nlp.nju.edu.cn/cwmt-wmt/CASICT2011.zip', 'CASICT2011.zip'), - ('http://nlp.nju.edu.cn/cwmt-wmt/CASICT2015.zip', 'CASICT2015.zip'), - ('http://nlp.nju.edu.cn/cwmt-wmt/Datum2015.zip', 'Datum2015.zip'), - ('http://nlp.nju.edu.cn/cwmt-wmt/Datum2017.zip', 'Datum2017.zip'), - ('http://nlp.nju.edu.cn/cwmt-wmt/NEU2017.zip', 'NEU2017.zip'), - ], - valid_urls=[ - ('http://data.statmt.org/wmt17/translation-task/dev.tgz', 'wmt17_dev.tgz'), - ], - test_urls=[ - #NEW: Improved translations for zh test sets - ('http://data.statmt.org/wmt17/translation-task/test-update-1.tgz', 'wmt17_test_zh_en.tgz'), - ('http://data.statmt.org/wmt17/translation-task/test.tgz', 'wmt17_test_others.tgz') - ], - train_files_patterns=[ - ('casict*/cas*{src:ch}{tgt:en}.txt', ['zh-en', 'zh-en'] ), - ('casia*/cas*{src:ch}{tgt:en}.txt', ['zh-en', 'zh-en'] ), - ('dataum*/Book*{src:cn}{tgt:en}.txt', ['zh-en', 'zh-en']), - ('neu*/NEU*{src:cn}{tgt:en}.txt', ['zh-en', 'zh-en'] ), - ('*/*UNv1.0.en-zh.{src:zh}{tgt:en}', ['zh-en']), - ('training/*news-commentary-v12.{src}-{tgt}.{lang}', ['zh-en', ]), - - ('*/*europarl-v8.{src}-{tgt}.{lang}', ['fi-en', 'lv-en']), - ('wiki/fi-en/titles.{src}-{tgt}.{lang}', ['fi-en', ]), - ('rapid2016.{tgt}-{src}.{lang}', ['fi-en', 'lv-en']), - ('*/leta.{lang}', ['lv-en']), - ('*/dcep.{lang}', ['lv-en']), - ('*/farewell.{lang}', ['lv-en']), - ('bitext.{lang}', ['tr-en']), - ] , - valid_files_patterns=[ - ('dev/newsdev2017*{src}{tgt}-{src:src}{tgt:ref}.{lang}', - [ - 'fi-en', 'lv-en', 'tr-en', 'zh-en', - 'en-fi', 'en-lv', 'en-tr', 'en-zh' - ]), - ('dev/newstest2016*{src}{tgt}-{src:src}{tgt:ref}.{lang}', - [ - 'fi-en', 'tr-en', - 'en-fi', 'en-tr', - ]), - ], - test_files_patterns=[ - ('test/newstest2017-{src}{tgt}-{src:src}{tgt:ref}.{lang}', - [ - 'fi-en', 'lv-en', 'tr-en', - 'en-fi', 'en-lv', 'en-tr', - ]), - ('newstest2017-{src}{tgt}-{src:src}{tgt:ref}.{lang}', - [ - 'zh-en', - 'en-zh' - ]), - ], -) - -czeng_instruction = 'download instruction at: http://ufal.mff.cuni.cz/czeng/czeng16' -#alternative: use the prepared data but detokenize it? -wmt18_cs_et_en_manual_downloads = [ -#for cs, need to register and download; Register and download CzEng 1.6. -#Better results can be obtained by using a subset of sentences, released under a new version name CzEng 1.7. - # ((f'http://ufallab.ms.mff.cuni.cz/~bojar/czeng16-data/data-plaintext-format.{i}.tar', - # f'data-plaintext-format.{i}.tar'), czeng_instruction) - # for i in range(10) -] - -wmt18_cs_et_en = DLDataset( - name='wmt18_cs_et_en', - train_urls=[ - 'http://www.statmt.org/wmt13/training-parallel-europarl-v7.tgz', - 'http://data.statmt.org/wmt18/translation-task/training-parallel-ep-v8.tgz', - 'https://s3.amazonaws.com/web-language-models/paracrawl/release1/paracrawl-release1.en-cs.zipporah0-dedup-clean.tgz', - 'https://s3.amazonaws.com/web-language-models/paracrawl/release1/paracrawl-release1.en-et.zipporah0-dedup-clean.tgz', - 'http://www.statmt.org/wmt13/training-parallel-commoncrawl.tgz', - 'http://data.statmt.org/wmt18/translation-task/training-parallel-nc-v13.tgz', - ('http://data.statmt.org/wmt18/translation-task/rapid2016.tgz', 'wmt18_rapid2016.tgz'), - # (tuple( - # (f'http://ufallab.ms.mff.cuni.cz/~bojar/czeng16-data/data-plaintext-format.{i}.tar', - # f'data-plaintext-format.{i}.tar') - # for i in range(10) - # ), - # 'czeng16_data_plaintext.gz.tar'), - ], - valid_urls=[ - ('http://data.statmt.org/wmt18/translation-task/dev.tgz', 'wmt18_dev.tgz'), - ], - test_urls=[ - ('http://data.statmt.org/wmt18/translation-task/test.tgz', 'wmt18_test.tgz'), - ], - train_files_patterns=[ - # ('*/*europarl-v7.{src}-{tgt}.{lang}', ['cs-en']), - ('*/*europarl-v8.{src}-{tgt}.{lang}', ['et-en']), - # ('*paracrawl-release1.{tgt}-{src}.zipporah0-dedup-clean.{lang}', ['cs-en', 'et-en']), - ('*paracrawl-release1.{tgt}-{src}.zipporah0-dedup-clean.{lang}', ['et-en']), - # ('*commoncrawl.{src}-{tgt}.{lang}', ['cs-en']), - # ('*/news-commentary-v13.{src}-{tgt}.{lang}', ['cs-en']), - # ('data.plaintext-format/*train.{lang}', ['cs-en']), - ('rapid2016.{tgt}-{src}.{lang}', ['et-en']), - ] , - valid_files_patterns=[ - ('dev/newsdev2018*{src}{tgt}-{src:src}{tgt:ref}.{lang}', ['et-en']), - # ('dev/newstest2017*{src}{tgt}-{src:src}{tgt:ref}.{lang}', ['cs-en']) - ], - test_files_patterns=[ - ('test/newstest2018-{src}{tgt}-{src:src}{tgt:ref}.{lang}', - # ['cs-en', 'et-en']), - ['et-en']), - ] -) - -ru_en_yandex_instruction = 'Yandex Corpus download instruction at: https://translate.yandex.ru/corpus?lang=en' -wmt19_ru_gu_kk_lt_manual_downloads = [ - (('https://translate.yandex.ru/corpus?lang=en', 'wmt19_1mcorpus.zip'), ru_en_yandex_instruction) -] -wmt19_ru_gu_kk_lt = DLDataset( - name='wmt19_ru_gu_kk_lt', - train_urls=[ - 'http://www.statmt.org/europarl/v9/training/europarl-v9.lt-en.tsv.gz', - 'https://s3.amazonaws.com/web-language-models/paracrawl/release3/en-lt.bicleaner07.tmx.gz', - 'https://s3.amazonaws.com/web-language-models/paracrawl/release1/paracrawl-release1.en-ru.zipporah0-dedup-clean.tgz', - 'http://www.statmt.org/wmt13/training-parallel-commoncrawl.tgz', - 'http://data.statmt.org/news-commentary/v14/training/news-commentary-v14-wmt19.en-kk.tsv.gz', - 'http://data.statmt.org/news-commentary/v14/training/news-commentary-v14.en-ru.tsv.gz', - 'http://data.statmt.org/wikititles/v1/wikititles-v1.kk-en.tsv.gz', - 'http://data.statmt.org/wikititles/v1/wikititles-v1.ru-en.tsv.gz', - 'http://data.statmt.org/wikititles/v1/wikititles-v1.kk-en.tsv.gz', - 'http://data.statmt.org/wikititles/v1/wikititles-v1.lt-en.tsv.gz', - 'http://data.statmt.org/wikititles/v1/wikititles-v1.gu-en.tsv.gz', - (('https://stuncorpusprod.blob.core.windows.net/corpusfiles/UNv1.0.en-ru.tar.gz.00', - 'https://stuncorpusprod.blob.core.windows.net/corpusfiles/UNv1.0.en-ru.tar.gz.01', - 'https://stuncorpusprod.blob.core.windows.net/corpusfiles/UNv1.0.en-ru.tar.gz.02',), - 'wmt19_UNv1.0.en-ru.tar.gz'), - 'https://tilde-model.s3-eu-west-1.amazonaws.com/rapid2016.en-lt.tmx.zip', - ('https://translate.yandex.ru/corpus?lang=en', 'wmt19_1mcorpus.zip'), - ], - valid_urls=[ - ('http://data.statmt.org/wmt19/translation-task/dev.tgz', 'wmt19_dev.tgz'), - ], - test_urls=[ - ('http://data.statmt.org/wmt19/translation-task/test.tgz', 'wmt19_test.tgz'), - ], - train_files_patterns=[ - ('*europarl-v9.{src}-{tgt}.tsv.{lang}', ['lt-en']), - #paracrawl - ('*paracrawl-release1.{tgt}-{src}.zipporah0-dedup-clean.{lang}', ['ru-en']), - ('bitext.{lang}', ['lt-en',]), - ('*commoncrawl.{src}-{tgt}.{lang}', ['ru-en',]), - ('*news-commentary-v14-wmt19.{tgt}-{src}.tsv.{lang}', ['kk-en', ]), - ('*news-commentary-v14.{tgt}-{src}.tsv.{lang}', ['ru-en']), - #yandex - ('corpus.{tgt}_{src}.1m.{lang}', ['ru-en']), - ('wikititles_v1_wikititles-v1.{src}-{tgt}.tsv.{lang}', ['ru-en', 'kk-en', 'lt-en', 'gu-en']), - ('*/UNv1.0.{tgt}-{src}.{lang}', ['ru-en']), - #rapid - ('bitext.{lang}', ['lt-en']) - ], - valid_files_patterns=[ - ('dev/newsdev2019*{src}{tgt}-{src:src}{tgt:ref}.{lang}', ['gu-en', 'kk-en', 'lt-en']), - ('dev/newstest2018*{src}{tgt}-{src:src}{tgt:ref}.{lang}', ['ru-en']), - ], - test_files_patterns=[ - ('sgm/newstest2019-{src}{tgt}-{src:src}{tgt:ref}.{lang}', - ['ru-en', 'gu-en', 'kk-en', 'lt-en', 'en-ru', 'en-gu', 'en-kk', 'en-lt']), - ] -) - - -######### - -if __name__ == "__main__": - # speed up the downloads with multiple processing - dl_folder = f'{to_data_path}/downloads' - extract_folder = f'{to_data_path}/extracted' - - urls = [ - url - for dataset in [wmt13_es_en, wmt14_de_fr_en, wmt16_ro_en, wmt18_cs_et_en, wmt19_ru_gu_kk_lt] - for urls in [dataset.train_urls, dataset.valid_urls, dataset.test_urls] - for url in urls - ] - urls = set(urls) - download_multi(dl_folder, extract_folder, urls, num_processes=8, debug=True) - - # check manually downlaods - to_manually_download_urls = ( - wmt17_fi_lv_tr_zh_en_manual_downloads + wmt18_cs_et_en_manual_downloads + wmt19_ru_gu_kk_lt_manual_downloads - ) - to_be_manually_dowloaded = check_need_manual_downalod(dl_folder, to_manually_download_urls) - if len(to_be_manually_dowloaded) > 0: - print('Missing files that need to be downloaded manually; stop the process now.') - exit(-1) - - completed_urls = {} - completed_extraction = {} - def work_on_wmt(directions, wmt_data): - download_and_extract( - to_data_path, - directions, - wmt_data, - to_manually_download_urls=to_manually_download_urls, - completed_urls=completed_urls, completed_extraction=completed_extraction, debug=True) - - work_on_wmt( - ['es_XX-en_XX'], - wmt13_es_en,) - work_on_wmt( - [ - 'fr_XX-en_XX', 'en_XX-fr_XX', - # 'en_XX-de_DE', 'de_DE-en_XX', - ], - wmt14_de_fr_en,) - work_on_wmt( - ['ro_RO-en_XX', 'en_XX-ro_XX'], - wmt16_ro_en,) - work_on_wmt( - [ - # 'zh_CN-en_XX', - 'lv_LV-en_XX', 'fi_FI-en_XX', 'tr_TR-en_XX', - #in case the reversed directions have different train/valid/test data - # 'en_XX-zh_CN', - 'en_XX-lv_LV', 'en_XX-fi_FI', 'en_XX-tr_TR', - ], - wmt17_fi_lv_tr_zh_en, ) - # czeng17_script_path = download_czeng17_script(download_to, extract_to, debug=False) - # cz_username = None - work_on_wmt( - [ - # 'cs_CZ-en_XX', - 'et_EE-en_XX'], - wmt18_cs_et_en,) - work_on_wmt( - [ - # 'ru_RU-en_XX', 'en_XX-ru_RU', - 'gu_IN-en_XX', 'kk_KZ-en_XX', 'lt_LT-en_XX', - #in case the reversed directions have different train/valid/test data - 'en_XX-gu_IN', 'en_XX-kk_KZ', 'en_XX-lt_LT' - ], - wmt19_ru_gu_kk_lt,) - - not_matching = check_wmt_test_bleu( - f'{to_data_path}/raw', - [ - ('wmt13', ['es_XX-en_XX']), - ('wmt14/full', ['fr_XX-en_XX',]), - ('wmt16', ['ro_RO-en_XX',]), - # ('wmt17/improved', ['zh_CN-en_XX']), - ('wmt17', [ 'lv_LV-en_XX', 'fi_FI-en_XX', 'tr_TR-en_XX']), - ('wmt18', ['cs_CZ-en_XX', 'et_EE-en_XX']), - ('wmt19', ['gu_IN-en_XX', 'kk_KZ-en_XX', 'lt_LT-en_XX']), - #'ru_RU-en_XX', - ] - ) - if len(not_matching) > 0: - print('the following datasets do not have matching test datasets:\n\t', '\n\t'.join(not_matching)) - diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/simultaneous_translation/utils/functions.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/simultaneous_translation/utils/functions.py deleted file mode 100644 index 590a6c11cea222ac9096b19f0e3dfe1b71b6c10b..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/simultaneous_translation/utils/functions.py +++ /dev/null @@ -1,125 +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 - - -def prob_check(tensor, eps=1e-10): - assert not torch.isnan(tensor).any(), ( - "Nan in a probability tensor." - ) - # Add the eps here to prevent errors introduced by precision - assert tensor.le(1.0 + eps).all() and tensor.ge(0.0 - eps).all(), ( - "Incorrect values in a probability tensor" - ", 0.0 <= tensor <= 1.0" - ) - - -def exclusive_cumprod(tensor, dim: int, eps: float = 1e-10): - """ - Implementing exclusive cumprod. - There is cumprod in pytorch, however there is no exclusive mode. - cumprod(x) = [x1, x1x2, x2x3x4, ..., prod_{i=1}^n x_i] - exclusive means - cumprod(x) = [1, x1, x1x2, x1x2x3, ..., prod_{i=1}^{n-1} x_i] - """ - tensor_size = list(tensor.size()) - tensor_size[dim] = 1 - return_tensor = safe_cumprod( - torch.cat([torch.ones(tensor_size).type_as(tensor), tensor], dim=dim), - dim=dim, - eps=eps, - ) - - if dim == 0: - return return_tensor[:-1] - elif dim == 1: - return return_tensor[:, :-1] - elif dim == 2: - return return_tensor[:, :, :-1] - else: - raise RuntimeError( - "Cumprod on dimension 3 and more is not implemented" - ) - - -def safe_cumprod(tensor, dim: int, eps: float = 1e-10): - """ - An implementation of cumprod to prevent precision issue. - cumprod(x) - = [x1, x1x2, x1x2x3, ....] - = [exp(log(x1)), exp(log(x1) + log(x2)), exp(log(x1) + log(x2) + log(x3)), ...] - = exp(cumsum(log(x))) - """ - - if (tensor + eps < 0).any().item(): - raise RuntimeError( - "Safe cumprod can only take non-negative tensors as input." - "Consider use torch.cumprod if you want to calculate negative values." - ) - - log_tensor = torch.log(tensor + eps) - cumsum_log_tensor = torch.cumsum(log_tensor, dim) - exp_cumsum_log_tensor = torch.exp(cumsum_log_tensor) - return exp_cumsum_log_tensor - - -def moving_sum(x, start_idx: int, end_idx: int): - """ - From MONOTONIC CHUNKWISE ATTENTION - https://arxiv.org/pdf/1712.05382.pdf - Equation (18) - - x = [x_1, x_2, ..., x_N] - MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m - for n in {1, 2, 3, ..., N} - - x : src_len, batch_size - start_idx : start idx - end_idx : end idx - - Example - src_len = 5 - batch_size = 3 - x = - [[ 0, 5, 10], - [ 1, 6, 11], - [ 2, 7, 12], - [ 3, 8, 13], - [ 4, 9, 14]] - - MovingSum(x, 3, 1) = - [[ 0, 5, 10], - [ 1, 11, 21], - [ 3, 18, 33], - [ 6, 21, 36], - [ 9, 24, 39]] - - MovingSum(x, 1, 3) = - [[ 3, 18, 33], - [ 6, 21, 36], - [ 9, 24, 39], - [ 7, 17, 27], - [ 4, 9, 14]] - """ - # TODO: Make dimension configurable - assert start_idx > 0 and end_idx > 0 - batch_size, tgt_len, src_len = x.size() - x = x.view(-1, src_len).unsqueeze(1) - # batch_size, 1, src_len - moving_sum_weight = torch.ones([1, 1, end_idx + start_idx - 1]).type_as(x) - - moving_sum = torch.nn.functional.conv1d( - x, moving_sum_weight, padding=start_idx + end_idx - 1 - ).squeeze(1) - - moving_sum = moving_sum[:, end_idx:-start_idx] - - assert src_len == moving_sum.size(1) - assert batch_size * tgt_len == moving_sum.size(0) - - moving_sum = moving_sum.view(batch_size, tgt_len, src_len) - - return moving_sum diff --git a/spaces/HarshulNanda/EngHindi/app.py b/spaces/HarshulNanda/EngHindi/app.py deleted file mode 100644 index 7841a309e482bcde29782b09b6142745eb565aa7..0000000000000000000000000000000000000000 --- a/spaces/HarshulNanda/EngHindi/app.py +++ /dev/null @@ -1,53 +0,0 @@ -import gradio as gr -import pickle -import pandas as pd -import warnings -warnings.filterwarnings('ignore') - -model = pickle.load(open("hinglish_vs_english_model_no_GPU_2.0.pkl", 'rb')) # version 2.0 - -def classify_text(text): - text_to_predict = pd.DataFrame({ - "Text": [ - text - ] - }) - predictions, output_directory = model.predict(text_to_predict) - return list(predictions["Label_predictions"])[0] - -inputs = gr.inputs.Textbox(lines=5, label="Enter text", placeholder="Aur bhai, kaisa hai re tu, tune bataya nhi tere kitne marks aaye last examination me") -outputs = gr.outputs.Label(label="Prediction") - -gr.Interface( - fn = classify_text, - inputs=inputs, - outputs=outputs, - title="EngHindi", - description="Enter some text and get a prediction of whether it's in Hinglish or English.", - examples = [ - "Hi! Kya haal chaal hai?", - "How are you doing today?", - "Aaj ka mausam kaisa hai?", - "What is the weather like today?", - "Kya aap mujhe bata sakte hain ki yahaan kahaan se bhojan khana hai?", - "Can you tell me where to get food around here?", - "Main aapki help kar sakta hoon.", - "I can help you with that.", - "Mujhe ye samajh nahi aa raha hai.", - "I don't understand this.", - "Kal raat ko maine bahut der tak kaam kiya tha.", - "I worked very late last night.", - "Yeh kya hai?", - "What is this?", - "Main yahaan nahi ruk sakta.", - "I can't stay here.", - "Aaj meri shaadi hai.", - "Today is my wedding day.", - "Kyun aisa karte ho?", - "The most bad thing about this show was the speech that he gave, so bad.", - "The shit you hear about me might be true or it might be faker than the bitch who told it to ya", - "Aur bhai, kaisa hai re tu, tune bataya nhi tere kitne marks aaye last examination me.", - ], - theme = "darkhuggingface", - live = True, -).launch(inline=False) \ No newline at end of file diff --git a/spaces/Harveenchadha/Vakyansh-Malayalam-TTS/ttsv/src/glow_tts/init.py b/spaces/Harveenchadha/Vakyansh-Malayalam-TTS/ttsv/src/glow_tts/init.py deleted file mode 100644 index 39dd83dbd55475d562a3f54d951cb822800d2e0f..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/Vakyansh-Malayalam-TTS/ttsv/src/glow_tts/init.py +++ /dev/null @@ -1,79 +0,0 @@ -import os -import json -import argparse -import math -import torch -from torch import nn, optim -from torch.nn import functional as F -from torch.utils.data import DataLoader - -from data_utils import TextMelLoader, TextMelCollate -import models -import commons -import utils - - -class FlowGenerator_DDI(models.FlowGenerator): - """A helper for Data-dependent Initialization""" - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - for f in self.decoder.flows: - if getattr(f, "set_ddi", False): - f.set_ddi(True) - - -def main(): - hps = utils.get_hparams() - logger = utils.get_logger(hps.log_dir) - logger.info(hps) - utils.check_git_hash(hps.log_dir) - - torch.manual_seed(hps.train.seed) - - train_dataset = TextMelLoader(hps.data.training_files, hps.data) - collate_fn = TextMelCollate(1) - train_loader = DataLoader( - train_dataset, - num_workers=8, - shuffle=True, - batch_size=hps.train.batch_size, - pin_memory=True, - drop_last=True, - collate_fn=collate_fn, - ) - symbols = hps.data.punc + hps.data.chars - generator = FlowGenerator_DDI( - len(symbols) + getattr(hps.data, "add_blank", False), - out_channels=hps.data.n_mel_channels, - **hps.model - ).cuda() - optimizer_g = commons.Adam( - generator.parameters(), - scheduler=hps.train.scheduler, - dim_model=hps.model.hidden_channels, - warmup_steps=hps.train.warmup_steps, - lr=hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps, - ) - - generator.train() - for batch_idx, (x, x_lengths, y, y_lengths) in enumerate(train_loader): - x, x_lengths = x.cuda(), x_lengths.cuda() - y, y_lengths = y.cuda(), y_lengths.cuda() - - _ = generator(x, x_lengths, y, y_lengths, gen=False) - break - - utils.save_checkpoint( - generator, - optimizer_g, - hps.train.learning_rate, - 0, - os.path.join(hps.model_dir, "ddi_G.pth"), - ) - - -if __name__ == "__main__": - main() diff --git a/spaces/Heckeroo/waifu-diffusion/app.py b/spaces/Heckeroo/waifu-diffusion/app.py deleted file mode 100644 index ccef706bf3035fe470bf6a4f5bd701b18bf59133..0000000000000000000000000000000000000000 --- a/spaces/Heckeroo/waifu-diffusion/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/hakurei/waifu-diffusion").launch() \ No newline at end of file diff --git a/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.7b27e54c.js b/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.7b27e54c.js deleted file mode 100644 index bd6998add382231dfdd916a3cc399e0d2b461a98..0000000000000000000000000000000000000000 --- a/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.7b27e54c.js +++ /dev/null @@ -1,2 +0,0 @@ -import{S as s,i as o,s as a}from"./index.396f4a72.js";class n extends s{constructor(e){super(),o(this,e,null,null,a,{})}}var i=n;const l=["static"],r=t=>({type:"Any",description:"stored state value",example_data:""});export{i as Component,r as document,l as modes}; -//# sourceMappingURL=index.7b27e54c.js.map diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/models/fairseq_model.py b/spaces/ICML2022/OFA/fairseq/fairseq/models/fairseq_model.py deleted file mode 100644 index e55c7ba1ad90f4e2f12db6c814d04a90c4e3b77c..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/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/ICML2022/OFA/fairseq/fairseq/models/speech_to_text/s2t_transformer.py b/spaces/ICML2022/OFA/fairseq/fairseq/models/speech_to_text/s2t_transformer.py deleted file mode 100644 index aff9d0ffc7b7e671c476ff28d1cd945e9ff41519..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/models/speech_to_text/s2t_transformer.py +++ /dev/null @@ -1,502 +0,0 @@ -#!/usr/bin/env python3 - -import logging -import math -from typing import Dict, List, Optional, Tuple -from pathlib import Path - -import torch -import torch.nn as nn -from fairseq import checkpoint_utils, utils -from fairseq.data.data_utils import lengths_to_padding_mask -from fairseq.models import ( - FairseqEncoder, - FairseqEncoderDecoderModel, - register_model, - register_model_architecture, -) -from fairseq.models.transformer import Embedding, TransformerDecoder -from fairseq.modules import ( - FairseqDropout, - LayerNorm, - PositionalEmbedding, - TransformerEncoderLayer, -) -from torch import Tensor - - -logger = logging.getLogger(__name__) - - -class Conv1dSubsampler(nn.Module): - """Convolutional subsampler: a stack of 1D convolution (along temporal - dimension) followed by non-linear activation via gated linear units - (https://arxiv.org/abs/1911.08460) - - Args: - in_channels (int): the number of input channels - mid_channels (int): the number of intermediate channels - out_channels (int): the number of output channels - kernel_sizes (List[int]): the kernel size for each convolutional layer - """ - - def __init__( - self, - in_channels: int, - mid_channels: int, - out_channels: int, - kernel_sizes: List[int] = (3, 3), - ): - super(Conv1dSubsampler, self).__init__() - self.n_layers = len(kernel_sizes) - self.conv_layers = nn.ModuleList( - nn.Conv1d( - in_channels if i == 0 else mid_channels // 2, - mid_channels if i < self.n_layers - 1 else out_channels * 2, - k, - stride=2, - padding=k // 2, - ) - for i, k in enumerate(kernel_sizes) - ) - - def get_out_seq_lens_tensor(self, in_seq_lens_tensor): - out = in_seq_lens_tensor.clone() - for _ in range(self.n_layers): - out = ((out.float() - 1) / 2 + 1).floor().long() - return out - - def forward(self, src_tokens, src_lengths): - bsz, in_seq_len, _ = src_tokens.size() # B x T x (C x D) - x = src_tokens.transpose(1, 2).contiguous() # -> B x (C x D) x T - for conv in self.conv_layers: - x = conv(x) - x = nn.functional.glu(x, dim=1) - _, _, out_seq_len = x.size() - x = x.transpose(1, 2).transpose(0, 1).contiguous() # -> T x B x (C x D) - return x, self.get_out_seq_lens_tensor(src_lengths) - - -@register_model("s2t_transformer") -class S2TTransformerModel(FairseqEncoderDecoderModel): - """Adapted Transformer model (https://arxiv.org/abs/1706.03762) for - speech-to-text tasks. The Transformer encoder/decoder remains the same. - A trainable input subsampler is prepended to the Transformer encoder to - project inputs into the encoder dimension as well as downsample input - sequence for computational efficiency.""" - - def __init__(self, encoder, decoder): - super().__init__(encoder, decoder) - - @staticmethod - def add_args(parser): - """Add model-specific arguments to the parser.""" - # input - parser.add_argument( - "--conv-kernel-sizes", - type=str, - metavar="N", - help="kernel sizes of Conv1d subsampling layers", - ) - parser.add_argument( - "--conv-channels", - type=int, - metavar="N", - help="# of channels in Conv1d subsampling layers", - ) - # Transformer - parser.add_argument( - "--activation-fn", - type=str, - default="relu", - choices=utils.get_available_activation_fns(), - help="activation function to use", - ) - parser.add_argument( - "--dropout", type=float, metavar="D", help="dropout probability" - ) - parser.add_argument( - "--attention-dropout", - type=float, - metavar="D", - help="dropout probability for attention weights", - ) - parser.add_argument( - "--activation-dropout", - "--relu-dropout", - type=float, - metavar="D", - help="dropout probability after activation in FFN.", - ) - parser.add_argument( - "--encoder-embed-dim", - type=int, - metavar="N", - help="encoder embedding dimension", - ) - parser.add_argument( - "--encoder-ffn-embed-dim", - type=int, - metavar="N", - help="encoder embedding dimension for FFN", - ) - parser.add_argument( - "--encoder-layers", type=int, metavar="N", help="num encoder layers" - ) - parser.add_argument( - "--encoder-attention-heads", - type=int, - metavar="N", - help="num encoder attention heads", - ) - parser.add_argument( - "--encoder-normalize-before", - action="store_true", - help="apply layernorm before each encoder block", - ) - parser.add_argument( - "--decoder-embed-dim", - type=int, - metavar="N", - help="decoder embedding dimension", - ) - parser.add_argument( - "--decoder-ffn-embed-dim", - type=int, - metavar="N", - help="decoder embedding dimension for FFN", - ) - parser.add_argument( - "--decoder-layers", type=int, metavar="N", help="num decoder layers" - ) - parser.add_argument( - "--decoder-attention-heads", - type=int, - metavar="N", - help="num decoder attention heads", - ) - parser.add_argument( - "--decoder-normalize-before", - action="store_true", - help="apply layernorm before each decoder block", - ) - parser.add_argument( - "--share-decoder-input-output-embed", - action="store_true", - help="share decoder input and output embeddings", - ) - parser.add_argument( - "--layernorm-embedding", - action="store_true", - help="add layernorm to embedding", - ) - parser.add_argument( - "--no-scale-embedding", - action="store_true", - help="if True, dont scale embeddings", - ) - parser.add_argument( - "--load-pretrained-encoder-from", - type=str, - metavar="STR", - help="model to take encoder weights from (for initialization)", - ) - parser.add_argument( - '--encoder-freezing-updates', - type=int, - metavar='N', - help='freeze encoder for first N updates' - ) - - @classmethod - def build_encoder(cls, args): - encoder = S2TTransformerEncoder(args) - pretraining_path = getattr(args, "load_pretrained_encoder_from", None) - if pretraining_path is not None: - if not Path(pretraining_path).exists(): - logger.warning( - f"skipped pretraining because {pretraining_path} does not exist" - ) - else: - encoder = checkpoint_utils.load_pretrained_component_from_model( - component=encoder, checkpoint=pretraining_path - ) - logger.info(f"loaded pretrained encoder from: {pretraining_path}") - return encoder - - @classmethod - def build_decoder(cls, args, task, embed_tokens): - return TransformerDecoderScriptable(args, task.target_dictionary, embed_tokens) - - @classmethod - def build_model(cls, args, task): - """Build a new model instance.""" - - # make sure all arguments are present in older models - base_architecture(args) - - def build_embedding(dictionary, embed_dim): - num_embeddings = len(dictionary) - padding_idx = dictionary.pad() - return Embedding(num_embeddings, embed_dim, padding_idx) - - decoder_embed_tokens = build_embedding( - task.target_dictionary, args.decoder_embed_dim - ) - encoder = cls.build_encoder(args) - decoder = cls.build_decoder(args, task, decoder_embed_tokens) - return cls(encoder, decoder) - - def get_normalized_probs( - self, - net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], - log_probs: bool, - sample: Optional[Dict[str, Tensor]] = None, - ): - # net_output['encoder_out'] is a (B, T, D) tensor - lprobs = self.get_normalized_probs_scriptable(net_output, log_probs, sample) - lprobs.batch_first = True - return lprobs - - def forward(self, src_tokens, src_lengths, prev_output_tokens): - """ - The forward method inherited from the base class has a **kwargs - argument in its input, which is not supported in torchscript. This - method overwrites the forward method definition without **kwargs. - """ - encoder_out = self.encoder(src_tokens=src_tokens, src_lengths=src_lengths) - decoder_out = self.decoder( - prev_output_tokens=prev_output_tokens, encoder_out=encoder_out - ) - return decoder_out - - -class S2TTransformerEncoder(FairseqEncoder): - """Speech-to-text Transformer encoder that consists of input subsampler and - Transformer encoder.""" - - def __init__(self, args): - super().__init__(None) - - self.encoder_freezing_updates = args.encoder_freezing_updates - self.num_updates = 0 - - self.dropout_module = FairseqDropout( - p=args.dropout, module_name=self.__class__.__name__ - ) - self.embed_scale = math.sqrt(args.encoder_embed_dim) - if args.no_scale_embedding: - self.embed_scale = 1.0 - self.padding_idx = 1 - - self.subsample = Conv1dSubsampler( - args.input_feat_per_channel * args.input_channels, - args.conv_channels, - args.encoder_embed_dim, - [int(k) for k in args.conv_kernel_sizes.split(",")], - ) - - self.embed_positions = PositionalEmbedding( - args.max_source_positions, args.encoder_embed_dim, self.padding_idx - ) - - self.transformer_layers = nn.ModuleList( - [TransformerEncoderLayer(args) for _ in range(args.encoder_layers)] - ) - if args.encoder_normalize_before: - self.layer_norm = LayerNorm(args.encoder_embed_dim) - else: - self.layer_norm = None - - def _forward(self, src_tokens, src_lengths, return_all_hiddens=False): - x, input_lengths = self.subsample(src_tokens, src_lengths) - x = self.embed_scale * x - - encoder_padding_mask = lengths_to_padding_mask(input_lengths) - positions = self.embed_positions(encoder_padding_mask).transpose(0, 1) - x += positions - x = self.dropout_module(x) - - encoder_states = [] - - for layer in self.transformer_layers: - x = layer(x, encoder_padding_mask) - if return_all_hiddens: - encoder_states.append(x) - - if self.layer_norm is not None: - x = self.layer_norm(x) - - return { - "encoder_out": [x], # T x B x C - "encoder_padding_mask": [encoder_padding_mask] if encoder_padding_mask.any() else [], # B x T - "encoder_embedding": [], # B x T x C - "encoder_states": encoder_states, # List[T x B x C] - "src_tokens": [], - "src_lengths": [], - } - - def forward(self, src_tokens, src_lengths, return_all_hiddens=False): - if self.num_updates < self.encoder_freezing_updates: - with torch.no_grad(): - x = self._forward(src_tokens, src_lengths, - return_all_hiddens=return_all_hiddens) - else: - x = self._forward(src_tokens, src_lengths, - return_all_hiddens=return_all_hiddens) - return x - - def reorder_encoder_out(self, encoder_out, new_order): - new_encoder_out = ( - [] if len(encoder_out["encoder_out"]) == 0 - else [x.index_select(1, new_order) for x in encoder_out["encoder_out"]] - ) - - new_encoder_padding_mask = ( - [] if len(encoder_out["encoder_padding_mask"]) == 0 - else [x.index_select(0, new_order) for x in encoder_out["encoder_padding_mask"]] - ) - - new_encoder_embedding = ( - [] if len(encoder_out["encoder_embedding"]) == 0 - else [x.index_select(0, new_order) for x in encoder_out["encoder_embedding"]] - ) - - encoder_states = encoder_out["encoder_states"] - if len(encoder_states) > 0: - for idx, state in enumerate(encoder_states): - encoder_states[idx] = state.index_select(1, new_order) - - return { - "encoder_out": new_encoder_out, # T x B x C - "encoder_padding_mask": new_encoder_padding_mask, # B x T - "encoder_embedding": new_encoder_embedding, # B x T x C - "encoder_states": encoder_states, # List[T x B x C] - "src_tokens": [], # B x T - "src_lengths": [], # B x 1 - } - - def set_num_updates(self, num_updates): - super().set_num_updates(num_updates) - self.num_updates = num_updates - - -class TransformerDecoderScriptable(TransformerDecoder): - def extract_features( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]] = None, - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - ): - # call scriptable method from parent class - x, _ = self.extract_features_scriptable( - prev_output_tokens, - encoder_out, - incremental_state, - full_context_alignment, - alignment_layer, - alignment_heads, - ) - return x, None - - -@register_model_architecture(model_name="s2t_transformer", arch_name="s2t_transformer") -def base_architecture(args): - args.encoder_freezing_updates = getattr(args, "encoder_freezing_updates", 0) - # Convolutional subsampler - args.conv_kernel_sizes = getattr(args, "conv_kernel_sizes", "5,5") - args.conv_channels = getattr(args, "conv_channels", 1024) - # Transformer - args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) - args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048) - args.encoder_layers = getattr(args, "encoder_layers", 12) - args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8) - args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True) - args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim) - args.decoder_ffn_embed_dim = getattr( - args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim - ) - args.decoder_layers = getattr(args, "decoder_layers", 6) - args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8) - args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True) - args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False) - args.dropout = getattr(args, "dropout", 0.1) - args.attention_dropout = getattr(args, "attention_dropout", args.dropout) - args.activation_dropout = getattr(args, "activation_dropout", args.dropout) - args.activation_fn = getattr(args, "activation_fn", "relu") - args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None) - args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0) - args.share_decoder_input_output_embed = getattr( - args, "share_decoder_input_output_embed", False - ) - args.no_token_positional_embeddings = getattr( - args, "no_token_positional_embeddings", False - ) - args.adaptive_input = getattr(args, "adaptive_input", False) - args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0.0) - args.decoder_output_dim = getattr( - args, "decoder_output_dim", args.decoder_embed_dim - ) - args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim) - args.no_scale_embedding = getattr(args, "no_scale_embedding", False) - args.quant_noise_pq = getattr(args, "quant_noise_pq", 0) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_s") -def s2t_transformer_s(args): - args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256) - args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 256 * 8) - args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4) - args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4) - args.dropout = getattr(args, "dropout", 0.1) - base_architecture(args) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_xs") -def s2t_transformer_xs(args): - args.encoder_layers = getattr(args, "encoder_layers", 6) - args.decoder_layers = getattr(args, "decoder_layers", 3) - args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 256 * 4) - args.dropout = getattr(args, "dropout", 0.3) - s2t_transformer_s(args) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_sp") -def s2t_transformer_sp(args): - args.encoder_layers = getattr(args, "encoder_layers", 16) - s2t_transformer_s(args) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_m") -def s2t_transformer_m(args): - args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) - args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 512 * 4) - args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8) - args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8) - args.dropout = getattr(args, "dropout", 0.15) - base_architecture(args) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_mp") -def s2t_transformer_mp(args): - args.encoder_layers = getattr(args, "encoder_layers", 16) - s2t_transformer_m(args) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_l") -def s2t_transformer_l(args): - args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024) - args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 1024 * 4) - args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16) - args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16) - args.dropout = getattr(args, "dropout", 0.2) - base_architecture(args) - - -@register_model_architecture("s2t_transformer", "s2t_transformer_lp") -def s2t_transformer_lp(args): - args.encoder_layers = getattr(args, "encoder_layers", 16) - s2t_transformer_l(args) diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/sequence_generator.py b/spaces/ICML2022/OFA/fairseq/fairseq/sequence_generator.py deleted file mode 100644 index 2e61140dd834210cfd7ecc14808951f4709c3519..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/sequence_generator.py +++ /dev/null @@ -1,973 +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 -from typing import Dict, List, Optional -import sys - -import torch -import torch.nn as nn -from fairseq import search, utils -from fairseq.data import data_utils -from fairseq.models import FairseqIncrementalDecoder -from torch import Tensor -from fairseq.ngram_repeat_block import NGramRepeatBlock - - -class SequenceGenerator(nn.Module): - def __init__( - self, - models, - tgt_dict, - beam_size=1, - max_len_a=0, - max_len_b=200, - max_len=0, - min_len=1, - normalize_scores=True, - len_penalty=1.0, - unk_penalty=0.0, - temperature=1.0, - match_source_len=False, - no_repeat_ngram_size=0, - search_strategy=None, - eos=None, - symbols_to_strip_from_output=None, - lm_model=None, - lm_weight=1.0, - ): - """Generates translations of a given source sentence. - - Args: - models (List[~fairseq.models.FairseqModel]): ensemble of models, - currently support fairseq.models.TransformerModel for scripting - beam_size (int, optional): beam width (default: 1) - max_len_a/b (int, optional): generate sequences of maximum length - ax + b, where x is the source length - max_len (int, optional): the maximum length of the generated output - (not including end-of-sentence) - min_len (int, optional): the minimum length of the generated output - (not including end-of-sentence) - normalize_scores (bool, optional): normalize scores by the length - of the output (default: True) - len_penalty (float, optional): length penalty, where <1.0 favors - shorter, >1.0 favors longer sentences (default: 1.0) - unk_penalty (float, optional): unknown word penalty, where <0 - produces more unks, >0 produces fewer (default: 0.0) - temperature (float, optional): temperature, where values - >1.0 produce more uniform samples and values <1.0 produce - sharper samples (default: 1.0) - match_source_len (bool, optional): outputs should match the source - length (default: False) - """ - super().__init__() - if isinstance(models, EnsembleModel): - self.model = models - else: - self.model = EnsembleModel(models) - self.tgt_dict = tgt_dict - self.pad = tgt_dict.pad() - self.unk = tgt_dict.unk() - self.eos = tgt_dict.eos() if eos is None else eos - self.symbols_to_strip_from_output = ( - symbols_to_strip_from_output.union({self.eos}) - if symbols_to_strip_from_output is not None - else {self.eos} - ) - self.vocab_size = len(tgt_dict) - self.beam_size = beam_size - # the max beam size is the dictionary size - 1, since we never select pad - self.beam_size = min(beam_size, self.vocab_size - 1) - self.max_len_a = max_len_a - self.max_len_b = max_len_b - self.min_len = min_len - self.max_len = max_len or self.model.max_decoder_positions() - - self.normalize_scores = normalize_scores - self.len_penalty = len_penalty - self.unk_penalty = unk_penalty - self.temperature = temperature - self.match_source_len = match_source_len - - if no_repeat_ngram_size > 0: - self.repeat_ngram_blocker = NGramRepeatBlock(no_repeat_ngram_size) - else: - self.repeat_ngram_blocker = None - - assert temperature > 0, "--temperature must be greater than 0" - - self.search = ( - search.BeamSearch(tgt_dict) if search_strategy is None else search_strategy - ) - # We only need to set src_lengths in LengthConstrainedBeamSearch. - # As a module attribute, setting it would break in multithread - # settings when the model is shared. - self.should_set_src_lengths = ( - hasattr(self.search, "needs_src_lengths") and self.search.needs_src_lengths - ) - - self.model.eval() - - self.lm_model = lm_model - self.lm_weight = lm_weight - if self.lm_model is not None: - self.lm_model.eval() - - def cuda(self): - self.model.cuda() - return self - - @torch.no_grad() - def forward( - self, - sample: Dict[str, Dict[str, Tensor]], - prefix_tokens: Optional[Tensor] = None, - bos_token: Optional[int] = None, - ): - """Generate a batch of translations. - - Args: - sample (dict): batch - prefix_tokens (torch.LongTensor, optional): force decoder to begin - with these tokens - bos_token (int, optional): beginning of sentence token - (default: self.eos) - """ - return self._generate(sample, prefix_tokens, bos_token=bos_token) - - # TODO(myleott): unused, deprecate after pytorch-translate migration - def generate_batched_itr(self, data_itr, beam_size=None, cuda=False, timer=None): - """Iterate over a batched dataset and yield individual translations. - Args: - cuda (bool, optional): use GPU for generation - timer (StopwatchMeter, optional): time generations - """ - for sample in data_itr: - s = utils.move_to_cuda(sample) if cuda else sample - if "net_input" not in s: - continue - input = s["net_input"] - # model.forward normally channels prev_output_tokens into the decoder - # separately, but SequenceGenerator directly calls model.encoder - encoder_input = { - k: v for k, v in input.items() if k != "prev_output_tokens" - } - if timer is not None: - timer.start() - with torch.no_grad(): - hypos = self.generate(encoder_input) - if timer is not None: - timer.stop(sum(len(h[0]["tokens"]) for h in hypos)) - for i, id in enumerate(s["id"].data): - # remove padding - src = utils.strip_pad(input["src_tokens"].data[i, :], self.pad) - ref = ( - utils.strip_pad(s["target"].data[i, :], self.pad) - if s["target"] is not None - else None - ) - yield id, src, ref, hypos[i] - - @torch.no_grad() - def generate(self, models, sample: Dict[str, Dict[str, Tensor]], **kwargs) -> List[List[Dict[str, Tensor]]]: - """Generate translations. Match the api of other fairseq generators. - - Args: - models (List[~fairseq.models.FairseqModel]): ensemble of models - sample (dict): batch - prefix_tokens (torch.LongTensor, optional): force decoder to begin - with these tokens - constraints (torch.LongTensor, optional): force decoder to include - the list of constraints - bos_token (int, optional): beginning of sentence token - (default: self.eos) - """ - return self._generate(sample, **kwargs) - - def _generate( - self, - sample: Dict[str, Dict[str, Tensor]], - prefix_tokens: Optional[Tensor] = None, - constraints: Optional[Tensor] = None, - bos_token: Optional[int] = None, - ): - incremental_states = torch.jit.annotate( - List[Dict[str, Dict[str, Optional[Tensor]]]], - [ - torch.jit.annotate(Dict[str, Dict[str, Optional[Tensor]]], {}) - for i in range(self.model.models_size) - ], - ) - net_input = sample["net_input"] - - if "src_tokens" in net_input: - src_tokens = net_input["src_tokens"] - # length of the source text being the character length except EndOfSentence and pad - src_lengths = ( - (src_tokens.ne(self.eos) & src_tokens.ne(self.pad)).long().sum(dim=1) - ) - elif "source" in net_input: - src_tokens = net_input["source"] - src_lengths = ( - net_input["padding_mask"].size(-1) - net_input["padding_mask"].sum(-1) - if net_input["padding_mask"] is not None - else torch.tensor(src_tokens.size(-1)).to(src_tokens) - ) - elif "features" in net_input: - src_tokens = net_input["features"] - src_lengths = ( - net_input["padding_mask"].size(-1) - net_input["padding_mask"].sum(-1) - if net_input["padding_mask"] is not None - else torch.tensor(src_tokens.size(-1)).to(src_tokens) - ) - else: - raise Exception("expected src_tokens or source in net input. input keys: " + str(net_input.keys())) - - # bsz: total number of sentences in beam - # Note that src_tokens may have more than 2 dimensions (i.e. audio features) - bsz, src_len = src_tokens.size()[:2] - beam_size = self.beam_size - - if constraints is not None and not self.search.supports_constraints: - raise NotImplementedError( - "Target-side constraints were provided, but search method doesn't support them" - ) - - # Initialize constraints, when active - self.search.init_constraints(constraints, beam_size) - - max_len: int = -1 - if self.match_source_len: - max_len = src_lengths.max().item() - else: - max_len = min( - int(self.max_len_a * src_len + self.max_len_b), - self.max_len - 1, - ) - assert ( - self.min_len <= max_len - ), "min_len cannot be larger than max_len, please adjust these!" - # compute the encoder output for each beam - with torch.autograd.profiler.record_function("EnsembleModel: forward_encoder"): - encoder_outs = self.model.forward_encoder(net_input) - - # placeholder of indices for bsz * beam_size to hold tokens and accumulative scores - new_order = torch.arange(bsz).view(-1, 1).repeat(1, beam_size).view(-1) - new_order = new_order.to(src_tokens.device).long() - encoder_outs = self.model.reorder_encoder_out(encoder_outs, new_order) - # ensure encoder_outs is a List. - assert encoder_outs is not None - - # initialize buffers - scores = ( - torch.zeros(bsz * beam_size, max_len + 1).to(src_tokens).float() - ) # +1 for eos; pad is never chosen for scoring - tokens = ( - torch.zeros(bsz * beam_size, max_len + 2) - .to(src_tokens) - .long() - .fill_(self.pad) - ) # +2 for eos and pad - tokens[:, 0] = self.eos if bos_token is None else bos_token - attn: Optional[Tensor] = None - - # A list that indicates candidates that should be ignored. - # For example, suppose we're sampling and have already finalized 2/5 - # samples. Then cands_to_ignore would mark 2 positions as being ignored, - # so that we only finalize the remaining 3 samples. - cands_to_ignore = ( - torch.zeros(bsz, beam_size).to(src_tokens).eq(-1) - ) # forward and backward-compatible False mask - - # list of completed sentences - finalized = torch.jit.annotate( - List[List[Dict[str, Tensor]]], - [torch.jit.annotate(List[Dict[str, Tensor]], []) for i in range(bsz)], - ) # contains lists of dictionaries of infomation about the hypothesis being finalized at each step - - # a boolean array indicating if the sentence at the index is finished or not - finished = [False for i in range(bsz)] - num_remaining_sent = bsz # number of sentences remaining - - # number of candidate hypos per step - cand_size = 2 * beam_size # 2 x beam size in case half are EOS - - # offset arrays for converting between different indexing schemes - bbsz_offsets = ( - (torch.arange(0, bsz) * beam_size) - .unsqueeze(1) - .type_as(tokens) - .to(src_tokens.device) - ) - cand_offsets = torch.arange(0, cand_size).type_as(tokens).to(src_tokens.device) - - reorder_state: Optional[Tensor] = None - batch_idxs: Optional[Tensor] = None - - original_batch_idxs: Optional[Tensor] = None - if "id" in sample and isinstance(sample["id"], Tensor): - original_batch_idxs = sample["id"] - else: - original_batch_idxs = torch.arange(0, bsz).type_as(tokens) - - for step in range(max_len + 1): # one extra step for EOS marker - # reorder decoder internal states based on the prev choice of beams - if reorder_state is not None: - if batch_idxs is not None: - # update beam indices to take into account removed sentences - corr = batch_idxs - torch.arange(batch_idxs.numel()).type_as( - batch_idxs - ) - reorder_state.view(-1, beam_size).add_( - corr.unsqueeze(-1) * beam_size - ) - original_batch_idxs = original_batch_idxs[batch_idxs] - self.model.reorder_incremental_state(incremental_states, reorder_state) - encoder_outs = self.model.reorder_encoder_out( - encoder_outs, reorder_state - ) - with torch.autograd.profiler.record_function("EnsembleModel: forward_decoder"): - lprobs, avg_attn_scores = self.model.forward_decoder( - tokens[:, : step + 1], - encoder_outs, - incremental_states, - self.temperature, - ) - - if self.lm_model is not None: - lm_out = self.lm_model(tokens[:, : step + 1]) - probs = self.lm_model.get_normalized_probs( - lm_out, log_probs=True, sample=None - ) - probs = probs[:, -1, :] * self.lm_weight - lprobs += probs - # handle prefix tokens (possibly with different lengths) - if ( - prefix_tokens is not None - and step < prefix_tokens.size(1) - and step < max_len - ): - lprobs, tokens, scores = self._prefix_tokens( - step, lprobs, scores, tokens, prefix_tokens, beam_size - ) - elif step < self.min_len: - # minimum length constraint (does not apply if using prefix_tokens) - lprobs[:, self.eos] = -math.inf - - lprobs[lprobs != lprobs] = torch.tensor(-math.inf).to(lprobs) - - lprobs[:, self.pad] = -math.inf # never select pad - lprobs[:, self.unk] -= self.unk_penalty # apply unk penalty - - # handle max length constraint - if step >= max_len: - lprobs[:, : self.eos] = -math.inf - lprobs[:, self.eos + 1 :] = -math.inf - - # Record attention scores, only support avg_attn_scores is a Tensor - if avg_attn_scores is not None: - if attn is None: - attn = torch.empty( - bsz * beam_size, avg_attn_scores.size(1), max_len + 2 - ).to(scores) - attn[:, :, step + 1].copy_(avg_attn_scores) - - scores = scores.type_as(lprobs) - eos_bbsz_idx = torch.empty(0).to( - tokens - ) # indices of hypothesis ending with eos (finished sentences) - eos_scores = torch.empty(0).to( - scores - ) # scores of hypothesis ending with eos (finished sentences) - - if self.should_set_src_lengths: - self.search.set_src_lengths(src_lengths) - - if self.repeat_ngram_blocker is not None: - lprobs = self.repeat_ngram_blocker(tokens, lprobs, bsz, beam_size, step) - - # Shape: (batch, cand_size) - cand_scores, cand_indices, cand_beams = self.search.step( - step, - lprobs.view(bsz, -1, self.vocab_size), - scores.view(bsz, beam_size, -1)[:, :, :step], - tokens[:, : step + 1], - original_batch_idxs, - ) - - # cand_bbsz_idx contains beam indices for the top candidate - # hypotheses, with a range of values: [0, bsz*beam_size), - # and dimensions: [bsz, cand_size] - cand_bbsz_idx = cand_beams.add(bbsz_offsets) - - # finalize hypotheses that end in eos - # Shape of eos_mask: (batch size, beam size) - eos_mask = cand_indices.eq(self.eos) & cand_scores.ne(-math.inf) - eos_mask[:, :beam_size][cands_to_ignore] = torch.tensor(0).to(eos_mask) - - # only consider eos when it's among the top beam_size indices - # Now we know what beam item(s) to finish - # Shape: 1d list of absolute-numbered - eos_bbsz_idx = torch.masked_select( - cand_bbsz_idx[:, :beam_size], mask=eos_mask[:, :beam_size] - ) - - finalized_sents: List[int] = [] - if eos_bbsz_idx.numel() > 0: - eos_scores = torch.masked_select( - cand_scores[:, :beam_size], mask=eos_mask[:, :beam_size] - ) - - finalized_sents = self.finalize_hypos( - step, - eos_bbsz_idx, - eos_scores, - tokens, - scores, - finalized, - finished, - beam_size, - attn, - src_lengths, - max_len, - ) - num_remaining_sent -= len(finalized_sents) - - assert num_remaining_sent >= 0 - if num_remaining_sent == 0: - break - if self.search.stop_on_max_len and step >= max_len: - break - assert step < max_len, f"{step} < {max_len}" - - # Remove finalized sentences (ones for which {beam_size} - # finished hypotheses have been generated) from the batch. - if len(finalized_sents) > 0: - new_bsz = bsz - len(finalized_sents) - - # construct batch_idxs which holds indices of batches to keep for the next pass - batch_mask = torch.ones( - bsz, dtype=torch.bool, device=cand_indices.device - ) - batch_mask[finalized_sents] = False - # TODO replace `nonzero(as_tuple=False)` after TorchScript supports it - batch_idxs = torch.arange( - bsz, device=cand_indices.device - ).masked_select(batch_mask) - - # Choose the subset of the hypothesized constraints that will continue - self.search.prune_sentences(batch_idxs) - - eos_mask = eos_mask[batch_idxs] - cand_beams = cand_beams[batch_idxs] - bbsz_offsets.resize_(new_bsz, 1) - cand_bbsz_idx = cand_beams.add(bbsz_offsets) - cand_scores = cand_scores[batch_idxs] - cand_indices = cand_indices[batch_idxs] - - if prefix_tokens is not None: - prefix_tokens = prefix_tokens[batch_idxs] - src_lengths = src_lengths[batch_idxs] - cands_to_ignore = cands_to_ignore[batch_idxs] - - scores = scores.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, -1) - tokens = tokens.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, -1) - if attn is not None: - attn = attn.view(bsz, -1)[batch_idxs].view( - new_bsz * beam_size, attn.size(1), -1 - ) - bsz = new_bsz - else: - batch_idxs = None - - # Set active_mask so that values > cand_size indicate eos hypos - # and values < cand_size indicate candidate active hypos. - # After, the min values per row are the top candidate active hypos - - # Rewrite the operator since the element wise or is not supported in torchscript. - - eos_mask[:, :beam_size] = ~((~cands_to_ignore) & (~eos_mask[:, :beam_size])) - active_mask = torch.add( - eos_mask.type_as(cand_offsets) * cand_size, - cand_offsets[: eos_mask.size(1)], - ) - - # get the top beam_size active hypotheses, which are just - # the hypos with the smallest values in active_mask. - # {active_hypos} indicates which {beam_size} hypotheses - # from the list of {2 * beam_size} candidates were - # selected. Shapes: (batch size, beam size) - new_cands_to_ignore, active_hypos = torch.topk( - active_mask, k=beam_size, dim=1, largest=False - ) - - # update cands_to_ignore to ignore any finalized hypos. - cands_to_ignore = new_cands_to_ignore.ge(cand_size)[:, :beam_size] - # Make sure there is at least one active item for each sentence in the batch. - assert (~cands_to_ignore).any(dim=1).all() - - # update cands_to_ignore to ignore any finalized hypos - - # {active_bbsz_idx} denotes which beam number is continued for each new hypothesis (a beam - # can be selected more than once). - active_bbsz_idx = torch.gather(cand_bbsz_idx, dim=1, index=active_hypos) - active_scores = torch.gather(cand_scores, dim=1, index=active_hypos) - - active_bbsz_idx = active_bbsz_idx.view(-1) - active_scores = active_scores.view(-1) - - # copy tokens and scores for active hypotheses - - # Set the tokens for each beam (can select the same row more than once) - tokens[:, : step + 1] = torch.index_select( - tokens[:, : step + 1], dim=0, index=active_bbsz_idx - ) - # Select the next token for each of them - tokens.view(bsz, beam_size, -1)[:, :, step + 1] = torch.gather( - cand_indices, dim=1, index=active_hypos - ) - if step > 0: - scores[:, :step] = torch.index_select( - scores[:, :step], dim=0, index=active_bbsz_idx - ) - scores.view(bsz, beam_size, -1)[:, :, step] = torch.gather( - cand_scores, dim=1, index=active_hypos - ) - - # Update constraints based on which candidates were selected for the next beam - self.search.update_constraints(active_hypos) - - # copy attention for active hypotheses - if attn is not None: - attn[:, :, : step + 2] = torch.index_select( - attn[:, :, : step + 2], dim=0, index=active_bbsz_idx - ) - - # reorder incremental state in decoder - reorder_state = active_bbsz_idx - - # sort by score descending - for sent in range(len(finalized)): - scores = torch.tensor( - [float(elem["score"].item()) for elem in finalized[sent]] - ) - _, sorted_scores_indices = torch.sort(scores, descending=True) - finalized[sent] = [finalized[sent][ssi] for ssi in sorted_scores_indices] - finalized[sent] = torch.jit.annotate( - List[Dict[str, Tensor]], finalized[sent] - ) - return finalized - - def _prefix_tokens( - self, step: int, lprobs, scores, tokens, prefix_tokens, beam_size: int - ): - """Handle prefix tokens""" - prefix_toks = prefix_tokens[:, step].unsqueeze(-1).repeat(1, beam_size).view(-1) - prefix_lprobs = lprobs.gather(-1, prefix_toks.unsqueeze(-1)) - prefix_mask = prefix_toks.ne(self.pad) - lprobs[prefix_mask] = torch.min(prefix_lprobs) - 1 - lprobs[prefix_mask] = lprobs[prefix_mask].scatter( - -1, prefix_toks[prefix_mask].unsqueeze(-1), prefix_lprobs[prefix_mask] - ) - # if prefix includes eos, then we should make sure tokens and - # scores are the same across all beams - eos_mask = prefix_toks.eq(self.eos) - if eos_mask.any(): - # validate that the first beam matches the prefix - first_beam = tokens[eos_mask].view(-1, beam_size, tokens.size(-1))[ - :, 0, 1 : step + 1 - ] - eos_mask_batch_dim = eos_mask.view(-1, beam_size)[:, 0] - target_prefix = prefix_tokens[eos_mask_batch_dim][:, :step] - assert (first_beam == target_prefix).all() - - # copy tokens, scores and lprobs from the first beam to all beams - tokens = self.replicate_first_beam(tokens, eos_mask_batch_dim, beam_size) - scores = self.replicate_first_beam(scores, eos_mask_batch_dim, beam_size) - lprobs = self.replicate_first_beam(lprobs, eos_mask_batch_dim, beam_size) - return lprobs, tokens, scores - - def replicate_first_beam(self, tensor, mask, beam_size: int): - tensor = tensor.view(-1, beam_size, tensor.size(-1)) - tensor[mask] = tensor[mask][:, :1, :] - return tensor.view(-1, tensor.size(-1)) - - def finalize_hypos( - self, - step: int, - bbsz_idx, - eos_scores, - tokens, - scores, - finalized: List[List[Dict[str, Tensor]]], - finished: List[bool], - beam_size: int, - attn: Optional[Tensor], - src_lengths, - max_len: int, - ): - """Finalize hypothesis, store finalized information in `finalized`, and change `finished` accordingly. - A sentence is finalized when {beam_size} finished items have been collected for it. - - Returns number of sentences (not beam items) being finalized. - These will be removed from the batch and not processed further. - Args: - bbsz_idx (Tensor): - """ - assert bbsz_idx.numel() == eos_scores.numel() - - # clone relevant token and attention tensors. - # tokens is (batch * beam, max_len). So the index_select - # gets the newly EOS rows, then selects cols 1..{step + 2} - tokens_clone = tokens.index_select(0, bbsz_idx)[ - :, 1 : step + 2 - ] # skip the first index, which is EOS - - tokens_clone[:, step] = self.eos - attn_clone = ( - attn.index_select(0, bbsz_idx)[:, :, 1 : step + 2] - if attn is not None - else None - ) - - # compute scores per token position - pos_scores = scores.index_select(0, bbsz_idx)[:, : step + 1] - pos_scores[:, step] = eos_scores - # convert from cumulative to per-position scores - pos_scores[:, 1:] = pos_scores[:, 1:] - pos_scores[:, :-1] - - # normalize sentence-level scores - if self.normalize_scores: - eos_scores /= (step + 1) ** self.len_penalty - - # cum_unfin records which sentences in the batch are finished. - # It helps match indexing between (a) the original sentences - # in the batch and (b) the current, possibly-reduced set of - # sentences. - cum_unfin: List[int] = [] - prev = 0 - for f in finished: - if f: - prev += 1 - else: - cum_unfin.append(prev) - cum_fin_tensor = torch.tensor(cum_unfin, dtype=torch.int).to(bbsz_idx) - - unfin_idx = bbsz_idx // beam_size - sent = unfin_idx + torch.index_select(cum_fin_tensor, 0, unfin_idx) - - # Create a set of "{sent}{unfin_idx}", where - # "unfin_idx" is the index in the current (possibly reduced) - # list of sentences, and "sent" is the index in the original, - # unreduced batch - # For every finished beam item - # sentence index in the current (possibly reduced) batch - seen = (sent << 32) + unfin_idx - unique_seen: List[int] = torch.unique(seen).tolist() - - if self.match_source_len: - condition = step > torch.index_select(src_lengths, 0, unfin_idx) - eos_scores = torch.where(condition, torch.tensor(-math.inf), eos_scores) - sent_list: List[int] = sent.tolist() - for i in range(bbsz_idx.size()[0]): - # An input sentence (among those in a batch) is finished when - # beam_size hypotheses have been collected for it - if len(finalized[sent_list[i]]) < beam_size: - if attn_clone is not None: - # remove padding tokens from attn scores - hypo_attn = attn_clone[i] - else: - hypo_attn = torch.empty(0) - - finalized[sent_list[i]].append( - { - "tokens": tokens_clone[i], - "score": eos_scores[i], - "attention": hypo_attn, # src_len x tgt_len - "alignment": torch.empty(0), - "positional_scores": pos_scores[i], - } - ) - - newly_finished: List[int] = [] - for unique_s in unique_seen: - # check termination conditions for this sentence - unique_sent: int = unique_s >> 32 - unique_unfin_idx: int = unique_s - (unique_sent << 32) - - if not finished[unique_sent] and self.is_finished( - step, unique_unfin_idx, max_len, len(finalized[unique_sent]), beam_size - ): - finished[unique_sent] = True - newly_finished.append(unique_unfin_idx) - - return newly_finished - - def is_finished( - self, - step: int, - unfin_idx: int, - max_len: int, - finalized_sent_len: int, - beam_size: int, - ): - """ - Check whether decoding for a sentence is finished, which - occurs when the list of finalized sentences has reached the - beam size, or when we reach the maximum length. - """ - assert finalized_sent_len <= beam_size - if finalized_sent_len == beam_size or step == max_len: - return True - return False - - -class EnsembleModel(nn.Module): - """A wrapper around an ensemble of models.""" - - def __init__(self, models): - super().__init__() - self.models_size = len(models) - # method '__len__' is not supported in ModuleList for torch script - self.single_model = models[0] - self.models = nn.ModuleList(models) - - self.has_incremental: bool = False - if all( - hasattr(m, "decoder") and isinstance(m.decoder, FairseqIncrementalDecoder) - for m in models - ): - self.has_incremental = True - - def forward(self): - pass - - def has_encoder(self): - return hasattr(self.single_model, "encoder") - - def has_incremental_states(self): - return self.has_incremental - - def max_decoder_positions(self): - return min([m.max_decoder_positions() for m in self.models if hasattr(m, "max_decoder_positions")] + [sys.maxsize]) - - @torch.jit.export - def forward_encoder(self, net_input: Dict[str, Tensor]): - if not self.has_encoder(): - return None - return [model.encoder.forward_torchscript(net_input) for model in self.models] - - @torch.jit.export - def forward_decoder( - self, - tokens, - encoder_outs: List[Dict[str, List[Tensor]]], - incremental_states: List[Dict[str, Dict[str, Optional[Tensor]]]], - temperature: float = 1.0, - ): - log_probs = [] - avg_attn: Optional[Tensor] = None - encoder_out: Optional[Dict[str, List[Tensor]]] = None - for i, model in enumerate(self.models): - if self.has_encoder(): - encoder_out = encoder_outs[i] - # decode each model - if self.has_incremental_states(): - decoder_out = model.decoder.forward( - tokens, - encoder_out=encoder_out, - incremental_state=incremental_states[i], - ) - else: - if hasattr(model, "decoder"): - decoder_out = model.decoder.forward(tokens, encoder_out=encoder_out) - else: - decoder_out = model.forward(tokens) - - attn: Optional[Tensor] = None - decoder_len = len(decoder_out) - if decoder_len > 1 and decoder_out[1] is not None: - if isinstance(decoder_out[1], Tensor): - attn = decoder_out[1] - else: - attn_holder = decoder_out[1]["attn"] - if isinstance(attn_holder, Tensor): - attn = attn_holder - elif attn_holder is not None: - attn = attn_holder[0] - if attn is not None: - attn = attn[:, -1, :] - - decoder_out_tuple = ( - decoder_out[0][:, -1:, :].div_(temperature), - None if decoder_len <= 1 else decoder_out[1], - ) - probs = model.get_normalized_probs( - decoder_out_tuple, log_probs=True, sample=None - ) - probs = probs[:, -1, :] - if self.models_size == 1: - return probs, attn - - log_probs.append(probs) - if attn is not None: - if avg_attn is None: - avg_attn = attn - else: - avg_attn.add_(attn) - - avg_probs = torch.logsumexp(torch.stack(log_probs, dim=0), dim=0) - math.log( - self.models_size - ) - - if avg_attn is not None: - avg_attn.div_(self.models_size) - return avg_probs, avg_attn - - @torch.jit.export - def reorder_encoder_out( - self, encoder_outs: Optional[List[Dict[str, List[Tensor]]]], new_order - ): - """ - Reorder encoder output according to *new_order*. - - Args: - encoder_out: output from the ``forward()`` method - new_order (LongTensor): desired order - - Returns: - *encoder_out* rearranged according to *new_order* - """ - new_outs: List[Dict[str, List[Tensor]]] = [] - if not self.has_encoder(): - return new_outs - for i, model in enumerate(self.models): - assert encoder_outs is not None - new_outs.append( - model.encoder.reorder_encoder_out(encoder_outs[i], new_order) - ) - return new_outs - - @torch.jit.export - def reorder_incremental_state( - self, - incremental_states: List[Dict[str, Dict[str, Optional[Tensor]]]], - new_order, - ): - if not self.has_incremental_states(): - return - for i, model in enumerate(self.models): - model.decoder.reorder_incremental_state_scripting( - incremental_states[i], new_order - ) - - -class SequenceGeneratorWithAlignment(SequenceGenerator): - def __init__( - self, models, tgt_dict, left_pad_target=False, print_alignment="hard", **kwargs - ): - """Generates translations of a given source sentence. - - Produces alignments following "Jointly Learning to Align and - Translate with Transformer Models" (Garg et al., EMNLP 2019). - - Args: - left_pad_target (bool, optional): Whether or not the - hypothesis should be left padded or not when they are - teacher forced for generating alignments. - """ - super().__init__(EnsembleModelWithAlignment(models), tgt_dict, **kwargs) - self.left_pad_target = left_pad_target - - if print_alignment == "hard": - self.extract_alignment = utils.extract_hard_alignment - elif print_alignment == "soft": - self.extract_alignment = utils.extract_soft_alignment - - @torch.no_grad() - def generate(self, models, sample, **kwargs): - finalized = super()._generate(sample, **kwargs) - - src_tokens = sample["net_input"]["src_tokens"] - bsz = src_tokens.shape[0] - beam_size = self.beam_size - ( - src_tokens, - src_lengths, - prev_output_tokens, - tgt_tokens, - ) = self._prepare_batch_for_alignment(sample, finalized) - if any(getattr(m, "full_context_alignment", False) for m in self.model.models): - attn = self.model.forward_align(src_tokens, src_lengths, prev_output_tokens) - else: - attn = [ - finalized[i // beam_size][i % beam_size]["attention"].transpose(1, 0) - for i in range(bsz * beam_size) - ] - - if src_tokens.device != "cpu": - src_tokens = src_tokens.to("cpu") - tgt_tokens = tgt_tokens.to("cpu") - attn = [i.to("cpu") for i in attn] - - # Process the attn matrix to extract hard alignments. - for i in range(bsz * beam_size): - alignment = self.extract_alignment( - attn[i], src_tokens[i], tgt_tokens[i], self.pad, self.eos - ) - finalized[i // beam_size][i % beam_size]["alignment"] = alignment - return finalized - - def _prepare_batch_for_alignment(self, sample, hypothesis): - src_tokens = sample["net_input"]["src_tokens"] - bsz = src_tokens.shape[0] - src_tokens = ( - src_tokens[:, None, :] - .expand(-1, self.beam_size, -1) - .contiguous() - .view(bsz * self.beam_size, -1) - ) - src_lengths = sample["net_input"]["src_lengths"] - src_lengths = ( - src_lengths[:, None] - .expand(-1, self.beam_size) - .contiguous() - .view(bsz * self.beam_size) - ) - prev_output_tokens = data_utils.collate_tokens( - [beam["tokens"] for example in hypothesis for beam in example], - self.pad, - self.eos, - self.left_pad_target, - move_eos_to_beginning=True, - ) - tgt_tokens = data_utils.collate_tokens( - [beam["tokens"] for example in hypothesis for beam in example], - self.pad, - self.eos, - self.left_pad_target, - move_eos_to_beginning=False, - ) - return src_tokens, src_lengths, prev_output_tokens, tgt_tokens - - -class EnsembleModelWithAlignment(EnsembleModel): - """A wrapper around an ensemble of models.""" - - def __init__(self, models): - super().__init__(models) - - def forward_align(self, src_tokens, src_lengths, prev_output_tokens): - avg_attn = None - for model in self.models: - decoder_out = model(src_tokens, src_lengths, prev_output_tokens) - attn = decoder_out[1]["attn"][0] - if avg_attn is None: - avg_attn = attn - else: - avg_attn.add_(attn) - if len(self.models) > 1: - avg_attn.div_(len(self.models)) - return avg_attn diff --git a/spaces/Illumotion/Koboldcpp/common/console.cpp b/spaces/Illumotion/Koboldcpp/common/console.cpp deleted file mode 100644 index f65cbc6eda0b1d1e4f45ab976fb8868be33b6c79..0000000000000000000000000000000000000000 --- a/spaces/Illumotion/Koboldcpp/common/console.cpp +++ /dev/null @@ -1,501 +0,0 @@ -#include "console.h" -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#include -#include -#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING -#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 -#endif -#else -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -#define ANSI_COLOR_RED "\x1b[31m" -#define ANSI_COLOR_GREEN "\x1b[32m" -#define ANSI_COLOR_YELLOW "\x1b[33m" -#define ANSI_COLOR_BLUE "\x1b[34m" -#define ANSI_COLOR_MAGENTA "\x1b[35m" -#define ANSI_COLOR_CYAN "\x1b[36m" -#define ANSI_COLOR_RESET "\x1b[0m" -#define ANSI_BOLD "\x1b[1m" - -namespace console { - - // - // Console state - // - - static bool advanced_display = false; - static bool simple_io = true; - static display_t current_display = reset; - - static FILE* out = stdout; - -#if defined (_WIN32) - static void* hConsole; -#else - static FILE* tty = nullptr; - static termios initial_state; -#endif - - // - // Init and cleanup - // - - void init(bool use_simple_io, bool use_advanced_display) { - advanced_display = use_advanced_display; - simple_io = use_simple_io; -#if defined(_WIN32) - // Windows-specific console initialization - DWORD dwMode = 0; - hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - if (hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(hConsole, &dwMode)) { - hConsole = GetStdHandle(STD_ERROR_HANDLE); - if (hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(hConsole, &dwMode))) { - hConsole = nullptr; - simple_io = true; - } - } - if (hConsole) { - // Check conditions combined to reduce nesting - if (advanced_display && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) && - !SetConsoleMode(hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) { - advanced_display = false; - } - // Set console output codepage to UTF8 - SetConsoleOutputCP(CP_UTF8); - } - HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE); - if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) { - // Set console input codepage to UTF16 - _setmode(_fileno(stdin), _O_WTEXT); - - // Set ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT) - if (simple_io) { - dwMode |= ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT; - } else { - dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT); - } - if (!SetConsoleMode(hConIn, dwMode)) { - simple_io = true; - } - } -#else - // POSIX-specific console initialization - if (!simple_io) { - struct termios new_termios; - tcgetattr(STDIN_FILENO, &initial_state); - new_termios = initial_state; - new_termios.c_lflag &= ~(ICANON | ECHO); - new_termios.c_cc[VMIN] = 1; - new_termios.c_cc[VTIME] = 0; - tcsetattr(STDIN_FILENO, TCSANOW, &new_termios); - - tty = fopen("/dev/tty", "w+"); - if (tty != nullptr) { - out = tty; - } - } - - setlocale(LC_ALL, ""); -#endif - } - - void cleanup() { - // Reset console display - set_display(reset); - -#if !defined(_WIN32) - // Restore settings on POSIX systems - if (!simple_io) { - if (tty != nullptr) { - out = stdout; - fclose(tty); - tty = nullptr; - } - tcsetattr(STDIN_FILENO, TCSANOW, &initial_state); - } -#endif - } - - // - // Display and IO - // - - // Keep track of current display and only emit ANSI code if it changes - void set_display(display_t display) { - if (advanced_display && current_display != display) { - fflush(stdout); - switch(display) { - case reset: - fprintf(out, ANSI_COLOR_RESET); - break; - case prompt: - fprintf(out, ANSI_COLOR_YELLOW); - break; - case user_input: - fprintf(out, ANSI_BOLD ANSI_COLOR_GREEN); - break; - case error: - fprintf(out, ANSI_BOLD ANSI_COLOR_RED); - } - current_display = display; - fflush(out); - } - } - - static char32_t getchar32() { -#if defined(_WIN32) - HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE); - wchar_t high_surrogate = 0; - - while (true) { - INPUT_RECORD record; - DWORD count; - if (!ReadConsoleInputW(hConsole, &record, 1, &count) || count == 0) { - return WEOF; - } - - if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { - wchar_t wc = record.Event.KeyEvent.uChar.UnicodeChar; - if (wc == 0) { - continue; - } - - if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate - high_surrogate = wc; - continue; - } - if ((wc >= 0xDC00) && (wc <= 0xDFFF)) { // Check if wc is a low surrogate - if (high_surrogate != 0) { // Check if we have a high surrogate - return ((high_surrogate - 0xD800) << 10) + (wc - 0xDC00) + 0x10000; - } - } - - high_surrogate = 0; // Reset the high surrogate - return static_cast(wc); - } - } -#else - wchar_t wc = getwchar(); - if (static_cast(wc) == WEOF) { - return WEOF; - } - -#if WCHAR_MAX == 0xFFFF - if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate - wchar_t low_surrogate = getwchar(); - if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate - return (static_cast(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000; - } - } - if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair - return 0xFFFD; // Return the replacement character U+FFFD - } -#endif - - return static_cast(wc); -#endif - } - - static void pop_cursor() { -#if defined(_WIN32) - if (hConsole != NULL) { - CONSOLE_SCREEN_BUFFER_INFO bufferInfo; - GetConsoleScreenBufferInfo(hConsole, &bufferInfo); - - COORD newCursorPosition = bufferInfo.dwCursorPosition; - if (newCursorPosition.X == 0) { - newCursorPosition.X = bufferInfo.dwSize.X - 1; - newCursorPosition.Y -= 1; - } else { - newCursorPosition.X -= 1; - } - - SetConsoleCursorPosition(hConsole, newCursorPosition); - return; - } -#endif - putc('\b', out); - } - - static int estimateWidth(char32_t codepoint) { -#if defined(_WIN32) - (void)codepoint; - return 1; -#else - return wcwidth(codepoint); -#endif - } - - static int put_codepoint(const char* utf8_codepoint, size_t length, int expectedWidth) { -#if defined(_WIN32) - CONSOLE_SCREEN_BUFFER_INFO bufferInfo; - if (!GetConsoleScreenBufferInfo(hConsole, &bufferInfo)) { - // go with the default - return expectedWidth; - } - COORD initialPosition = bufferInfo.dwCursorPosition; - DWORD nNumberOfChars = length; - WriteConsole(hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL); - - CONSOLE_SCREEN_BUFFER_INFO newBufferInfo; - GetConsoleScreenBufferInfo(hConsole, &newBufferInfo); - - // Figure out our real position if we're in the last column - if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) { - DWORD nNumberOfChars; - WriteConsole(hConsole, &" \b", 2, &nNumberOfChars, NULL); - GetConsoleScreenBufferInfo(hConsole, &newBufferInfo); - } - - int width = newBufferInfo.dwCursorPosition.X - initialPosition.X; - if (width < 0) { - width += newBufferInfo.dwSize.X; - } - return width; -#else - // We can trust expectedWidth if we've got one - if (expectedWidth >= 0 || tty == nullptr) { - fwrite(utf8_codepoint, length, 1, out); - return expectedWidth; - } - - fputs("\033[6n", tty); // Query cursor position - int x1; - int y1; - int x2; - int y2; - int results = 0; - results = fscanf(tty, "\033[%d;%dR", &y1, &x1); - - fwrite(utf8_codepoint, length, 1, tty); - - fputs("\033[6n", tty); // Query cursor position - results += fscanf(tty, "\033[%d;%dR", &y2, &x2); - - if (results != 4) { - return expectedWidth; - } - - int width = x2 - x1; - if (width < 0) { - // Calculate the width considering text wrapping - struct winsize w; - ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); - width += w.ws_col; - } - return width; -#endif - } - - static void replace_last(char ch) { -#if defined(_WIN32) - pop_cursor(); - put_codepoint(&ch, 1, 1); -#else - fprintf(out, "\b%c", ch); -#endif - } - - static void append_utf8(char32_t ch, std::string & out) { - if (ch <= 0x7F) { - out.push_back(static_cast(ch)); - } else if (ch <= 0x7FF) { - out.push_back(static_cast(0xC0 | ((ch >> 6) & 0x1F))); - out.push_back(static_cast(0x80 | (ch & 0x3F))); - } else if (ch <= 0xFFFF) { - out.push_back(static_cast(0xE0 | ((ch >> 12) & 0x0F))); - out.push_back(static_cast(0x80 | ((ch >> 6) & 0x3F))); - out.push_back(static_cast(0x80 | (ch & 0x3F))); - } else if (ch <= 0x10FFFF) { - out.push_back(static_cast(0xF0 | ((ch >> 18) & 0x07))); - out.push_back(static_cast(0x80 | ((ch >> 12) & 0x3F))); - out.push_back(static_cast(0x80 | ((ch >> 6) & 0x3F))); - out.push_back(static_cast(0x80 | (ch & 0x3F))); - } else { - // Invalid Unicode code point - } - } - - // Helper function to remove the last UTF-8 character from a string - static void pop_back_utf8_char(std::string & line) { - if (line.empty()) { - return; - } - - size_t pos = line.length() - 1; - - // Find the start of the last UTF-8 character (checking up to 4 bytes back) - for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) { - if ((line[pos] & 0xC0) != 0x80) { - break; // Found the start of the character - } - } - line.erase(pos); - } - - static bool readline_advanced(std::string & line, bool multiline_input) { - if (out != stdout) { - fflush(stdout); - } - - line.clear(); - std::vector widths; - bool is_special_char = false; - bool end_of_stream = false; - - char32_t input_char; - while (true) { - fflush(out); // Ensure all output is displayed before waiting for input - input_char = getchar32(); - - if (input_char == '\r' || input_char == '\n') { - break; - } - - if (input_char == (char32_t) WEOF || input_char == 0x04 /* Ctrl+D*/) { - end_of_stream = true; - break; - } - - if (is_special_char) { - set_display(user_input); - replace_last(line.back()); - is_special_char = false; - } - - if (input_char == '\033') { // Escape sequence - char32_t code = getchar32(); - if (code == '[' || code == 0x1B) { - // Discard the rest of the escape sequence - while ((code = getchar32()) != (char32_t) WEOF) { - if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') { - break; - } - } - } - } else if (input_char == 0x08 || input_char == 0x7F) { // Backspace - if (!widths.empty()) { - int count; - do { - count = widths.back(); - widths.pop_back(); - // Move cursor back, print space, and move cursor back again - for (int i = 0; i < count; i++) { - replace_last(' '); - pop_cursor(); - } - pop_back_utf8_char(line); - } while (count == 0 && !widths.empty()); - } - } else { - int offset = line.length(); - append_utf8(input_char, line); - int width = put_codepoint(line.c_str() + offset, line.length() - offset, estimateWidth(input_char)); - if (width < 0) { - width = 0; - } - widths.push_back(width); - } - - if (!line.empty() && (line.back() == '\\' || line.back() == '/')) { - set_display(prompt); - replace_last(line.back()); - is_special_char = true; - } - } - - bool has_more = multiline_input; - if (is_special_char) { - replace_last(' '); - pop_cursor(); - - char last = line.back(); - line.pop_back(); - if (last == '\\') { - line += '\n'; - fputc('\n', out); - has_more = !has_more; - } else { - // llama will just eat the single space, it won't act as a space - if (line.length() == 1 && line.back() == ' ') { - line.clear(); - pop_cursor(); - } - has_more = false; - } - } else { - if (end_of_stream) { - has_more = false; - } else { - line += '\n'; - fputc('\n', out); - } - } - - fflush(out); - return has_more; - } - - static bool readline_simple(std::string & line, bool multiline_input) { -#if defined(_WIN32) - std::wstring wline; - if (!std::getline(std::wcin, wline)) { - // Input stream is bad or EOF received - line.clear(); - GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); - return false; - } - - int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wline[0], (int)wline.size(), NULL, 0, NULL, NULL); - line.resize(size_needed); - WideCharToMultiByte(CP_UTF8, 0, &wline[0], (int)wline.size(), &line[0], size_needed, NULL, NULL); -#else - if (!std::getline(std::cin, line)) { - // Input stream is bad or EOF received - line.clear(); - return false; - } -#endif - if (!line.empty()) { - char last = line.back(); - if (last == '/') { // Always return control on '/' symbol - line.pop_back(); - return false; - } - if (last == '\\') { // '\\' changes the default action - line.pop_back(); - multiline_input = !multiline_input; - } - } - line += '\n'; - - // By default, continue input if multiline_input is set - return multiline_input; - } - - bool readline(std::string & line, bool multiline_input) { - set_display(user_input); - - if (simple_io) { - return readline_simple(line, multiline_input); - } - return readline_advanced(line, multiline_input); - } - -} diff --git a/spaces/Illumotion/Koboldcpp/tests/test-tokenizer-0-falcon.cpp b/spaces/Illumotion/Koboldcpp/tests/test-tokenizer-0-falcon.cpp deleted file mode 100644 index 0f3c50bce8ae9d82259a7f421a5364c59ec70655..0000000000000000000000000000000000000000 --- a/spaces/Illumotion/Koboldcpp/tests/test-tokenizer-0-falcon.cpp +++ /dev/null @@ -1,187 +0,0 @@ -#include "llama.h" -#include "common.h" -#include "console.h" - -#include -#include -#include -#include -#include - -// generate using test-tokenizer-0-falcon.py -static const std::map> & k_tests() { - static std::map> _k_tests = { - { "" , { }, }, - { " " , { 204, }, }, - { " " , { 258, }, }, - { " " , { 466, }, }, - { "\t" , { 192, }, }, - { "\n" , { 193, }, }, - { "\t\n" , { 19125, }, }, - { "Hello world" , { 9856, 1079, }, }, - { " Hello world" , { 23090, 1079, }, }, - { "Hello World" , { 9856, 2889, }, }, - { " Hello World" , { 23090, 2889, }, }, - { " Hello World!" , { 23090, 2889, 12, }, }, - { "Hello, world!" , { 9856, 23, 1079, 12, }, }, - { " Hello, world!" , { 23090, 23, 1079, 12, }, }, - { " this is 🦙.cpp" , { 414, 304, 3346, 111, 231, 25, 29247, }, }, - { "w048 7tuijk dsdfhu" , { 98, 55866, 204, 34, 16682, 7149, 36190, 6869, 11481, }, }, - { "нещо на Български" , { 150, 133, 6207, 151, 215, 150, 134, 5052, 133, 6279, 5052, 223, 151, 216, 49679, 123, 53110, 47043, 7795, }, }, - { "កាន់តែពិសេសអាចខលចេញ" , { 38154, 206, 38154, 126, 38154, 225, 167, 237, 217, 38154, 221, 167, 237, 208, 38154, 228, 38154, 127, 38154, 237, 167, 237, 207, 38154, 237, 38154, 107, 38154, 126, 38154, 211, 38154, 207, 38154, 233, 38154, 211, 167, 237, 207, 38154, 215, }, }, - { "🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ (only emoji that has its own token)", { 2571, 232, 206, 204, 19, 11003, 20, 8196, 126, 283, 219, 48778, 116, 13392, 204, 19, 51831, 732, 63209, 1741, 7955, 522, 20, 22438, 211, 204, 19, 7927, 53360, 325, 504, 701, 946, 10930, 20, }, }, - { "Hello" , { 9856, }, }, - { " Hello" , { 23090, }, }, - { " Hello" , { 204, 23090, }, }, - { " Hello" , { 258, 23090, }, }, - { " Hello" , { 466, 23090, }, }, - { " Hello\n Hello" , { 466, 23090, 742, 23090, }, }, - }; - - return _k_tests; -} - -int main(int argc, char **argv) { - if (argc < 2) { - fprintf(stderr, "Usage: %s vocab-file [text-file]\n", argv[0]); - return 1; - } - - const std::string fname = argv[1]; - - std::string fname_text; - if (argc > 2) { - fname_text = argv[2]; - } - - fprintf(stderr, "%s : reading vocab from: '%s'\n", __func__, fname.c_str()); - - llama_model * model; - llama_context * ctx; - - llama_backend_init(false); - - // load the vocab - { - auto mparams = llama_model_default_params(); - - mparams.vocab_only = true; - - model = llama_load_model_from_file(fname.c_str(), mparams); - - if (model == NULL) { - fprintf(stderr, "%s: error: failed to load vocab '%s'\n", __func__, fname.c_str()); - return 1; - } - - auto cparams = llama_context_default_params(); - - ctx = llama_new_context_with_model(model, cparams); - - if (ctx == NULL) { - fprintf(stderr, "%s: error: failed to load vocab '%s'\n", __func__, fname.c_str()); - llama_free_model(model); - return 1; - } - } - - if (llama_vocab_type(model) != LLAMA_VOCAB_TYPE_BPE) { - fprintf(stderr, "%s : error: vocab type is not BPE\n", __func__); - llama_free_model(model); - llama_free(ctx); - return 2; - } - -#ifdef _WIN32 - // We need this for unicode console support - console::init(false, false); - atexit([]() { console::cleanup(); }); -#endif - - bool success = true; - - for (const auto & test_kv : k_tests()) { - const std::vector res = llama_tokenize(ctx, test_kv.first, false); - - printf("\n"); - printf("src: '%s'\n", test_kv.first.c_str()); - printf("res: '%s'\n", llama_detokenize_bpe(ctx, res).c_str()); - printf("tok: "); - for (const auto & tok : res) { - printf("%d ", tok); - } - printf("\n"); - - bool correct = res.size() == test_kv.second.size(); - - for (int i = 0; i < (int) res.size() && correct; ++i) { - if (test_kv.second[i] != res[i]) { - correct = false; - } - } - - if (!correct) { - fprintf(stderr, "%s : failed test: '%s'\n", __func__, test_kv.first.c_str()); - fprintf(stderr, "%s : detokenized to: '%s' instead of '%s'\n", __func__, - llama_detokenize_bpe(ctx, res).c_str(), - llama_detokenize_bpe(ctx, test_kv.second).c_str()); - fprintf(stderr, "%s : expected tokens: ", __func__); - for (const auto & t : test_kv.second) { - fprintf(stderr, "%6d, ", t); - } - fprintf(stderr, "\n"); - fprintf(stderr, "%s : got tokens: ", __func__); - for (const auto & t : res) { - fprintf(stderr, "%6d, ", t); - } - fprintf(stderr, "\n"); - - success = false; - } - } - - if (!fname_text.empty()) { - fprintf(stderr, "%s : tokenizing: '%s'\n", __func__, fname_text.c_str()); - - std::string text; - { - std::ifstream ifs(fname_text); - if (!ifs) { - fprintf(stderr, "%s : error: could not open file '%s'\n", __func__, fname_text.c_str()); - return 1; - } - text = std::string(std::istreambuf_iterator(ifs), std::istreambuf_iterator()); - } - - fprintf(stderr, "%s : text size: %zu\n", __func__, text.size()); - - const std::vector res = llama_tokenize(ctx, text, true); - - fprintf(stderr, "%s : tokens: %zu\n", __func__, res.size()); - - { - const std::string fname_out = fname_text + ".tokcpp"; - - std::ofstream ofs(fname_out); - if (!ofs) { - fprintf(stderr, "%s : error: could not open file '%s'\n", __func__, fname_out.c_str()); - return 1; - } - - for (const auto & tok : res) { - ofs << tok << " "; - } - - ofs << "\n"; - } - - fprintf(stderr, "%s : tokens written to '%s'\n", __func__, (fname_text + ".tokcpp").c_str()); - } - - llama_free_model(model); - llama_free(ctx); - - llama_backend_free(); - - return success ? 0 : 3; -} diff --git a/spaces/InvisableClearCoat101/mistralai-Mistral-7B-v0.1/app.py b/spaces/InvisableClearCoat101/mistralai-Mistral-7B-v0.1/app.py deleted file mode 100644 index 22ea81a78d380cdb481188f32c93b9ad214b85f2..0000000000000000000000000000000000000000 --- a/spaces/InvisableClearCoat101/mistralai-Mistral-7B-v0.1/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/mistralai/Mistral-7B-v0.1").launch() \ No newline at end of file diff --git a/spaces/JohnnyPittt/audio-styling/deepafx_st/processors/autodiff/channel.py b/spaces/JohnnyPittt/audio-styling/deepafx_st/processors/autodiff/channel.py deleted file mode 100644 index e48a3cc358f7d4ec668ba76cc86e9bf1f7f76b55..0000000000000000000000000000000000000000 --- a/spaces/JohnnyPittt/audio-styling/deepafx_st/processors/autodiff/channel.py +++ /dev/null @@ -1,28 +0,0 @@ -import torch - -from deepafx_st.processors.autodiff.compressor import Compressor -from deepafx_st.processors.autodiff.peq import ParametricEQ -from deepafx_st.processors.autodiff.fir import FIRFilter - - -class AutodiffChannel(torch.nn.Module): - def __init__(self, sample_rate): - super().__init__() - - self.peq = ParametricEQ(sample_rate) - self.comp = Compressor(sample_rate) - self.ports = [self.peq.ports, self.comp.ports] - self.num_control_params = ( - self.peq.num_control_params + self.comp.num_control_params - ) - - def forward(self, x, p, sample_rate=24000, **kwargs): - - # split params between EQ and Comp. - p_peq = p[:, : self.peq.num_control_params] - p_comp = p[:, self.peq.num_control_params :] - - y = self.peq(x, p_peq, sample_rate) - y = self.comp(y, p_comp, sample_rate) - - return y diff --git a/spaces/Jojohickman21/IvyLeague_Logo_Classifier/app.py b/spaces/Jojohickman21/IvyLeague_Logo_Classifier/app.py deleted file mode 100644 index c5a2467b149e2e96a213b0bebb3230a08039c430..0000000000000000000000000000000000000000 --- a/spaces/Jojohickman21/IvyLeague_Logo_Classifier/app.py +++ /dev/null @@ -1,14 +0,0 @@ -import gradio as gr -from fastai.vision.all import * -import skimage - -learner = load_learner('export.pkl') - -labels = learner.dls.vocab -def predict(img): - img = PILImage.create(img) - pred,pred_idx,probs = learner.predict(img) - return {labels[i]: float(probs[i]) for i in range(len(labels))} - - -gr.Interface(enable_queue= true,title= "Ivy League Logo/Emblem Classifier",fn=predict, inputs=gr.inputs.Image(shape=(256,256)), outputs=gr.outputs.Label(num_top_classes=3),examples=['img1.jpg','img2.jpg','img3.jpg']).launch() \ No newline at end of file diff --git a/spaces/KAIST-Geometric-AI-Lab/salad-demo/salad/models/phase2.py b/spaces/KAIST-Geometric-AI-Lab/salad-demo/salad/models/phase2.py deleted file mode 100644 index 5bfc59c6502a1d2b02f088045f41c2baf979701e..0000000000000000000000000000000000000000 --- a/spaces/KAIST-Geometric-AI-Lab/salad-demo/salad/models/phase2.py +++ /dev/null @@ -1,183 +0,0 @@ -from typing import Union - -import numpy as np -import torch -import torch.nn.functional as F - -from salad.models.base_model import BaseModel -from salad.utils import imageutil, nputil, sysutil, thutil, visutil -from salad.utils.spaghetti_util import (clip_eigenvalues, - generate_zc_from_sj_gaus, - get_mesh_from_spaghetti, load_mesher, - load_spaghetti, project_eigenvectors) - - -class Phase2Model(BaseModel): - def __init__(self, network, variance_schedule, **kwargs): - super().__init__(network, variance_schedule, **kwargs) - - def forward(self, x, cond): - return self.get_loss(x, cond) - - def step(self, batch, stage: str): - x, cond = batch - loss = self(x, cond) - self.log(f"{stage}/loss", loss, on_step=stage == "train", prog_bar=True) - return loss - - def get_loss(self, x0, cond, t=None, noisy_in=False, beta_in=None, e_rand_in=None): - B, G, D = x0.shape - - if not noisy_in: - if t is None: - t = self.var_sched.uniform_sample_t(B) - x_noisy, beta, e_rand = self.add_noise(x0, t) - else: - x_noisy = x0 - beta = beta_in - e_rand = e_rand_in - - e_theta = self.net(x_noisy, beta, cond) - loss = F.mse_loss(e_theta.flatten(), e_rand.flatten(), reduction="mean") - return loss - - @torch.no_grad() - def sample( - self, - num_samples_or_gaus: Union[torch.Tensor, np.ndarray, int], - return_traj=False, - classifier_free_guidance=None, - free_guidance_weight=-0.7, - augment_condition_in_test=False, - return_cond=False, - ): - if isinstance(num_samples_or_gaus, int): - batch_size = num_samples_or_gaus - ds = self._build_dataset("val") - cond = torch.stack([ds[i][1] for i in range(batch_size)], 0) - - elif isinstance(num_samples_or_gaus, np.ndarray) or isinstance( - num_samples_or_gaus, torch.Tensor - ): - cond = nputil.np2th(num_samples_or_gaus) - if cond.dim() == 2: - cond = cond[None] - batch_size = len(cond) - else: - raise ValueError( - "'num_samples_or_gaus' should be int, torch.Tensor or np.ndarray." - ) - - x_T = torch.randn([batch_size, 16, 512]).to(self.device) - cond = cond.to(self.device) - - traj = {self.var_sched.num_steps: x_T} - for t in range(self.var_sched.num_steps, 0, -1): - z = torch.randn_like(x_T) if t > 1 else torch.zeros_like(x_T) - alpha = self.var_sched.alphas[t] - alpha_bar = self.var_sched.alpha_bars[t] - sigma = self.var_sched.get_sigmas(t, flexibility=0) - - c0 = 1.0 / torch.sqrt(alpha) - c1 = (1 - alpha) / torch.sqrt(1 - alpha_bar) - - x_t = traj[t] - - beta = self.var_sched.betas[[t] * batch_size] - e_theta = self.net(x_t, beta=beta, context=cond) - - x_next = c0 * (x_t - c1 * e_theta) + sigma * z - traj[t - 1] = x_next.detach() - - traj[t] = traj[t].cpu() - - if not return_traj: - del traj[t] - - if return_traj: - if return_cond: - return traj, cond - return traj - else: - if return_cond: - return traj[0], cond - return traj[0] - - def validation(self): - latent_ds = self._build_dataset("val") - vis_num_shapes = 3 - num_variations = 3 - sysutil.clean_gpu() - - if not hasattr(self, "spaghetti"): - spaghetti = load_spaghetti( - self.device, - self.hparams.spaghetti_tag - if self.hparams.get("spaghetti_tag") - else "chairs_large", - ) - self.spaghetti = spaghetti - else: - spaghetti = self.spaghetti - - if not hasattr(self, "mesher"): - mesher = load_mesher(self.device) - self.mesher = mesher - else: - mesher = self.mesher - - """======== Sampling ========""" - gt_zs = [] - gt_gaus = [] - - gt_zs, gt_gaus = zip(*[latent_ds[i + 3] for i in range(vis_num_shapes)]) - gt_zs, gt_gaus = list(map(lambda x: torch.stack(x), [gt_zs, gt_gaus])) - if self.hparams.get("sj_global_normalization"): - gt_zs = thutil.th2np(gt_zs) - gt_zs = latent_ds.unnormalize_sj_global_static(gt_zs) - gt_zs = nputil.np2th(gt_zs).to(self.device) - - gt_gaus_repeated = gt_gaus.repeat_interleave(num_variations, 0) - clean_ldm_zs, clean_gaus = self.sample(gt_gaus_repeated, return_cond=True) - clean_gaus = project_eigenvectors(clip_eigenvalues(clean_gaus)) - clean_zcs = generate_zc_from_sj_gaus(spaghetti, clean_ldm_zs, clean_gaus) - gt_zcs = generate_zc_from_sj_gaus(spaghetti, gt_zs, gt_gaus) - sysutil.clean_gpu() - - """==========================""" - - """ Spaghetti Decoding """ - wandb_logger = self.get_wandb_logger() - resolution = (256, 256) - for i in range(vis_num_shapes): - img_per_shape = [] - gaus_img = visutil.render_gaussians(gt_gaus[i], resolution=resolution) - vert, face = get_mesh_from_spaghetti(spaghetti, mesher, gt_zcs[i], res=128) - gt_mesh_img = visutil.render_mesh(vert, face, resolution=resolution) - gt_img = imageutil.merge_images([gaus_img, gt_mesh_img]) - gt_img = imageutil.draw_text(gt_img, "GT", font_size=24) - img_per_shape.append(gt_img) - for j in range(num_variations): - try: - gaus_img = visutil.render_gaussians( - clean_gaus[i * num_variations + j], resolution=resolution - ) - vert, face = get_mesh_from_spaghetti( - spaghetti, mesher, clean_zcs[i * num_variations + j], res=128 - ) - mesh_img = visutil.render_mesh(vert, face, resolution=resolution) - pred_img = imageutil.merge_images([gaus_img, mesh_img]) - pred_img = imageutil.draw_text( - pred_img, f"{j}-th clean gaus", font_size=24 - ) - img_per_shape.append(pred_img) - except Exception as e: - print(e) - - try: - image = imageutil.merge_images(img_per_shape) - wandb_logger.log_image("visualization", [image]) - except Exception as e: - print(e) - - """ ================== """ diff --git a/spaces/Kangarroar/ApplioRVC-Inference/demucs/model.py b/spaces/Kangarroar/ApplioRVC-Inference/demucs/model.py deleted file mode 100644 index e9d932f4d014f7b95b394d2e24ed5edc379ded8d..0000000000000000000000000000000000000000 --- a/spaces/Kangarroar/ApplioRVC-Inference/demucs/model.py +++ /dev/null @@ -1,202 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import math - -import julius -from torch import nn - -from .utils import capture_init, center_trim - - -class BLSTM(nn.Module): - def __init__(self, dim, layers=1): - super().__init__() - self.lstm = nn.LSTM(bidirectional=True, num_layers=layers, hidden_size=dim, input_size=dim) - self.linear = nn.Linear(2 * dim, dim) - - def forward(self, x): - x = x.permute(2, 0, 1) - x = self.lstm(x)[0] - x = self.linear(x) - x = x.permute(1, 2, 0) - return x - - -def rescale_conv(conv, reference): - std = conv.weight.std().detach() - scale = (std / reference)**0.5 - conv.weight.data /= scale - if conv.bias is not None: - conv.bias.data /= scale - - -def rescale_module(module, reference): - for sub in module.modules(): - if isinstance(sub, (nn.Conv1d, nn.ConvTranspose1d)): - rescale_conv(sub, reference) - - -class Demucs(nn.Module): - @capture_init - def __init__(self, - sources, - audio_channels=2, - channels=64, - depth=6, - rewrite=True, - glu=True, - rescale=0.1, - resample=True, - kernel_size=8, - stride=4, - growth=2., - lstm_layers=2, - context=3, - normalize=False, - samplerate=44100, - segment_length=4 * 10 * 44100): - """ - Args: - sources (list[str]): list of source names - audio_channels (int): stereo or mono - channels (int): first convolution channels - depth (int): number of encoder/decoder layers - rewrite (bool): add 1x1 convolution to each encoder layer - and a convolution to each decoder layer. - For the decoder layer, `context` gives the kernel size. - glu (bool): use glu instead of ReLU - resample_input (bool): upsample x2 the input and downsample /2 the output. - rescale (int): rescale initial weights of convolutions - to get their standard deviation closer to `rescale` - kernel_size (int): kernel size for convolutions - stride (int): stride for convolutions - growth (float): multiply (resp divide) number of channels by that - for each layer of the encoder (resp decoder) - lstm_layers (int): number of lstm layers, 0 = no lstm - context (int): kernel size of the convolution in the - decoder before the transposed convolution. If > 1, - will provide some context from neighboring time - steps. - samplerate (int): stored as meta information for easing - future evaluations of the model. - segment_length (int): stored as meta information for easing - future evaluations of the model. Length of the segments on which - the model was trained. - """ - - super().__init__() - self.audio_channels = audio_channels - self.sources = sources - self.kernel_size = kernel_size - self.context = context - self.stride = stride - self.depth = depth - self.resample = resample - self.channels = channels - self.normalize = normalize - self.samplerate = samplerate - self.segment_length = segment_length - - self.encoder = nn.ModuleList() - self.decoder = nn.ModuleList() - - if glu: - activation = nn.GLU(dim=1) - ch_scale = 2 - else: - activation = nn.ReLU() - ch_scale = 1 - in_channels = audio_channels - for index in range(depth): - encode = [] - encode += [nn.Conv1d(in_channels, channels, kernel_size, stride), nn.ReLU()] - if rewrite: - encode += [nn.Conv1d(channels, ch_scale * channels, 1), activation] - self.encoder.append(nn.Sequential(*encode)) - - decode = [] - if index > 0: - out_channels = in_channels - else: - out_channels = len(self.sources) * audio_channels - if rewrite: - decode += [nn.Conv1d(channels, ch_scale * channels, context), activation] - decode += [nn.ConvTranspose1d(channels, out_channels, kernel_size, stride)] - if index > 0: - decode.append(nn.ReLU()) - self.decoder.insert(0, nn.Sequential(*decode)) - in_channels = channels - channels = int(growth * channels) - - channels = in_channels - - if lstm_layers: - self.lstm = BLSTM(channels, lstm_layers) - else: - self.lstm = None - - if rescale: - rescale_module(self, reference=rescale) - - def valid_length(self, length): - """ - Return the nearest valid length to use with the model so that - there is no time steps left over in a convolutions, e.g. for all - layers, size of the input - kernel_size % stride = 0. - - If the mixture has a valid length, the estimated sources - will have exactly the same length when context = 1. If context > 1, - the two signals can be center trimmed to match. - - For training, extracts should have a valid length.For evaluation - on full tracks we recommend passing `pad = True` to :method:`forward`. - """ - if self.resample: - length *= 2 - for _ in range(self.depth): - length = math.ceil((length - self.kernel_size) / self.stride) + 1 - length = max(1, length) - length += self.context - 1 - for _ in range(self.depth): - length = (length - 1) * self.stride + self.kernel_size - - if self.resample: - length = math.ceil(length / 2) - return int(length) - - def forward(self, mix): - x = mix - - if self.normalize: - mono = mix.mean(dim=1, keepdim=True) - mean = mono.mean(dim=-1, keepdim=True) - std = mono.std(dim=-1, keepdim=True) - else: - mean = 0 - std = 1 - - x = (x - mean) / (1e-5 + std) - - if self.resample: - x = julius.resample_frac(x, 1, 2) - - saved = [] - for encode in self.encoder: - x = encode(x) - saved.append(x) - if self.lstm: - x = self.lstm(x) - for decode in self.decoder: - skip = center_trim(saved.pop(-1), x) - x = x + skip - x = decode(x) - - if self.resample: - x = julius.resample_frac(x, 2, 1) - x = x * std + mean - x = x.view(x.size(0), len(self.sources), self.audio_channels, x.size(-1)) - return x diff --git a/spaces/Kangarroar/ApplioRVC-Inference/infer/modules/train/extract_feature_print.py b/spaces/Kangarroar/ApplioRVC-Inference/infer/modules/train/extract_feature_print.py deleted file mode 100644 index f771dd9b8ba92262e6844e7b5781de43c342833a..0000000000000000000000000000000000000000 --- a/spaces/Kangarroar/ApplioRVC-Inference/infer/modules/train/extract_feature_print.py +++ /dev/null @@ -1,137 +0,0 @@ -import os -import sys -import traceback - -os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" -os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0" - -device = sys.argv[1] -n_part = int(sys.argv[2]) -i_part = int(sys.argv[3]) -if len(sys.argv) == 6: - exp_dir = sys.argv[4] - version = sys.argv[5] -else: - i_gpu = sys.argv[4] - exp_dir = sys.argv[5] - os.environ["CUDA_VISIBLE_DEVICES"] = str(i_gpu) - version = sys.argv[6] -import fairseq -import numpy as np -import soundfile as sf -import torch -import torch.nn.functional as F - -if "privateuseone" not in device: - device = "cpu" - if torch.cuda.is_available(): - device = "cuda" - elif torch.backends.mps.is_available(): - device = "mps" -else: - import torch_directml - - device = torch_directml.device(torch_directml.default_device()) - - def forward_dml(ctx, x, scale): - ctx.scale = scale - res = x.clone().detach() - return res - - fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml - -f = open("%s/extract_f0_feature.log" % exp_dir, "a+") - - -def printt(strr): - print(strr) - f.write("%s\n" % strr) - f.flush() - - -printt(sys.argv) -model_path = "assets/hubert/hubert_base.pt" - -printt(exp_dir) -wavPath = "%s/1_16k_wavs" % exp_dir -outPath = ( - "%s/3_feature256" % exp_dir if version == "v1" else "%s/3_feature768" % exp_dir -) -os.makedirs(outPath, exist_ok=True) - - -# wave must be 16k, hop_size=320 -def readwave(wav_path, normalize=False): - wav, sr = sf.read(wav_path) - assert sr == 16000 - feats = torch.from_numpy(wav).float() - if feats.dim() == 2: # double channels - feats = feats.mean(-1) - assert feats.dim() == 1, feats.dim() - if normalize: - with torch.no_grad(): - feats = F.layer_norm(feats, feats.shape) - feats = feats.view(1, -1) - return feats - - -# HuBERT model -printt("load model(s) from {}".format(model_path)) -# if hubert model is exist -if os.access(model_path, os.F_OK) == False: - printt( - "Error: Extracting is shut down because %s does not exist, you may download it from https://huggingface.co/lj1995/VoiceConversionWebUI/tree/main" - % model_path - ) - exit(0) -models, saved_cfg, task = fairseq.checkpoint_utils.load_model_ensemble_and_task( - [model_path], - suffix="", -) -model = models[0] -model = model.to(device) -printt("move model to %s" % device) -if device not in ["mps", "cpu"]: - model = model.half() -model.eval() - -todo = sorted(list(os.listdir(wavPath)))[i_part::n_part] -n = max(1, len(todo) // 10) # 最多打印十条 -if len(todo) == 0: - printt("no-feature-todo") -else: - printt("all-feature-%s" % len(todo)) - for idx, file in enumerate(todo): - try: - if file.endswith(".wav"): - wav_path = "%s/%s" % (wavPath, file) - out_path = "%s/%s" % (outPath, file.replace("wav", "npy")) - - if os.path.exists(out_path): - continue - - feats = readwave(wav_path, normalize=saved_cfg.task.normalize) - padding_mask = torch.BoolTensor(feats.shape).fill_(False) - inputs = { - "source": feats.half().to(device) - if device not in ["mps", "cpu"] - else feats.to(device), - "padding_mask": padding_mask.to(device), - "output_layer": 9 if version == "v1" else 12, # layer 9 - } - with torch.no_grad(): - logits = model.extract_features(**inputs) - feats = ( - model.final_proj(logits[0]) if version == "v1" else logits[0] - ) - - feats = feats.squeeze(0).float().cpu().numpy() - if np.isnan(feats).sum() == 0: - np.save(out_path, feats, allow_pickle=False) - else: - printt("%s-contains nan" % file) - if idx % n == 0: - printt("now-%s,all-%s,%s,%s" % (len(todo), idx, file, feats.shape)) - except: - printt(traceback.format_exc()) - printt("all-feature-done") diff --git a/spaces/KenjieDec/RemBG/rembg/commands/b_command.py b/spaces/KenjieDec/RemBG/rembg/commands/b_command.py deleted file mode 100644 index a47118db2cb6cf7b9162696ac97091378ba868ca..0000000000000000000000000000000000000000 --- a/spaces/KenjieDec/RemBG/rembg/commands/b_command.py +++ /dev/null @@ -1,161 +0,0 @@ -import asyncio -import io -import json -import os -import sys -from typing import IO - -import click -from PIL import Image - -from ..bg import remove -from ..session_factory import new_session -from ..sessions import sessions_names - - -@click.command( - name="b", - help="for a byte stream as input", -) -@click.option( - "-m", - "--model", - default="u2net", - type=click.Choice(sessions_names), - show_default=True, - show_choices=True, - help="model name", -) -@click.option( - "-a", - "--alpha-matting", - is_flag=True, - show_default=True, - help="use alpha matting", -) -@click.option( - "-af", - "--alpha-matting-foreground-threshold", - default=240, - type=int, - show_default=True, - help="trimap fg threshold", -) -@click.option( - "-ab", - "--alpha-matting-background-threshold", - default=10, - type=int, - show_default=True, - help="trimap bg threshold", -) -@click.option( - "-ae", - "--alpha-matting-erode-size", - default=10, - type=int, - show_default=True, - help="erode size", -) -@click.option( - "-om", - "--only-mask", - is_flag=True, - show_default=True, - help="output only the mask", -) -@click.option( - "-ppm", - "--post-process-mask", - is_flag=True, - show_default=True, - help="post process the mask", -) -@click.option( - "-bgc", - "--bgcolor", - default=None, - type=(int, int, int, int), - nargs=4, - help="Background color (R G B A) to replace the removed background with", -) -@click.option("-x", "--extras", type=str) -@click.option( - "-o", - "--output_specifier", - type=str, - help="printf-style specifier for output filenames (e.g. 'output-%d.png'))", -) -@click.argument( - "image_width", - type=int, -) -@click.argument( - "image_height", - type=int, -) -def rs_command( - model: str, - extras: str, - image_width: int, - image_height: int, - output_specifier: str, - **kwargs -) -> None: - try: - kwargs.update(json.loads(extras)) - except Exception: - pass - - session = new_session(model) - bytes_per_img = image_width * image_height * 3 - - if output_specifier: - output_dir = os.path.dirname( - os.path.abspath(os.path.expanduser(output_specifier)) - ) - - if not os.path.isdir(output_dir): - os.makedirs(output_dir, exist_ok=True) - - def img_to_byte_array(img: Image) -> bytes: - buff = io.BytesIO() - img.save(buff, format="PNG") - return buff.getvalue() - - async def connect_stdin_stdout(): - loop = asyncio.get_event_loop() - reader = asyncio.StreamReader() - protocol = asyncio.StreamReaderProtocol(reader) - - await loop.connect_read_pipe(lambda: protocol, sys.stdin) - w_transport, w_protocol = await loop.connect_write_pipe( - asyncio.streams.FlowControlMixin, sys.stdout - ) - - writer = asyncio.StreamWriter(w_transport, w_protocol, reader, loop) - return reader, writer - - async def main(): - reader, writer = await connect_stdin_stdout() - - idx = 0 - while True: - try: - img_bytes = await reader.readexactly(bytes_per_img) - if not img_bytes: - break - - img = Image.frombytes("RGB", (image_width, image_height), img_bytes) - output = remove(img, session=session, **kwargs) - - if output_specifier: - output.save((output_specifier % idx), format="PNG") - else: - writer.write(img_to_byte_array(output)) - - idx += 1 - except asyncio.IncompleteReadError: - break - - asyncio.run(main()) diff --git a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/web/static/js/frequency.histogram.view.js b/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/web/static/js/frequency.histogram.view.js deleted file mode 100644 index e350696cf5e3ef8d3182701348d9f0c4db654e40..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/web/static/js/frequency.histogram.view.js +++ /dev/null @@ -1,338 +0,0 @@ -/* -录音 Recorder扩展,频率直方图显示 -使用本扩展需要引入lib.fft.js支持,直方图特意优化主要显示0-5khz语音部分,其他高频显示区域较小,不适合用来展示音乐频谱 - -https://github.com/xiangyuecn/Recorder - -本扩展核心算法主要参考了Java开源库jmp123 版本0.3 的代码: -https://www.iteye.com/topic/851459 -https://sourceforge.net/projects/jmp123/files/ -*/ -(function(){ -"use strict"; - -var FrequencyHistogramView=function(set){ - return new fn(set); -}; -var fn=function(set){ - var This=this; - var o={ - /* - elem:"css selector" //自动显示到dom,并以此dom大小为显示大小 - //或者配置显示大小,手动把frequencyObj.elem显示到别的地方 - ,width:0 //显示宽度 - ,height:0 //显示高度 - - 以上配置二选一 - */ - - scale:2 //缩放系数,应为正整数,使用2(3? no!)倍宽高进行绘制,避免移动端绘制模糊 - - ,fps:20 //绘制帧率,不可过高 - - ,lineCount:30 //直方图柱子数量,数量的多少对性能影响不大,密集运算集中在FFT算法中 - ,widthRatio:0.6 //柱子线条宽度占比,为所有柱子占用整个视图宽度的比例,剩下的空白区域均匀插入柱子中间;默认值也基本相当于一根柱子占0.6,一根空白占0.4;设为1不留空白,当视图不足容下所有柱子时也不留空白 - ,spaceWidth:0 //柱子间空白固定基础宽度,柱子宽度自适应,当不为0时widthRatio无效,当视图不足容下所有柱子时将不会留空白,允许为负数,让柱子发生重叠 - ,minHeight:0 //柱子保留基础高度,position不为±1时应该保留点高度 - ,position:-1 //绘制位置,取值-1到1,-1为最底下,0为中间,1为最顶上,小数为百分比 - ,mirrorEnable:false //是否启用镜像,如果启用,视图宽度会分成左右两块,右边这块进行绘制,左边这块进行镜像(以中间这根柱子的中心进行镜像) - - ,stripeEnable:true //是否启用柱子顶上的峰值小横条,position不是-1时应当关闭,否则会很丑 - ,stripeHeight:3 //峰值小横条基础高度 - ,stripeMargin:6 //峰值小横条和柱子保持的基础距离 - - ,fallDuration:1000 //柱子从最顶上下降到最底部最长时间ms - ,stripeFallDuration:3500 //峰值小横条从最顶上下降到底部最长时间ms - - //柱子颜色配置:[位置,css颜色,...] 位置: 取值0.0-1.0之间 - ,linear:[0,"rgba(0,187,17,1)",0.5,"rgba(255,215,0,1)",1,"rgba(255,102,0,1)"] - //峰值小横条渐变颜色配置,取值格式和linear一致,留空为柱子的渐变颜色 - ,stripeLinear:null - - ,shadowBlur:0 //柱子阴影基础大小,设为0不显示阴影,如果柱子数量太多时请勿开启,非常影响性能 - ,shadowColor:"#bbb" //柱子阴影颜色 - ,stripeShadowBlur:-1 //峰值小横条阴影基础大小,设为0不显示阴影,-1为柱子的大小,如果柱子数量太多时请勿开启,非常影响性能 - ,stripeShadowColor:"" //峰值小横条阴影颜色,留空为柱子的阴影颜色 - - //当发生绘制时会回调此方法,参数为当前绘制的频率数据和采样率,可实现多个直方图同时绘制,只消耗一个input输入和计算时间 - ,onDraw:function(frequencyData,sampleRate){} - }; - for(var k in set){ - o[k]=set[k]; - }; - This.set=set=o; - - var elem=set.elem; - if(elem){ - if(typeof(elem)=="string"){ - elem=document.querySelector(elem); - }else if(elem.length){ - elem=elem[0]; - }; - }; - if(elem){ - set.width=elem.offsetWidth; - set.height=elem.offsetHeight; - }; - - var scale=set.scale; - var width=set.width*scale; - var height=set.height*scale; - - var thisElem=This.elem=document.createElement("div"); - var lowerCss=["","transform-origin:0 0;","transform:scale("+(1/scale)+");"]; - thisElem.innerHTML='
      '; - - var canvas=This.canvas=thisElem.querySelector("canvas"); - var ctx=This.ctx=canvas.getContext("2d"); - canvas.width=width; - canvas.height=height; - - if(elem){ - elem.innerHTML=""; - elem.appendChild(thisElem); - }; - - if(!Recorder.LibFFT){ - throw new Error("需要lib.fft.js支持"); - }; - This.fft=Recorder.LibFFT(1024); - - //柱子所在高度 - This.lastH=[]; - //峰值小横条所在高度 - This.stripesH=[]; -}; -fn.prototype=FrequencyHistogramView.prototype={ - genLinear:function(ctx,colors,from,to){ - var rtv=ctx.createLinearGradient(0,from,0,to); - for(var i=0;iset.stripeFallDuration*1.3){ - //超时没有输入,顶部横条已全部落下,干掉定时器 - clearInterval(This.timer); - This.timer=0; - return; - }; - if(now-drawTime0?originY*(1-posAbs):originY*(1+posAbs)); - }; - - var lastH=This.lastH; - var stripesH=This.stripesH; - var speed=Math.ceil(heightY/(set.fallDuration/(1000/set.fps))); - var stripeSpeed=Math.ceil(heightY/(set.stripeFallDuration/(1000/set.fps))); - var stripeMargin=set.stripeMargin*scale; - - var Y0=1 << (Math.round(Math.log(bufferSize)/Math.log(2) + 3) << 1); - var logY0 = Math.log(Y0)/Math.log(10); - var dBmax=20*Math.log(0x7fff)/Math.log(10); - - var fftSize=bufferSize/2; - var fftSize5k=Math.min(fftSize,Math.floor(fftSize*5000/(sampleRate/2)));//5khz所在位置,8000采样率及以下最高只有4khz - var fftSize5kIsAll=fftSize5k==fftSize; - var line80=fftSize5kIsAll?lineCount:Math.round(lineCount*0.8);//80%的柱子位置 - var fftSizeStep1=fftSize5k/line80; - var fftSizeStep2=fftSize5kIsAll?0:(fftSize-fftSize5k)/(lineCount-line80); - var fftIdx=0; - for(var i=0;i Y0) ? Math.floor((Math.log(maxAmp)/Math.log(10) - logY0) * 17) : 0; - var h=heightY*Math.min(dB/dBmax,1); - - //使柱子匀速下降 - lastH[i]=(lastH[i]||0)-speed; - if(hshi) { - stripesH[i]=h+stripeMargin; - }else{ - //使峰值小横条匀速度下落 - var sh =shi-stripeSpeed; - if(sh < 0){sh = 0;}; - stripesH[i] = sh; - }; - }; - - //开始绘制图形 - ctx.clearRect(0,0,width,height); - - var linear1=This.genLinear(ctx,set.linear,originY,originY-heightY);//上半部分的填充 - var stripeLinear1=set.stripeLinear&&This.genLinear(ctx,set.stripeLinear,originY,originY-heightY)||linear1;//上半部分的峰值小横条填充 - - var linear2=This.genLinear(ctx,set.linear,originY,originY+heightY);//下半部分的填充 - var stripeLinear2=set.stripeLinear&&This.genLinear(ctx,set.stripeLinear,originY,originY+heightY)||linear2;//上半部分的峰值小横条填充 - - //计算柱子间距 - ctx.shadowBlur=set.shadowBlur*scale; - ctx.shadowColor=set.shadowColor; - var mirrorEnable=set.mirrorEnable; - var mirrorCount=mirrorEnable?lineCount*2-1:lineCount;//镜像柱子数量翻一倍-1根 - - var widthRatio=set.widthRatio; - var spaceWidth=set.spaceWidth*scale; - if(spaceWidth!=0){ - widthRatio=(width-spaceWidth*(mirrorCount+1))/width; - }; - - var lineWidth=Math.max(1*scale,Math.floor((width*widthRatio)/mirrorCount));//柱子宽度至少1个单位 - var spaceFloat=(width-mirrorCount*lineWidth)/(mirrorCount+1);//均匀间隔,首尾都留空,可能为负数,柱子将发生重叠 - - //绘制柱子 - var minHeight=set.minHeight*scale; - var mirrorSubX=spaceFloat+lineWidth/2; - var XFloat=mirrorEnable?width/2-mirrorSubX:0;//镜像时,中间柱子位于正中心 - for(var i=0,xFloat=XFloat,x,y,h;iheight){ - y=height-stripeHeight; - }; - ctx.fillStyle=stripeLinear2; - ctx.fillRect(x, y, lineWidth, stripeHeight); - }; - - xFloat+=lineWidth; - }; - }; - - //镜像,从中间直接镜像即可 - if(mirrorEnable){ - var srcW=Math.floor(width/2); - ctx.save(); - ctx.scale(-1,1); - ctx.drawImage(This.canvas,Math.ceil(width/2),0,srcW,height,-srcW,0,srcW,height); - ctx.restore(); - }; - - set.onDraw(frequencyData,sampleRate); - } -}; -Recorder.FrequencyHistogramView=FrequencyHistogramView; - - -})(); \ No newline at end of file diff --git a/spaces/Kevin676/s3prl-vc-vcc2020/app.py b/spaces/Kevin676/s3prl-vc-vcc2020/app.py deleted file mode 100644 index 905c55da46a48f85346ac7e729d86f633aa4c66c..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/s3prl-vc-vcc2020/app.py +++ /dev/null @@ -1,219 +0,0 @@ - -import os -from glob import glob -from loguru import logger -import soundfile as sf -import librosa -import gradio as gr - -from huggingface_hub import hf_hub_download -import time -import torch -import yaml - -from s3prl_vc.upstream.interface import get_upstream -from s3prl.nn import Featurizer -import s3prl_vc.models -from s3prl_vc.utils import read_hdf5 -from s3prl_vc.vocoder import Vocoder - - -# ---------- Settings ---------- -GPU_ID = '-1' -os.environ['CUDA_VISIBLE_DEVICES'] = GPU_ID -DEVICE = 'cuda' if GPU_ID != '-1' else 'cpu' - -SERVER_PORT = 42208 -SERVER_NAME = "0.0.0.0" -SSL_DIR = './keyble_ssl' - -EXAMPLE_DIR = './examples' -en_examples = sorted(glob(os.path.join(EXAMPLE_DIR, "en", '*.wav'))) -jp_examples = sorted(glob(os.path.join(EXAMPLE_DIR, "jp", '*.wav'))) -zh_examples = sorted(glob(os.path.join(EXAMPLE_DIR, "zh", '*.wav'))) - -TRGSPKS = ["TEF1", "TEF2", "TEM1", "TEM2"] - -ref_samples = { - trgspk: sorted(glob(os.path.join("./ref_samples", trgspk, '*.wav'))) - for trgspk in TRGSPKS -} - -# ---------- Logging ---------- -logger.add('app.log', mode='a') -logger.info('============================= App restarted =============================') - -# ---------- Download models ---------- -logger.info('============================= Download models ===========================') - -vocoder_paths = { - "ckpt": hf_hub_download(repo_id="unilight/hifigan_vctk_plus_vcc2020", filename="checkpoint-2500000steps.pkl"), - "config": hf_hub_download(repo_id="unilight/hifigan_vctk_plus_vcc2020", filename="config.yml"), - "stats": hf_hub_download(repo_id="unilight/hifigan_vctk_plus_vcc2020", filename="stats.h5") -} - -vc_model_paths = { - trgspk: { - "ckpt": hf_hub_download(repo_id="unilight/s3prl-vc-vcc2020", filename=f"{trgspk}/checkpoint-10000steps.pkl"), - "config": hf_hub_download(repo_id="unilight/s3prl-vc-vcc2020", filename=f"{trgspk}/config.yml"), - "stats": hf_hub_download(repo_id="unilight/s3prl-vc-vcc2020", filename=f"{trgspk}/stats.h5"), - } for trgspk in TRGSPKS -} - -# ---------- Model ---------- -vc_models = {} -for trgspk in TRGSPKS: - logger.info(f'============================= Setting up model for {trgspk} =============') - checkpoint_path = vc_model_paths[trgspk]["ckpt"] - config_path = vc_model_paths[trgspk]["config"] - stats_path = vc_model_paths[trgspk]["stats"] - with open(config_path) as f: - config = yaml.load(f, Loader=yaml.Loader) - - config["trg_stats"] = { - "mean": torch.from_numpy(read_hdf5(stats_path, "mean")).float().to(DEVICE), - "scale": torch.from_numpy(read_hdf5(stats_path, "scale")) - .float() - .to(DEVICE), - } - - # define upstream model - upstream_model = get_upstream(config["upstream"]).to(DEVICE) - upstream_model.eval() - upstream_featurizer = Featurizer(upstream_model).to(DEVICE) - upstream_featurizer.load_state_dict( - torch.load(checkpoint_path, map_location="cpu")["featurizer"] - ) - upstream_featurizer.eval() - - # get model and load parameters - model_class = getattr(s3prl_vc.models, config["model_type"]) - model = model_class( - upstream_featurizer.output_size, - config["num_mels"], - config["sampling_rate"] - / config["hop_size"] - * upstream_featurizer.downsample_rate - / 16000, - config["trg_stats"], - use_spemb=config.get("use_spk_emb", False), - **config["model_params"], - ).to(DEVICE) - model.load_state_dict(torch.load(checkpoint_path, map_location="cpu")["model"]) - model = model.eval().to(DEVICE) - logger.info(f"Loaded model parameters from {checkpoint_path}.") - - # load vocoder - vocoder = Vocoder( - vocoder_paths["ckpt"], - vocoder_paths["config"], - vocoder_paths["stats"], - config["trg_stats"], - DEVICE, - ) - - vc_models[trgspk] = { - "upstream": upstream_model, - "featurizer": upstream_featurizer, - "decoder": model, - "vocoder": vocoder - } - -def predict(trgspk, wav_file): - x, fs = librosa.load(wav_file, sr=16000) - logger.info('wav file loaded') - - with torch.no_grad(): - start_time = time.time() - xs = torch.from_numpy(x).unsqueeze(0).float().to(DEVICE) - ilens = torch.LongTensor([x.shape[0]]).to(DEVICE) - - all_hs, all_hlens = vc_models[trgspk]["upstream"](xs, ilens) - logger.info('upstream done') - - hs, hlens = vc_models[trgspk]["featurizer"](all_hs, all_hlens) - logger.info('featurizer done') - - outs, _ = vc_models[trgspk]["decoder"](hs, hlens, spk_embs=None) - logger.info('downstream done') - - out = outs[0] - y, sr = vc_models[trgspk]["vocoder"].decode(out) - logger.info('vocoder done') - sf.write( - "out.wav", - y.cpu().numpy(), - 24000, - "PCM_16", - ) - logger.info('write done') - logger.info('RTF={}'.format( - (time.time() - start_time) / (len(x) / 16000) - )) - - return "out.wav" - -with gr.Blocks(title="S3PRL-VC: Any-to-one voice conversion demo on VCC2020") as demo: - gr.Markdown( - """ - # S3PRL-VC: Any-to-one voice conversion demo on VCC2020 - - ### [[Paper (ICASSP2023)]](https://arxiv.org/abs/2110.06280) [[Paper(JSTSP)]](https://arxiv.org/abs/2207.04356) [[Code]](https://github.com/unilight/s3prl-vc) - - **S3PRL-VC** is a voice conversion (VC) toolkit for benchmarking self-supervised speech representations (S3Rs). The term **any-to-one** means that the system can convert from any unseen speaker to a pre-defined speaker given in training. - - In this demo, you can record your voice, and the model will convert your voice to one of the four pre-defined speakers. These four speakers come from the **voice conversion challenge (VCC) 2020**. You can listen to the samples to get a sense of what these speakers sound like. - - The **RTF** of the system is around **1.5~2.5**, i.e. if you recorded a 5 second long audio, it will take 5 * (1.5~2.5) = 7.5~12.5 seconds to generate the output. - """ - ) - - with gr.Row(): - with gr.Column(): - gr.Markdown("## Upload a .wav file here!") - input_wav = gr.Audio(label="Source speech", source='upload', type='filepath') - - gr.Markdown("## Select a target speaker!") - trgspk = gr.Radio(label="Target speaker", choices=["TEF1", "TEF2", "TEM1", "TEM2"]) - gr.Markdown("### Here is what the target speaker sounds like!") - ref_sample_wav1 = gr.Audio(label="Sample 1", type="filepath") - ref_sample_wav2 = gr.Audio(label="Sample 2", type="filepath") - trgspk.change(lambda trgspk: ref_samples[trgspk], - inputs = trgspk, - outputs = [ref_sample_wav1, ref_sample_wav2] - ) - - convert_btn = gr.Button(value="Convert!") - gr.Markdown("### You can use these examples if using a microphone is too troublesome!") - gr.Markdown("I recorded the samples using my Macbook Pro, so there might be some noises.") - gr.Examples( - examples=en_examples, - inputs=input_wav, - label="English examples" - ) - gr.Examples( - examples=jp_examples, - inputs=input_wav, - label="Japanese examples" - ) - gr.Examples( - examples=zh_examples, - inputs=input_wav, - label="Mandarin examples" - ) - - with gr.Column(): - gr.Markdown("## Listen to the converted speech here!") - output_wav = gr.Audio(type="filepath", label="Converted speech") - convert_btn.click(predict, [trgspk, input_wav], output_wav) - -if __name__ == '__main__': - try: - demo.launch(debug=True, - enable_queue=True, - ) - except KeyboardInterrupt as e: - print(e) - - finally: - demo.close() \ No newline at end of file diff --git a/spaces/KyanChen/RSPrompter/mmdet/utils/dist_utils.py b/spaces/KyanChen/RSPrompter/mmdet/utils/dist_utils.py deleted file mode 100644 index 2f2c8614a181ec0594ba157002a2760737e2c6e3..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/utils/dist_utils.py +++ /dev/null @@ -1,184 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import functools -import pickle -import warnings -from collections import OrderedDict - -import numpy as np -import torch -import torch.distributed as dist -from mmengine.dist import get_dist_info -from torch._utils import (_flatten_dense_tensors, _take_tensors, - _unflatten_dense_tensors) - - -def _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1): - if bucket_size_mb > 0: - bucket_size_bytes = bucket_size_mb * 1024 * 1024 - buckets = _take_tensors(tensors, bucket_size_bytes) - else: - buckets = OrderedDict() - for tensor in tensors: - tp = tensor.type() - if tp not in buckets: - buckets[tp] = [] - buckets[tp].append(tensor) - buckets = buckets.values() - - for bucket in buckets: - flat_tensors = _flatten_dense_tensors(bucket) - dist.all_reduce(flat_tensors) - flat_tensors.div_(world_size) - for tensor, synced in zip( - bucket, _unflatten_dense_tensors(flat_tensors, bucket)): - tensor.copy_(synced) - - -def allreduce_grads(params, coalesce=True, bucket_size_mb=-1): - """Allreduce gradients. - - Args: - params (list[torch.Parameters]): List of parameters of a model - coalesce (bool, optional): Whether allreduce parameters as a whole. - Defaults to True. - bucket_size_mb (int, optional): Size of bucket, the unit is MB. - Defaults to -1. - """ - grads = [ - param.grad.data for param in params - if param.requires_grad and param.grad is not None - ] - world_size = dist.get_world_size() - if coalesce: - _allreduce_coalesced(grads, world_size, bucket_size_mb) - else: - for tensor in grads: - dist.all_reduce(tensor.div_(world_size)) - - -def reduce_mean(tensor): - """"Obtain the mean of tensor on different GPUs.""" - if not (dist.is_available() and dist.is_initialized()): - return tensor - tensor = tensor.clone() - dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM) - return tensor - - -def obj2tensor(pyobj, device='cuda'): - """Serialize picklable python object to tensor.""" - storage = torch.ByteStorage.from_buffer(pickle.dumps(pyobj)) - return torch.ByteTensor(storage).to(device=device) - - -def tensor2obj(tensor): - """Deserialize tensor to picklable python object.""" - return pickle.loads(tensor.cpu().numpy().tobytes()) - - -@functools.lru_cache() -def _get_global_gloo_group(): - """Return a process group based on gloo backend, containing all the ranks - The result is cached.""" - if dist.get_backend() == 'nccl': - return dist.new_group(backend='gloo') - else: - return dist.group.WORLD - - -def all_reduce_dict(py_dict, op='sum', group=None, to_float=True): - """Apply all reduce function for python dict object. - - The code is modified from https://github.com/Megvii- - BaseDetection/YOLOX/blob/main/yolox/utils/allreduce_norm.py. - - NOTE: make sure that py_dict in different ranks has the same keys and - the values should be in the same shape. Currently only supports - nccl backend. - - Args: - py_dict (dict): Dict to be applied all reduce op. - op (str): Operator, could be 'sum' or 'mean'. Default: 'sum' - group (:obj:`torch.distributed.group`, optional): Distributed group, - Default: None. - to_float (bool): Whether to convert all values of dict to float. - Default: True. - - Returns: - OrderedDict: reduced python dict object. - """ - warnings.warn( - 'group` is deprecated. Currently only supports NCCL backend.') - _, world_size = get_dist_info() - if world_size == 1: - return py_dict - - # all reduce logic across different devices. - py_key = list(py_dict.keys()) - if not isinstance(py_dict, OrderedDict): - py_key_tensor = obj2tensor(py_key) - dist.broadcast(py_key_tensor, src=0) - py_key = tensor2obj(py_key_tensor) - - tensor_shapes = [py_dict[k].shape for k in py_key] - tensor_numels = [py_dict[k].numel() for k in py_key] - - if to_float: - warnings.warn('Note: the "to_float" is True, you need to ' - 'ensure that the behavior is reasonable.') - flatten_tensor = torch.cat( - [py_dict[k].flatten().float() for k in py_key]) - else: - flatten_tensor = torch.cat([py_dict[k].flatten() for k in py_key]) - - dist.all_reduce(flatten_tensor, op=dist.ReduceOp.SUM) - if op == 'mean': - flatten_tensor /= world_size - - split_tensors = [ - x.reshape(shape) for x, shape in zip( - torch.split(flatten_tensor, tensor_numels), tensor_shapes) - ] - out_dict = {k: v for k, v in zip(py_key, split_tensors)} - if isinstance(py_dict, OrderedDict): - out_dict = OrderedDict(out_dict) - return out_dict - - -def sync_random_seed(seed=None, device='cuda'): - """Make sure different ranks share the same seed. - - All workers must call this function, otherwise it will deadlock. - This method is generally used in `DistributedSampler`, - because the seed should be identical across all processes - in the distributed group. - - In distributed sampling, different ranks should sample non-overlapped - data in the dataset. Therefore, this function is used to make sure that - each rank shuffles the data indices in the same order based - on the same seed. Then different ranks could use different indices - to select non-overlapped data from the same data list. - - Args: - seed (int, Optional): The seed. Default to None. - device (str): The device where the seed will be put on. - Default to 'cuda'. - - Returns: - int: Seed to be used. - """ - if seed is None: - seed = np.random.randint(2**31) - assert isinstance(seed, int) - - rank, world_size = get_dist_info() - - if world_size == 1: - return seed - - if rank == 0: - random_num = torch.tensor(seed, dtype=torch.int32, device=device) - else: - random_num = torch.tensor(0, dtype=torch.int32, device=device) - dist.broadcast(random_num, src=0) - return random_num.item() diff --git a/spaces/L0SG/BigVGAN/meldataset.py b/spaces/L0SG/BigVGAN/meldataset.py deleted file mode 100644 index 306f301802ddf1c87fd5f9c55dc125e41c45cbcd..0000000000000000000000000000000000000000 --- a/spaces/L0SG/BigVGAN/meldataset.py +++ /dev/null @@ -1,212 +0,0 @@ -# Copyright (c) 2022 NVIDIA CORPORATION. -# Licensed under the MIT license. - -# Adapted from https://github.com/jik876/hifi-gan under the MIT license. -# LICENSE is in incl_licenses directory. - -import math -import os -import random -import torch -import torch.utils.data -import numpy as np -from librosa.util import normalize -from scipy.io.wavfile import read -from librosa.filters import mel as librosa_mel_fn -import pathlib -from tqdm import tqdm - -MAX_WAV_VALUE = 32768.0 - - -def load_wav(full_path, sr_target): - sampling_rate, data = read(full_path) - if sampling_rate != sr_target: - raise RuntimeError("Sampling rate of the file {} is {} Hz, but the model requires {} Hz". - format(full_path, sampling_rate, sr_target)) - 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 - - -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 mel_spectrogram(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 - if fmax not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device) - hann_window[str(y.device)] = torch.hann_window(win_size).to(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) - - # complex tensor as default, then use view_as_real for future pytorch compatibility - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)], - center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True) - spec = torch.view_as_real(spec) - spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9)) - - spec = torch.matmul(mel_basis[str(fmax)+'_'+str(y.device)], spec) - spec = spectral_normalize_torch(spec) - - return spec - - -def get_dataset_filelist(a): - with open(a.input_training_file, 'r', encoding='utf-8') as fi: - training_files = [os.path.join(a.input_wavs_dir, x.split('|')[0] + '.wav') - for x in fi.read().split('\n') if len(x) > 0] - print("first training file: {}".format(training_files[0])) - - with open(a.input_validation_file, 'r', encoding='utf-8') as fi: - validation_files = [os.path.join(a.input_wavs_dir, x.split('|')[0] + '.wav') - for x in fi.read().split('\n') if len(x) > 0] - print("first validation file: {}".format(validation_files[0])) - - list_unseen_validation_files = [] - for i in range(len(a.list_input_unseen_validation_file)): - with open(a.list_input_unseen_validation_file[i], 'r', encoding='utf-8') as fi: - unseen_validation_files = [os.path.join(a.list_input_unseen_wavs_dir[i], x.split('|')[0] + '.wav') - for x in fi.read().split('\n') if len(x) > 0] - print("first unseen {}th validation fileset: {}".format(i, unseen_validation_files[0])) - list_unseen_validation_files.append(unseen_validation_files) - - return training_files, validation_files, list_unseen_validation_files - - -class MelDataset(torch.utils.data.Dataset): - def __init__(self, training_files, hparams, segment_size, n_fft, num_mels, - hop_size, win_size, sampling_rate, fmin, fmax, split=True, shuffle=True, n_cache_reuse=1, - device=None, fmax_loss=None, fine_tuning=False, base_mels_path=None, is_seen=True): - self.audio_files = training_files - random.seed(1234) - if shuffle: - random.shuffle(self.audio_files) - self.hparams = hparams - self.is_seen = is_seen - if self.is_seen: - self.name = pathlib.Path(self.audio_files[0]).parts[0] - else: - self.name = '-'.join(pathlib.Path(self.audio_files[0]).parts[:2]).strip("/") - - self.segment_size = segment_size - self.sampling_rate = sampling_rate - self.split = split - self.n_fft = n_fft - self.num_mels = num_mels - self.hop_size = hop_size - self.win_size = win_size - self.fmin = fmin - self.fmax = fmax - self.fmax_loss = fmax_loss - self.cached_wav = None - self.n_cache_reuse = n_cache_reuse - self._cache_ref_count = 0 - self.device = device - self.fine_tuning = fine_tuning - self.base_mels_path = base_mels_path - - print("INFO: checking dataset integrity...") - for i in tqdm(range(len(self.audio_files))): - assert os.path.exists(self.audio_files[i]), "{} not found".format(self.audio_files[i]) - - def __getitem__(self, index): - - filename = self.audio_files[index] - if self._cache_ref_count == 0: - audio, sampling_rate = load_wav(filename, self.sampling_rate) - audio = audio / MAX_WAV_VALUE - if not self.fine_tuning: - audio = normalize(audio) * 0.95 - self.cached_wav = audio - if sampling_rate != self.sampling_rate: - raise ValueError("{} SR doesn't match target {} SR".format( - sampling_rate, self.sampling_rate)) - self._cache_ref_count = self.n_cache_reuse - else: - audio = self.cached_wav - self._cache_ref_count -= 1 - - audio = torch.FloatTensor(audio) - audio = audio.unsqueeze(0) - - if not self.fine_tuning: - if self.split: - if audio.size(1) >= self.segment_size: - max_audio_start = audio.size(1) - self.segment_size - audio_start = random.randint(0, max_audio_start) - audio = audio[:, audio_start:audio_start+self.segment_size] - else: - audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), 'constant') - - mel = mel_spectrogram(audio, self.n_fft, self.num_mels, - self.sampling_rate, self.hop_size, self.win_size, self.fmin, self.fmax, - center=False) - else: # validation step - # match audio length to self.hop_size * n for evaluation - if (audio.size(1) % self.hop_size) != 0: - audio = audio[:, :-(audio.size(1) % self.hop_size)] - mel = mel_spectrogram(audio, self.n_fft, self.num_mels, - self.sampling_rate, self.hop_size, self.win_size, self.fmin, self.fmax, - center=False) - assert audio.shape[1] == mel.shape[2] * self.hop_size, "audio shape {} mel shape {}".format(audio.shape, mel.shape) - - else: - mel = np.load( - os.path.join(self.base_mels_path, os.path.splitext(os.path.split(filename)[-1])[0] + '.npy')) - mel = torch.from_numpy(mel) - - if len(mel.shape) < 3: - mel = mel.unsqueeze(0) - - if self.split: - frames_per_seg = math.ceil(self.segment_size / self.hop_size) - - if audio.size(1) >= self.segment_size: - mel_start = random.randint(0, mel.size(2) - frames_per_seg - 1) - mel = mel[:, :, mel_start:mel_start + frames_per_seg] - audio = audio[:, mel_start * self.hop_size:(mel_start + frames_per_seg) * self.hop_size] - else: - mel = torch.nn.functional.pad(mel, (0, frames_per_seg - mel.size(2)), 'constant') - audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), 'constant') - - mel_loss = mel_spectrogram(audio, self.n_fft, self.num_mels, - self.sampling_rate, self.hop_size, self.win_size, self.fmin, self.fmax_loss, - center=False) - - return (mel.squeeze(), audio.squeeze(0), filename, mel_loss.squeeze()) - - def __len__(self): - return len(self.audio_files) diff --git a/spaces/LH66/BingAI/Dockerfile b/spaces/LH66/BingAI/Dockerfile deleted file mode 100644 index 3698c7cb7938e025afc53b18a571ae2961fbdffe..0000000000000000000000000000000000000000 --- a/spaces/LH66/BingAI/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -# Build Stage -# 使用 golang:alpine 作为构建阶段的基础镜像 -FROM golang:alpine AS builder - -# 添加 git,以便之后能从GitHub克隆项目 -RUN apk --no-cache add git - -# 从 GitHub 克隆 go-proxy-bingai 项目到 /workspace/app 目录下 -RUN git clone https://github.com/Harry-zklcdc/go-proxy-bingai.git /workspace/app - -# 设置工作目录为之前克隆的项目目录 -WORKDIR /workspace/app - -# 编译 go 项目。-ldflags="-s -w" 是为了减少编译后的二进制大小 -RUN go build -ldflags="-s -w" -tags netgo -trimpath -o go-proxy-bingai main.go - -# Runtime Stage -# 使用轻量级的 alpine 镜像作为运行时的基础镜像 -FROM alpine - -# 设置工作目录 -WORKDIR /workspace/app - -# 从构建阶段复制编译后的二进制文件到运行时镜像中 -COPY --from=builder /workspace/app/go-proxy-bingai . - -# 设置环境变量,此处为随机字符 -ENV Go_Proxy_BingAI_USER_TOKEN_1="kJs8hD92ncMzLaoQWYtX5rG6bE3fZ4iO" - -# 暴露8080端口 -EXPOSE 8080 - -# 容器启动时运行的命令 -CMD ["/workspace/app/go-proxy-bingai"] \ No newline at end of file diff --git a/spaces/Lamai/LAMAIGPT/README.md b/spaces/Lamai/LAMAIGPT/README.md deleted file mode 100644 index 5bf09b995f04f7af05d1314906b1b1ff39c20ddc..0000000000000000000000000000000000000000 --- a/spaces/Lamai/LAMAIGPT/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: AutoGPT -emoji: 🦾 -colorFrom: yellow -colorTo: yellow -sdk: gradio -sdk_version: 3.27.0 -app_file: ui/app.py -pinned: false -license: mit -duplicated_from: aliabid94/AutoGPT ---- - diff --git a/spaces/LaynzKunz/Model-RCV/lib/infer_pack/models_onnx.py b/spaces/LaynzKunz/Model-RCV/lib/infer_pack/models_onnx.py deleted file mode 100644 index 963e67b29f828e9fdd096397952054fe77cf3d10..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Model-RCV/lib/infer_pack/models_onnx.py +++ /dev/null @@ -1,819 +0,0 @@ -import math, pdb, os -from time import time as ttime -import torch -from torch import nn -from torch.nn import functional as F -from lib.infer_pack import modules -from lib.infer_pack import attentions -from lib.infer_pack import commons -from lib.infer_pack.commons import init_weights, get_padding -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from lib.infer_pack.commons import init_weights -import numpy as np -from lib.infer_pack import commons - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder768(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(768, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMsNSFsidM(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - version, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - if version == "v1": - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - else: - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - self.speaker_map = None - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def construct_spkmixmap(self, n_speaker): - self.speaker_map = torch.zeros((n_speaker, 1, 1, self.gin_channels)) - for i in range(n_speaker): - self.speaker_map[i] = self.emb_g(torch.LongTensor([[i]])) - self.speaker_map = self.speaker_map.unsqueeze(0) - - def forward(self, phone, phone_lengths, pitch, nsff0, g, rnd, max_len=None): - if self.speaker_map is not None: # [N, S] * [S, B, 1, H] - g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1] - g = g * self.speaker_map # [N, S, B, 1, H] - g = torch.sum(g, dim=1) # [N, 1, B, 1, H] - g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N] - else: - g = g.unsqueeze(0) - g = self.emb_g(g).transpose(1, 2) - - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * rnd) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g) - return o - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class MultiPeriodDiscriminatorV2(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminatorV2, self).__init__() - # periods = [2, 3, 5, 7, 11, 17] - periods = [2, 3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/Lbin123/Lbingo/src/components/chat-suggestions.tsx b/spaces/Lbin123/Lbingo/src/components/chat-suggestions.tsx deleted file mode 100644 index 00c2fee295c9e010946046eb71705a5e131f7a5a..0000000000000000000000000000000000000000 --- a/spaces/Lbin123/Lbingo/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/Lianjd/stock_dashboard/backtrader/indicators/aroon.py b/spaces/Lianjd/stock_dashboard/backtrader/indicators/aroon.py deleted file mode 100644 index 34a3e57e6b15a3cafea3f3dd36299850530c9357..0000000000000000000000000000000000000000 --- a/spaces/Lianjd/stock_dashboard/backtrader/indicators/aroon.py +++ /dev/null @@ -1,197 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8; py-indent-offset:4 -*- -############################################################################### -# -# Copyright (C) 2015-2020 Daniel Rodriguez -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# -############################################################################### -from __future__ import (absolute_import, division, print_function, - unicode_literals) - -from . import Indicator, FindFirstIndexHighest, FindFirstIndexLowest - - -class _AroonBase(Indicator): - ''' - Base class which does the calculation of the AroonUp/AroonDown values and - defines the common parameters. - - It uses the class attributes _up and _down (boolean flags) to decide which - value has to be calculated. - - Values are not assigned to lines but rather stored in the "up" and "down" - instance variables, which can be used by subclasses to for assignment or - further calculations - ''' - _up = False - _down = False - - params = (('period', 14), ('upperband', 70), ('lowerband', 30),) - plotinfo = dict(plotymargin=0.05, plotyhlines=[0, 100]) - - def _plotlabel(self): - plabels = [self.p.period] - return plabels - - def _plotinit(self): - self.plotinfo.plotyhlines += [self.p.lowerband, self.p.upperband] - - def __init__(self): - # Look backwards period + 1 for current data because the formula mus - # produce values between 0 and 100 and can only do that if the - # calculated hhidx/llidx go from 0 to period (hence period + 1 values) - idxperiod = self.p.period + 1 - - if self._up: - hhidx = FindFirstIndexHighest(self.data.high, period=idxperiod) - self.up = (100.0 / self.p.period) * (self.p.period - hhidx) - - if self._down: - llidx = FindFirstIndexLowest(self.data.low, period=idxperiod) - self.down = (100.0 / self.p.period) * (self.p.period - llidx) - - super(_AroonBase, self).__init__() - - -class AroonUp(_AroonBase): - ''' - This is the AroonUp from the indicator AroonUpDown developed by Tushar - Chande in 1995. - - Formula: - - up = 100 * (period - distance to highest high) / period - - Note: - The lines oscillate between 0 and 100. That means that the "distance" to - the last highest or lowest must go from 0 to period so that the formula - can yield 0 and 100. - - Hence the lookback period is period + 1, because the current bar is also - taken into account. And therefore this indicator needs an effective - lookback period of period + 1. - - See: - - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon - ''' - _up = True - - lines = ('aroonup',) - - def __init__(self): - super(AroonUp, self).__init__() - - self.lines.aroonup = self.up - - -class AroonDown(_AroonBase): - ''' - This is the AroonDown from the indicator AroonUpDown developed by Tushar - Chande in 1995. - - Formula: - - down = 100 * (period - distance to lowest low) / period - - Note: - The lines oscillate between 0 and 100. That means that the "distance" to - the last highest or lowest must go from 0 to period so that the formula - can yield 0 and 100. - - Hence the lookback period is period + 1, because the current bar is also - taken into account. And therefore this indicator needs an effective - lookback period of period + 1. - - See: - - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon - ''' - _down = True - - lines = ('aroondown',) - - def __init__(self): - super(AroonDown, self).__init__() - - self.lines.aroondown = self.down - - -class AroonUpDown(AroonUp, AroonDown): - ''' - Developed by Tushar Chande in 1995. - - It tries to determine if a trend exists or not by calculating how far away - within a given period the last highs/lows are (AroonUp/AroonDown) - - Formula: - - up = 100 * (period - distance to highest high) / period - - down = 100 * (period - distance to lowest low) / period - - Note: - The lines oscillate between 0 and 100. That means that the "distance" to - the last highest or lowest must go from 0 to period so that the formula - can yield 0 and 100. - - Hence the lookback period is period + 1, because the current bar is also - taken into account. And therefore this indicator needs an effective - lookback period of period + 1. - - See: - - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon - ''' - alias = ('AroonIndicator',) - - -class AroonOscillator(_AroonBase): - ''' - It is a variation of the AroonUpDown indicator which shows the current - difference between the AroonUp and AroonDown value, trying to present a - visualization which indicates which is stronger (greater than 0 -> AroonUp - and less than 0 -> AroonDown) - - Formula: - - aroonosc = aroonup - aroondown - - See: - - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon - ''' - _up = True - _down = True - - alias = ('AroonOsc',) - - lines = ('aroonosc',) - - def _plotinit(self): - super(AroonOscillator, self)._plotinit() - - for yhline in self.plotinfo.plotyhlines[:]: - self.plotinfo.plotyhlines.append(-yhline) - - def __init__(self): - super(AroonOscillator, self).__init__() - - self.lines.aroonosc = self.up - self.down - - -class AroonUpDownOscillator(AroonUpDown, AroonOscillator): - ''' - Presents together the indicators AroonUpDown and AroonOsc - - Formula: - (None, uses the aforementioned indicators) - - See: - - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon - ''' - alias = ('AroonUpDownOsc',) diff --git a/spaces/Liu-LAB/GPT-academic/crazy_functions/json_fns/pydantic_io.py b/spaces/Liu-LAB/GPT-academic/crazy_functions/json_fns/pydantic_io.py deleted file mode 100644 index 4e300d65dd918f890d64e68e0cc5a37f36366585..0000000000000000000000000000000000000000 --- a/spaces/Liu-LAB/GPT-academic/crazy_functions/json_fns/pydantic_io.py +++ /dev/null @@ -1,111 +0,0 @@ -""" -https://github.com/langchain-ai/langchain/blob/master/docs/extras/modules/model_io/output_parsers/pydantic.ipynb - -Example 1. - -# Define your desired data structure. -class Joke(BaseModel): - setup: str = Field(description="question to set up a joke") - punchline: str = Field(description="answer to resolve the joke") - - # You can add custom validation logic easily with Pydantic. - @validator("setup") - def question_ends_with_question_mark(cls, field): - if field[-1] != "?": - raise ValueError("Badly formed question!") - return field - - -Example 2. - -# Here's another example, but with a compound typed field. -class Actor(BaseModel): - name: str = Field(description="name of an actor") - film_names: List[str] = Field(description="list of names of films they starred in") -""" - -import json, re, logging - - -PYDANTIC_FORMAT_INSTRUCTIONS = """The output should be formatted as a JSON instance that conforms to the JSON schema below. - -As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} -the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. - -Here is the output schema: -``` -{schema} -```""" - - -PYDANTIC_FORMAT_INSTRUCTIONS_SIMPLE = """The output should be formatted as a JSON instance that conforms to the JSON schema below. -``` -{schema} -```""" - -class JsonStringError(Exception): ... - -class GptJsonIO(): - - def __init__(self, schema, example_instruction=True): - self.pydantic_object = schema - self.example_instruction = example_instruction - self.format_instructions = self.generate_format_instructions() - - def generate_format_instructions(self): - schema = self.pydantic_object.schema() - - # Remove extraneous fields. - reduced_schema = schema - if "title" in reduced_schema: - del reduced_schema["title"] - if "type" in reduced_schema: - del reduced_schema["type"] - # Ensure json in context is well-formed with double quotes. - if self.example_instruction: - schema_str = json.dumps(reduced_schema) - return PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str) - else: - return PYDANTIC_FORMAT_INSTRUCTIONS_SIMPLE.format(schema=schema_str) - - def generate_output(self, text): - # Greedy search for 1st json candidate. - match = re.search( - r"\{.*\}", text.strip(), re.MULTILINE | re.IGNORECASE | re.DOTALL - ) - json_str = "" - if match: json_str = match.group() - json_object = json.loads(json_str, strict=False) - final_object = self.pydantic_object.parse_obj(json_object) - return final_object - - def generate_repair_prompt(self, broken_json, error): - prompt = "Fix a broken json string.\n\n" + \ - "(1) The broken json string need to fix is: \n\n" + \ - "```" + "\n" + \ - broken_json + "\n" + \ - "```" + "\n\n" + \ - "(2) The error message is: \n\n" + \ - error + "\n\n" + \ - "Now, fix this json string. \n\n" - return prompt - - def generate_output_auto_repair(self, response, gpt_gen_fn): - """ - response: string containing canidate json - gpt_gen_fn: gpt_gen_fn(inputs, sys_prompt) - """ - try: - result = self.generate_output(response) - except Exception as e: - try: - logging.info(f'Repairing json:{response}') - repair_prompt = self.generate_repair_prompt(broken_json = response, error=repr(e)) - result = self.generate_output(gpt_gen_fn(repair_prompt, self.format_instructions)) - logging.info('Repaire json success.') - except Exception as e: - # 没辙了,放弃治疗 - logging.info('Repaire json fail.') - raise JsonStringError('Cannot repair json.', str(e)) - return result - diff --git a/spaces/MCkernick/Image_Restoration_Colorization/Global/options/test_options.py b/spaces/MCkernick/Image_Restoration_Colorization/Global/options/test_options.py deleted file mode 100644 index 67e2e3a720cf7f9e540b09b64242197cdb712b57..0000000000000000000000000000000000000000 --- a/spaces/MCkernick/Image_Restoration_Colorization/Global/options/test_options.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -from .base_options import BaseOptions - - -class TestOptions(BaseOptions): - def initialize(self): - BaseOptions.initialize(self) - self.parser.add_argument("--ntest", type=int, default=float("inf"), help="# of test examples.") - self.parser.add_argument("--results_dir", type=str, default="./results/", help="saves results here.") - self.parser.add_argument( - "--aspect_ratio", type=float, default=1.0, help="aspect ratio of result images" - ) - self.parser.add_argument("--phase", type=str, default="test", help="train, val, test, etc") - self.parser.add_argument( - "--which_epoch", - type=str, - default="latest", - help="which epoch to load? set to latest to use latest cached model", - ) - self.parser.add_argument("--how_many", type=int, default=50, help="how many test images to run") - self.parser.add_argument( - "--cluster_path", - type=str, - default="features_clustered_010.npy", - help="the path for clustered results of encoded features", - ) - self.parser.add_argument( - "--use_encoded_image", - action="store_true", - help="if specified, encode the real image to get the feature map", - ) - self.parser.add_argument("--export_onnx", type=str, help="export ONNX model to a given file") - self.parser.add_argument("--engine", type=str, help="run serialized TRT engine") - self.parser.add_argument("--onnx", type=str, help="run ONNX model via TRT") - self.parser.add_argument( - "--start_epoch", - type=int, - default=-1, - help="write the start_epoch of iter.txt into this parameter", - ) - - self.parser.add_argument("--test_dataset", type=str, default="Real_RGB_old.bigfile") - self.parser.add_argument( - "--no_degradation", - action="store_true", - help="when train the mapping, enable this parameter --> no degradation will be added into clean image", - ) - self.parser.add_argument( - "--no_load_VAE", - action="store_true", - help="when train the mapping, enable this parameter --> random initialize the encoder an decoder", - ) - self.parser.add_argument( - "--use_v2_degradation", - action="store_true", - help="enable this parameter --> 4 kinds of degradations will be used to synthesize corruption", - ) - self.parser.add_argument("--use_vae_which_epoch", type=str, default="latest") - self.isTrain = False - - self.parser.add_argument("--generate_pair", action="store_true") - - self.parser.add_argument("--multi_scale_test", type=float, default=0.5) - self.parser.add_argument("--multi_scale_threshold", type=float, default=0.5) - self.parser.add_argument( - "--mask_need_scale", - action="store_true", - help="enable this param meas that the pixel range of mask is 0-255", - ) - self.parser.add_argument("--scale_num", type=int, default=1) - - self.parser.add_argument( - "--save_feature_url", type=str, default="", help="While extracting the features, where to put" - ) - - self.parser.add_argument( - "--test_input", type=str, default="", help="A directory or a root of bigfile" - ) - self.parser.add_argument("--test_mask", type=str, default="", help="A directory or a root of bigfile") - self.parser.add_argument("--test_gt", type=str, default="", help="A directory or a root of bigfile") - - self.parser.add_argument( - "--scale_input", action="store_true", help="While testing, choose to scale the input firstly" - ) - - self.parser.add_argument( - "--save_feature_name", type=str, default="features.json", help="The name of saved features" - ) - self.parser.add_argument( - "--test_rgb_old_wo_scratch", action="store_true", help="Same setting with origin test" - ) - - self.parser.add_argument("--test_mode", type=str, default="Crop", help="Scale|Full|Crop") - self.parser.add_argument("--Quality_restore", action="store_true", help="For RGB images") - self.parser.add_argument( - "--Scratch_and_Quality_restore", action="store_true", help="For scratched images" - ) - self.parser.add_argument("--HR", action='store_true',help='Large input size with scratches') diff --git a/spaces/Marshalls/testmtd/analysis/aistplusplus_api/smpl/smpl_webuser/serialization.py b/spaces/Marshalls/testmtd/analysis/aistplusplus_api/smpl/smpl_webuser/serialization.py deleted file mode 100644 index c39fc37122108aa81f1d907d58912b044a4f1fa2..0000000000000000000000000000000000000000 --- a/spaces/Marshalls/testmtd/analysis/aistplusplus_api/smpl/smpl_webuser/serialization.py +++ /dev/null @@ -1,137 +0,0 @@ -''' -Copyright 2015 Matthew Loper, Naureen Mahmood and the Max Planck Gesellschaft. All rights reserved. -This software is provided for research purposes only. -By using this software you agree to the terms of the SMPL Model license here http://smpl.is.tue.mpg.de/license - -More information about SMPL is available here http://smpl.is.tue.mpg. -For comments or questions, please email us at: smpl@tuebingen.mpg.de - - -About this file: -================ -This file defines the serialization functions of the SMPL model. - -Modules included: -- save_model: - saves the SMPL model to a given file location as a .pkl file -- load_model: - loads the SMPL model from a given file location (i.e. a .pkl file location), - or a dictionary object. - -''' - -__all__ = ['load_model', 'save_model'] - -import numpy as np -import cPickle as pickle -import chumpy as ch -from chumpy.ch import MatVecMult -from posemapper import posemap -from verts import verts_core - -def save_model(model, fname): - m0 = model - trainer_dict = {'v_template': np.asarray(m0.v_template),'J': np.asarray(m0.J),'weights': np.asarray(m0.weights),'kintree_table': m0.kintree_table,'f': m0.f, 'bs_type': m0.bs_type, 'posedirs': np.asarray(m0.posedirs)} - if hasattr(model, 'J_regressor'): - trainer_dict['J_regressor'] = m0.J_regressor - if hasattr(model, 'J_regressor_prior'): - trainer_dict['J_regressor_prior'] = m0.J_regressor_prior - if hasattr(model, 'weights_prior'): - trainer_dict['weights_prior'] = m0.weights_prior - if hasattr(model, 'shapedirs'): - trainer_dict['shapedirs'] = m0.shapedirs - if hasattr(model, 'vert_sym_idxs'): - trainer_dict['vert_sym_idxs'] = m0.vert_sym_idxs - if hasattr(model, 'bs_style'): - trainer_dict['bs_style'] = model.bs_style - else: - trainer_dict['bs_style'] = 'lbs' - pickle.dump(trainer_dict, open(fname, 'w'), -1) - - -def backwards_compatibility_replacements(dd): - - # replacements - if 'default_v' in dd: - dd['v_template'] = dd['default_v'] - del dd['default_v'] - if 'template_v' in dd: - dd['v_template'] = dd['template_v'] - del dd['template_v'] - if 'joint_regressor' in dd: - dd['J_regressor'] = dd['joint_regressor'] - del dd['joint_regressor'] - if 'blendshapes' in dd: - dd['posedirs'] = dd['blendshapes'] - del dd['blendshapes'] - if 'J' not in dd: - dd['J'] = dd['joints'] - del dd['joints'] - - # defaults - if 'bs_style' not in dd: - dd['bs_style'] = 'lbs' - - - -def ready_arguments(fname_or_dict): - - if not isinstance(fname_or_dict, dict): - dd = pickle.load(open(fname_or_dict)) - else: - dd = fname_or_dict - - backwards_compatibility_replacements(dd) - - want_shapemodel = 'shapedirs' in dd - nposeparms = dd['kintree_table'].shape[1]*3 - - if 'trans' not in dd: - dd['trans'] = np.zeros(3) - if 'pose' not in dd: - dd['pose'] = np.zeros(nposeparms) - if 'shapedirs' in dd and 'betas' not in dd: - dd['betas'] = np.zeros(dd['shapedirs'].shape[-1]) - - for s in ['v_template', 'weights', 'posedirs', 'pose', 'trans', 'shapedirs', 'betas', 'J']: - if (s in dd) and not hasattr(dd[s], 'dterms'): - dd[s] = ch.array(dd[s]) - - if want_shapemodel: - dd['v_shaped'] = dd['shapedirs'].dot(dd['betas'])+dd['v_template'] - v_shaped = dd['v_shaped'] - J_tmpx = MatVecMult(dd['J_regressor'], v_shaped[:,0]) - J_tmpy = MatVecMult(dd['J_regressor'], v_shaped[:,1]) - J_tmpz = MatVecMult(dd['J_regressor'], v_shaped[:,2]) - dd['J'] = ch.vstack((J_tmpx, J_tmpy, J_tmpz)).T - dd['v_posed'] = v_shaped + dd['posedirs'].dot(posemap(dd['bs_type'])(dd['pose'])) - else: - dd['v_posed'] = dd['v_template'] + dd['posedirs'].dot(posemap(dd['bs_type'])(dd['pose'])) - - return dd - - - -def load_model(fname_or_dict): - dd = ready_arguments(fname_or_dict) - - args = { - 'pose': dd['pose'], - 'v': dd['v_posed'], - 'J': dd['J'], - 'weights': dd['weights'], - 'kintree_table': dd['kintree_table'], - 'xp': ch, - 'want_Jtr': True, - 'bs_style': dd['bs_style'] - } - - result, Jtr = verts_core(**args) - result = result + dd['trans'].reshape((1,3)) - result.J_transformed = Jtr + dd['trans'].reshape((1,3)) - - for k, v in dd.items(): - setattr(result, k, v) - - return result - diff --git a/spaces/MaverickHans/selfie/app.py b/spaces/MaverickHans/selfie/app.py deleted file mode 100644 index f16e27801f8551dd1843310044720041738e6bf8..0000000000000000000000000000000000000000 --- a/spaces/MaverickHans/selfie/app.py +++ /dev/null @@ -1,9 +0,0 @@ -import gradio as gr -def segment(image): - with mp_selfie.SelfieSegmentation(model_selection=0) as model: - res=model.process(image) - mask=np.stack((res.segmentation_mask,)*3,axis=-1)>0.5 - return np.where(mask,image,cv2.blur(image,(40,40))) -webcam=gr.inputs.Image(shape=(640,480),source="webcam") -webapp=gr.interface.Interface(fn=segment,inputs=webcam,outputs="image") -webapp.launch(share=False) \ No newline at end of file diff --git a/spaces/MirageML/sjc/adapt_vesde.py b/spaces/MirageML/sjc/adapt_vesde.py deleted file mode 100644 index aeb3dbd5bb914a129599a2bab0cac359c8abcf25..0000000000000000000000000000000000000000 --- a/spaces/MirageML/sjc/adapt_vesde.py +++ /dev/null @@ -1,84 +0,0 @@ -from pathlib import Path -import torch -from ml_collections.config_flags import config_flags - -from sde.config import get_config -from sde import ddpm, ncsnv2, ncsnpp # need to import to trigger its registry -from sde import utils as mutils -from sde.ema import ExponentialMovingAverage - -from adapt import ScoreAdapter - -device = torch.device("cuda") - - -def restore_checkpoint(ckpt_dir, state, device): - loaded_state = torch.load(ckpt_dir, map_location=device) - # state['optimizer'].load_state_dict(loaded_state['optimizer']) - state['model'].load_state_dict(loaded_state['model'], strict=False) - state['ema'].load_state_dict(loaded_state['ema']) - state['step'] = loaded_state['step'] - return state - - -def save_checkpoint(ckpt_dir, state): - saved_state = { - 'optimizer': state['optimizer'].state_dict(), - 'model': state['model'].state_dict(), - 'ema': state['ema'].state_dict(), - 'step': state['step'] - } - torch.save(saved_state, ckpt_dir) - - -class VESDE(ScoreAdapter): - def __init__(self): - config = get_config() - config.device = device - ckpt_fname = self.checkpoint_root() / "sde" / 'checkpoint_127.pth' - - score_model = mutils.create_model(config) - ema = ExponentialMovingAverage( - score_model.parameters(), decay=config.model.ema_rate - ) - state = dict(model=score_model, ema=ema, step=0) - self._data_shape = ( - config.data.num_channels, config.data.image_size, config.data.image_size - ) - - self._σ_min = float(config.model.sigma_min * 2) - - state = restore_checkpoint(ckpt_fname, state, device=config.device) - ema.copy_to(score_model.parameters()) - - score_model.eval() - score_model = score_model.module # remove DataParallel - - self.model = score_model - self._device = device - - def data_shape(self): - return self._data_shape - - @property - def σ_min(self): - return self._σ_min - - @torch.no_grad() - def denoise(self, xs, σ): - N = xs.shape[0] - # see Karras eqn. 212-215 for the 1/2 σ correction - cond_t = (0.5 * σ) * torch.ones(N, device=self.device) - # note that the forward function the model has been modified; see comments - n_hat = self.model(xs, cond_t) - Ds = xs + σ * n_hat - return Ds - - def unet_is_cond(self): - return False - - def use_cls_guidance(self): - return False - - def snap_t_to_nearest_tick(self, t): - return super().snap_t_to_nearest_tick(t) diff --git a/spaces/MohammedAlakhras/AI_Chat/app.py b/spaces/MohammedAlakhras/AI_Chat/app.py deleted file mode 100644 index 0e9dd2df1afeb2f01b746fc2f68f5075f251b19a..0000000000000000000000000000000000000000 --- a/spaces/MohammedAlakhras/AI_Chat/app.py +++ /dev/null @@ -1,37 +0,0 @@ -import platform -import pathlib -import os - -import gradio as gr -import random -import time -from gradio_client import Client - - -plt = platform.system() -pathlib.WindowsPath = pathlib.PosixPath - -#api = os.environ['API'] - - -def chat(message,history): - client = Client('https://openskyml-pigeon-chat.hf.space/') - result = client.predict( - message, - api_name="/chat" - ) - return result - -description=''' -

      -
      -🌍 AI Chat Bot is available worldwide in over **160 languages**.
      -💬 This space is powered by **Huggingface Hosting**.
      -🚀 This space runs **very fast** even on **CPU**.
      -🔗 Facebook Account.
      -🔗 Github Account.
      -BY: Mohammed Alakhras ☑️ -

      -''' -#gr.ChatInterface(chat, title='Mohammed Alakhras AI Chat Bot 💬', description=description).launch() -gr.Interface(fn=chat, inputs="text",outputs="text", title='Mohammed Alakhras AI Chat Bot 💬', description=description).launch() diff --git a/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/module_losses/abi_module_loss.py b/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/module_losses/abi_module_loss.py deleted file mode 100644 index 918847b9d02bcb7f5e9de9abbb2b0d0837dfe47c..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/module_losses/abi_module_loss.py +++ /dev/null @@ -1,99 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from typing import Dict, Sequence, Union - -import torch - -from mmocr.models.common.dictionary import Dictionary -from mmocr.registry import MODELS -from mmocr.structures import TextRecogDataSample -from .base import BaseTextRecogModuleLoss -from .ce_module_loss import CEModuleLoss - - -@MODELS.register_module() -class ABIModuleLoss(BaseTextRecogModuleLoss): - """Implementation of ABINet multiloss that allows mixing different types of - losses with weights. - - Args: - dictionary (dict or :obj:`Dictionary`): The config for `Dictionary` or - the instance of `Dictionary`. - max_seq_len (int): Maximum sequence length. The sequence is usually - generated from decoder. Defaults to 40. - letter_case (str): There are three options to alter the letter cases - of gt texts: - - unchanged: Do not change gt texts. - - upper: Convert gt texts into uppercase characters. - - lower: Convert gt texts into lowercase characters. - Usually, it only works for English characters. Defaults to - 'unchanged'. - weight_vis (float or int): The weight of vision decoder loss. Defaults - to 1.0. - weight_dec (float or int): The weight of language decoder loss. - Defaults to 1.0. - weight_fusion (float or int): The weight of fuser (aligner) loss. - Defaults to 1.0. - """ - - def __init__(self, - dictionary: Union[Dict, Dictionary], - max_seq_len: int = 40, - letter_case: str = 'unchanged', - weight_vis: Union[float, int] = 1.0, - weight_lang: Union[float, int] = 1.0, - weight_fusion: Union[float, int] = 1.0, - **kwargs) -> None: - assert isinstance(weight_vis, (float, int)) - assert isinstance(weight_lang, (float, int)) - assert isinstance(weight_fusion, (float, int)) - super().__init__( - dictionary=dictionary, - max_seq_len=max_seq_len, - letter_case=letter_case) - self.weight_vis = weight_vis - self.weight_lang = weight_lang - self.weight_fusion = weight_fusion - self._ce_loss = CEModuleLoss( - self.dictionary, - max_seq_len, - letter_case, - reduction='mean', - ignore_first_char=True) - - def forward(self, outputs: Dict, - data_samples: Sequence[TextRecogDataSample]) -> Dict: - """ - Args: - outputs (dict): The output dictionary with at least one of - ``out_vis``, ``out_langs`` and ``out_fusers`` specified. - data_samples (list[TextRecogDataSample]): List of - ``TextRecogDataSample`` which are processed by ``get_target``. - - Returns: - dict: A loss dictionary with ``loss_visual``, ``loss_lang`` and - ``loss_fusion``. Each should either be the loss tensor or None if - the output of its corresponding module is not given. - """ - assert 'out_vis' in outputs or \ - 'out_langs' in outputs or 'out_fusers' in outputs - losses = {} - - if outputs.get('out_vis', None): - losses['loss_visual'] = self.weight_vis * self._ce_loss( - outputs['out_vis']['logits'], data_samples)['loss_ce'] - if outputs.get('out_langs', None): - lang_losses = [] - for out_lang in outputs['out_langs']: - lang_losses.append( - self._ce_loss(out_lang['logits'], data_samples)['loss_ce']) - losses['loss_lang'] = self.weight_lang * torch.mean( - torch.stack(lang_losses)) - if outputs.get('out_fusers', None): - fuser_losses = [] - for out_fuser in outputs['out_fusers']: - fuser_losses.append( - self._ce_loss(out_fuser['logits'], - data_samples)['loss_ce']) - losses['loss_fusion'] = self.weight_fusion * torch.mean( - torch.stack(fuser_losses)) - return losses diff --git a/spaces/NCTCMumbai/NCTC/models/official/nlp/bert/model_saving_utils.py b/spaces/NCTCMumbai/NCTC/models/official/nlp/bert/model_saving_utils.py deleted file mode 100644 index 13d2c9ed02f9a98d9dcbb2a60c46fa5cd13bb666..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/nlp/bert/model_saving_utils.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Utilities to save models.""" - -from __future__ import absolute_import -from __future__ import division -# from __future__ import google_type_annotations -from __future__ import print_function - -import os - -from absl import logging -import tensorflow as tf -import typing - - -def export_bert_model(model_export_path: typing.Text, - model: tf.keras.Model, - checkpoint_dir: typing.Optional[typing.Text] = None, - restore_model_using_load_weights: bool = False) -> None: - """Export BERT model for serving which does not include the optimizer. - - Arguments: - model_export_path: Path to which exported model will be saved. - model: Keras model object to export. - checkpoint_dir: Path from which model weights will be loaded, if - specified. - restore_model_using_load_weights: Whether to use checkpoint.restore() API - for custom checkpoint or to use model.load_weights() API. - There are 2 different ways to save checkpoints. One is using - tf.train.Checkpoint and another is using Keras model.save_weights(). - Custom training loop implementation uses tf.train.Checkpoint API - and Keras ModelCheckpoint callback internally uses model.save_weights() - API. Since these two API's cannot be used toghether, model loading logic - must be take into account how model checkpoint was saved. - - Raises: - ValueError when either model_export_path or model is not specified. - """ - if not model_export_path: - raise ValueError('model_export_path must be specified.') - if not isinstance(model, tf.keras.Model): - raise ValueError('model must be a tf.keras.Model object.') - - if checkpoint_dir: - # Keras compile/fit() was used to save checkpoint using - # model.save_weights(). - if restore_model_using_load_weights: - model_weight_path = os.path.join(checkpoint_dir, 'checkpoint') - assert tf.io.gfile.exists(model_weight_path) - model.load_weights(model_weight_path) - - # tf.train.Checkpoint API was used via custom training loop logic. - else: - checkpoint = tf.train.Checkpoint(model=model) - - # Restores the model from latest checkpoint. - latest_checkpoint_file = tf.train.latest_checkpoint(checkpoint_dir) - assert latest_checkpoint_file - logging.info('Checkpoint file %s found and restoring from ' - 'checkpoint', latest_checkpoint_file) - checkpoint.restore( - latest_checkpoint_file).assert_existing_objects_matched() - - model.save(model_export_path, include_optimizer=False, save_format='tf') diff --git a/spaces/NCTCMumbai/NCTC/models/official/nlp/modeling/layers/dense_einsum.py b/spaces/NCTCMumbai/NCTC/models/official/nlp/modeling/layers/dense_einsum.py deleted file mode 100644 index ba2383e6d9e47f1e1d39898c16bf99748e4d38e3..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/nlp/modeling/layers/dense_einsum.py +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Keras-based einsum layer.""" -# pylint: disable=g-classes-have-attributes -from __future__ import absolute_import -from __future__ import division -# from __future__ import google_type_annotations -from __future__ import print_function - -import tensorflow as tf - -_CHR_IDX = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] - - -@tf.keras.utils.register_keras_serializable(package="Text") -class DenseEinsum(tf.keras.layers.Layer): - """A densely connected layer that uses tf.einsum as the backing computation. - - This layer can perform einsum calculations of arbitrary dimensionality. - - Arguments: - output_shape: Positive integer or tuple, dimensionality of the output space. - num_summed_dimensions: The number of dimensions to sum over. Standard 2D - matmul should use 1, 3D matmul should use 2, and so forth. - activation: Activation function to use. If you don't specify anything, no - activation is applied - (ie. "linear" activation: `a(x) = x`). - use_bias: Boolean, whether the layer uses a bias vector. - kernel_initializer: Initializer for the `kernel` weights matrix. - bias_initializer: Initializer for the bias vector. - kernel_regularizer: Regularizer function applied to the `kernel` weights - matrix. - bias_regularizer: Regularizer function applied to the bias vector. - activity_regularizer: Regularizer function applied to the output of the - layer (its "activation").. - kernel_constraint: Constraint function applied to the `kernel` weights - matrix. - bias_constraint: Constraint function applied to the bias vector. - Input shape: - N-D tensor with shape: `(batch_size, ..., input_dim)`. The most common - situation would be a 2D input with shape `(batch_size, input_dim)`. - Output shape: - N-D tensor with shape: `(batch_size, ..., units)`. For instance, for a 2D - input with shape `(batch_size, input_dim)`, the output would have shape - `(batch_size, units)`. - """ - - def __init__(self, - output_shape, - num_summed_dimensions=1, - activation=None, - use_bias=True, - kernel_initializer="glorot_uniform", - bias_initializer="zeros", - kernel_regularizer=None, - bias_regularizer=None, - activity_regularizer=None, - kernel_constraint=None, - bias_constraint=None, - **kwargs): - super(DenseEinsum, self).__init__(**kwargs) - self._output_shape = output_shape if isinstance( - output_shape, (list, tuple)) else (output_shape,) - self._activation = tf.keras.activations.get(activation) - self._use_bias = use_bias - self._kernel_initializer = tf.keras.initializers.get(kernel_initializer) - self._bias_initializer = tf.keras.initializers.get(bias_initializer) - self._kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer) - self._bias_regularizer = tf.keras.regularizers.get(bias_regularizer) - self._kernel_constraint = tf.keras.constraints.get(kernel_constraint) - self._bias_constraint = tf.keras.constraints.get(bias_constraint) - self._num_summed_dimensions = num_summed_dimensions - self._einsum_string = None - - def _build_einsum_string(self, free_input_dims, bound_dims, output_dims): - input_str = "" - kernel_str = "" - output_str = "" - letter_offset = 0 - for i in range(free_input_dims): - char = _CHR_IDX[i + letter_offset] - input_str += char - output_str += char - - letter_offset += free_input_dims - for i in range(bound_dims): - char = _CHR_IDX[i + letter_offset] - input_str += char - kernel_str += char - - letter_offset += bound_dims - for i in range(output_dims): - char = _CHR_IDX[i + letter_offset] - kernel_str += char - output_str += char - - return input_str + "," + kernel_str + "->" + output_str - - def build(self, input_shape): - input_shape = tf.TensorShape(input_shape) - input_rank = input_shape.rank - free_input_dims = input_rank - self._num_summed_dimensions - output_dims = len(self._output_shape) - - self._einsum_string = self._build_einsum_string(free_input_dims, - self._num_summed_dimensions, - output_dims) - - # This is only saved for testing purposes. - self._kernel_shape = ( - input_shape[free_input_dims:].concatenate(self._output_shape)) - - self._kernel = self.add_weight( - "kernel", - shape=self._kernel_shape, - initializer=self._kernel_initializer, - regularizer=self._kernel_regularizer, - constraint=self._kernel_constraint, - dtype=self.dtype, - trainable=True) - if self._use_bias: - self._bias = self.add_weight( - "bias", - shape=self._output_shape, - initializer=self._bias_initializer, - regularizer=self._bias_regularizer, - constraint=self._bias_constraint, - dtype=self.dtype, - trainable=True) - else: - self._bias = None - super(DenseEinsum, self).build(input_shape) - - def get_config(self): - config = { - "output_shape": - self._output_shape, - "num_summed_dimensions": - self._num_summed_dimensions, - "activation": - tf.keras.activations.serialize(self._activation), - "use_bias": - self._use_bias, - "kernel_initializer": - tf.keras.initializers.serialize(self._kernel_initializer), - "bias_initializer": - tf.keras.initializers.serialize(self._bias_initializer), - "kernel_regularizer": - tf.keras.regularizers.serialize(self._kernel_regularizer), - "bias_regularizer": - tf.keras.regularizers.serialize(self._bias_regularizer), - "activity_regularizer": - tf.keras.regularizers.serialize(self._activity_regularizer), - "kernel_constraint": - tf.keras.constraints.serialize(self._kernel_constraint), - "bias_constraint": - tf.keras.constraints.serialize(self._bias_constraint) - } - base_config = super(DenseEinsum, self).get_config() - return dict(list(base_config.items()) + list(config.items())) - - def call(self, inputs): - ret = tf.einsum(self._einsum_string, inputs, self._kernel) - if self._use_bias: - ret += self._bias - if self._activation is not None: - ret = self._activation(ret) - return ret diff --git a/spaces/Naveentalluri/NavenAIvoice/app.py b/spaces/Naveentalluri/NavenAIvoice/app.py deleted file mode 100644 index ca8b6d40b4ab898c70da92f4a4298de2baf703dc..0000000000000000000000000000000000000000 --- a/spaces/Naveentalluri/NavenAIvoice/app.py +++ /dev/null @@ -1,164 +0,0 @@ -import os -import re -import requests -import json -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') -PLAY_HT_API_KEY=os.getenv('PLAY_HT_API_KEY') -PLAY_HT_USER_ID=os.getenv('PLAY_HT_USER_ID') - -PLAY_HT_VOICE_ID=os.getenv('PLAY_HT_VOICE_ID') -play_ht_api_get_audio_url = "https://play.ht/api/v2/tts" - - -template = """You are a helpful assistant to answer user queries. -{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, -) - -headers = { - "accept": "text/event-stream", - "content-type": "application/json", - "AUTHORIZATION": "Bearer "+ PLAY_HT_API_KEY, - "X-USER-ID": PLAY_HT_USER_ID -} - - -def get_payload(text): - return { - "text": text, - "voice": PLAY_HT_VOICE_ID, - "quality": "medium", - "output_format": "mp3", - "speed": 1, - "sample_rate": 24000, - "seed": None, - "temperature": None - } - -def get_generated_audio(text): - payload = get_payload(text) - generated_response = {} - try: - response = requests.post(play_ht_api_get_audio_url, json=payload, headers=headers) - response.raise_for_status() - generated_response["type"]= 'SUCCESS' - generated_response["response"] = response.text - except requests.exceptions.RequestException as e: - generated_response["type"]= 'ERROR' - try: - response_text = json.loads(response.text) - if response_text['error_message']: - generated_response["response"] = response_text['error_message'] - else: - generated_response["response"] = response.text - except Exception as e: - generated_response["response"] = response.text - except Exception as e: - generated_response["type"]= 'ERROR' - generated_response["response"] = response.text - return generated_response - -def extract_urls(text): - # Define the regex pattern for URLs - url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[/\w\.-]*' - - # Find all occurrences of URLs in the text - urls = re.findall(url_pattern, text) - - return urls - -def get_audio_reply_for_question(text): - generated_audio_event = get_generated_audio(text) - #From get_generated_audio, you will get events in a string format, from that we need to extract the url - final_response = { - "audio_url": '', - "message": '' - } - if generated_audio_event["type"] == 'SUCCESS': - audio_urls = extract_urls(generated_audio_event["response"]) - if len(audio_urls) == 0: - final_response['message'] = "No audio file link found in generated event" - else: - final_response['audio_url'] = audio_urls[-1] - else: - final_response['message'] = generated_audio_event['response'] - return final_response - -def download_url(url): - try: - # Send a GET request to the URL to fetch the content - final_response = { - 'content':'', - 'error':'' - } - response = requests.get(url) - # Check if the request was successful (status code 200) - if response.status_code == 200: - final_response['content'] = response.content - else: - final_response['error'] = f"Failed to download the URL. Status code: {response.status_code}" - except Exception as e: - final_response['error'] = f"Failed to download the URL. Error: {e}" - return final_response - -def get_filename_from_url(url): - # Use os.path.basename() to extract the file name from the URL - file_name = os.path.basename(url) - return file_name - -def get_text_response(user_message): - response = llm_chain.predict(user_message = user_message) - return response - -def get_text_response_and_audio_response(user_message): - response = get_text_response(user_message) # Getting the reply from Open AI - audio_reply_for_question_response = get_audio_reply_for_question(response) - final_response = { - 'output_file_path': '', - 'message':'' - } - audio_url = audio_reply_for_question_response['audio_url'] - if audio_url: - output_file_path=get_filename_from_url(audio_url) - download_url_response = download_url(audio_url) - audio_content = download_url_response['content'] - if audio_content: - with open(output_file_path, "wb") as audio_file: - audio_file.write(audio_content) - final_response['output_file_path'] = output_file_path - else: - final_response['message'] = download_url_response['error'] - else: - final_response['message'] = audio_reply_for_question_response['message'] - return final_response - -def chat_bot_response(message, history): - text_and_audio_response = get_text_response_and_audio_response(message) - output_file_path = text_and_audio_response['output_file_path'] - if output_file_path: - return (text_and_audio_response['output_file_path'],) - else: - return text_and_audio_response['message'] - -demo = gr.ChatInterface(chat_bot_response,examples=["How are you doing?","What are your interests?","Which places do you like to visit?"]) - -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/Neelanjan/MoodMelody/README.md b/spaces/Neelanjan/MoodMelody/README.md deleted file mode 100644 index fc88a2a9002b2029b09cd97afb7c97f5171f9cd3..0000000000000000000000000000000000000000 --- a/spaces/Neelanjan/MoodMelody/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: MoodMelody -emoji: 📊 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.34.0 -app_file: app.py -pinned: false -license: other ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Nekomaru180/rvc-model/vc_infer_pipeline.py b/spaces/Nekomaru180/rvc-model/vc_infer_pipeline.py deleted file mode 100644 index c26d45068f9b6bf2b194b13c3c89f8a06347c124..0000000000000000000000000000000000000000 --- a/spaces/Nekomaru180/rvc-model/vc_infer_pipeline.py +++ /dev/null @@ -1,306 +0,0 @@ -import numpy as np, parselmouth, torch, pdb -from time import time as ttime -import torch.nn.functional as F -from config import x_pad, x_query, x_center, x_max -import scipy.signal as signal -import pyworld, os, traceback, faiss -from scipy import signal - -bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000) - - -class VC(object): - def __init__(self, tgt_sr, device, is_half): - self.sr = 16000 # hubert输入采样率 - self.window = 160 # 每帧点数 - self.t_pad = self.sr * x_pad # 每条前后pad时间 - self.t_pad_tgt = tgt_sr * x_pad - self.t_pad2 = self.t_pad * 2 - self.t_query = self.sr * x_query # 查询切点前后查询时间 - self.t_center = self.sr * x_center # 查询切点位置 - self.t_max = self.sr * x_max # 免查询时长阈值 - self.device = device - self.is_half = is_half - - def get_f0(self, x, p_len, f0_up_key, f0_method, inp_f0=None): - time_step = self.window / self.sr * 1000 - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - if f0_method == "pm": - f0 = ( - parselmouth.Sound(x, self.sr) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=f0_min, - pitch_ceiling=f0_max, - ) - .selected_array["frequency"] - ) - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad( - f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant" - ) - elif f0_method == "harvest": - f0, t = pyworld.harvest( - x.astype(np.double), - fs=self.sr, - f0_ceil=f0_max, - f0_floor=f0_min, - frame_period=10, - ) - f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr) - f0 = signal.medfilt(f0, 3) - f0 *= pow(2, f0_up_key / 12) - # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - tf0 = self.sr // self.window # 每秒f0点数 - if inp_f0 is not None: - delta_t = np.round( - (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1 - ).astype("int16") - replace_f0 = np.interp( - list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1] - ) - shape = f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)].shape[0] - f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)] = replace_f0[:shape] - # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - f0bak = f0.copy() - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( - f0_mel_max - f0_mel_min - ) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - f0_coarse = np.rint(f0_mel).astype(np.int) - return f0_coarse, f0bak # 1-0 - - def vc( - self, - model, - net_g, - sid, - audio0, - pitch, - pitchf, - times, - index, - big_npy, - index_rate, - ): # ,file_index,file_big_npy - feats = torch.from_numpy(audio0) - if self.is_half: - feats = feats.half() - else: - feats = feats.float() - if feats.dim() == 2: # double channels - feats = feats.mean(-1) - assert feats.dim() == 1, feats.dim() - feats = feats.view(1, -1) - padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False) - - inputs = { - "source": feats.to(self.device), - "padding_mask": padding_mask, - "output_layer": 9, # layer 9 - } - t0 = ttime() - with torch.no_grad(): - logits = model.extract_features(**inputs) - feats = model.final_proj(logits[0]) - - if ( - isinstance(index, type(None)) == False - and isinstance(big_npy, type(None)) == False - and index_rate != 0 - ): - npy = feats[0].cpu().numpy() - if self.is_half: - npy = npy.astype("float32") - _, I = index.search(npy, 1) - npy = big_npy[I.squeeze()] - if self.is_half: - npy = npy.astype("float16") - feats = ( - torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate - + (1 - index_rate) * feats - ) - - feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1) - t1 = ttime() - p_len = audio0.shape[0] // self.window - if feats.shape[1] < p_len: - p_len = feats.shape[1] - if pitch != None and pitchf != None: - pitch = pitch[:, :p_len] - pitchf = pitchf[:, :p_len] - p_len = torch.tensor([p_len], device=self.device).long() - with torch.no_grad(): - if pitch != None and pitchf != None: - audio1 = ( - (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0] * 32768) - .data.cpu() - .float() - .numpy() - .astype(np.int16) - ) - else: - audio1 = ( - (net_g.infer(feats, p_len, sid)[0][0, 0] * 32768) - .data.cpu() - .float() - .numpy() - .astype(np.int16) - ) - del feats, p_len, padding_mask - if torch.cuda.is_available(): - torch.cuda.empty_cache() - t2 = ttime() - times[0] += t1 - t0 - times[2] += t2 - t1 - return audio1 - - def pipeline( - self, - model, - net_g, - sid, - audio, - times, - f0_up_key, - f0_method, - file_index, - file_big_npy, - index_rate, - if_f0, - f0_file=None, - ): - if ( - file_big_npy != "" - and file_index != "" - and os.path.exists(file_big_npy) == True - and os.path.exists(file_index) == True - and index_rate != 0 - ): - try: - index = faiss.read_index(file_index) - big_npy = np.load(file_big_npy) - except: - traceback.print_exc() - index = big_npy = None - else: - index = big_npy = None - print("Feature retrieval library doesn't exist or ratio is 0") - audio = signal.filtfilt(bh, ah, audio) - audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect") - opt_ts = [] - if audio_pad.shape[0] > self.t_max: - audio_sum = np.zeros_like(audio) - for i in range(self.window): - audio_sum += audio_pad[i : i - self.window] - for t in range(self.t_center, audio.shape[0], self.t_center): - opt_ts.append( - t - - self.t_query - + np.where( - np.abs(audio_sum[t - self.t_query : t + self.t_query]) - == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min() - )[0][0] - ) - s = 0 - audio_opt = [] - t = None - t1 = ttime() - audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect") - p_len = audio_pad.shape[0] // self.window - inp_f0 = None - if hasattr(f0_file, "name") == True: - try: - with open(f0_file.name, "r") as f: - lines = f.read().strip("\n").split("\n") - inp_f0 = [] - for line in lines: - inp_f0.append([float(i) for i in line.split(",")]) - inp_f0 = np.array(inp_f0, dtype="float32") - except: - traceback.print_exc() - sid = torch.tensor(sid, device=self.device).unsqueeze(0).long() - pitch, pitchf = None, None - if if_f0 == 1: - pitch, pitchf = self.get_f0(audio_pad, p_len, f0_up_key, f0_method, inp_f0) - pitch = pitch[:p_len] - pitchf = pitchf[:p_len] - pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long() - pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float() - t2 = ttime() - times[1] += t2 - t1 - for t in opt_ts: - t = t // self.window * self.window - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - pitch[:, s // self.window : (t + self.t_pad2) // self.window], - pitchf[:, s // self.window : (t + self.t_pad2) // self.window], - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - None, - None, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - s = t - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - pitch[:, t // self.window :] if t is not None else pitch, - pitchf[:, t // self.window :] if t is not None else pitchf, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - None, - None, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - audio_opt = np.concatenate(audio_opt) - del pitch, pitchf, sid - if torch.cuda.is_available(): - torch.cuda.empty_cache() - return audio_opt diff --git a/spaces/NeuralJunkie/HebLens/README.md b/spaces/NeuralJunkie/HebLens/README.md deleted file mode 100644 index cf39465d0818bf12fd1e9e71be682c5b0369e45d..0000000000000000000000000000000000000000 --- a/spaces/NeuralJunkie/HebLens/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: HebLens -emoji: 💻 -colorFrom: green -colorTo: purple -sdk: gradio -sdk_version: 3.29.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/Nithesh-101/Satellite_Image_Segmentation/README.md b/spaces/Nithesh-101/Satellite_Image_Segmentation/README.md deleted file mode 100644 index d7eaeca0513875fc701d8a21dbeedd17ac6aea3a..0000000000000000000000000000000000000000 --- a/spaces/Nithesh-101/Satellite_Image_Segmentation/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Satellite Image Segmentation -emoji: 📊 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.23.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/OFA-Sys/OFA-Image_Caption/fairseq/examples/translation/prepare-iwslt14.sh b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/translation/prepare-iwslt14.sh deleted file mode 100644 index 2fb6643fbccb58701dcbb77d91430e68a821ba38..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/translation/prepare-iwslt14.sh +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env bash -# -# Adapted from https://github.com/facebookresearch/MIXER/blob/master/prepareData.sh - -echo 'Cloning Moses github repository (for tokenization scripts)...' -git clone https://github.com/moses-smt/mosesdecoder.git - -echo 'Cloning Subword NMT repository (for BPE pre-processing)...' -git clone https://github.com/rsennrich/subword-nmt.git - -SCRIPTS=mosesdecoder/scripts -TOKENIZER=$SCRIPTS/tokenizer/tokenizer.perl -LC=$SCRIPTS/tokenizer/lowercase.perl -CLEAN=$SCRIPTS/training/clean-corpus-n.perl -BPEROOT=subword-nmt/subword_nmt -BPE_TOKENS=10000 - -URL="http://dl.fbaipublicfiles.com/fairseq/data/iwslt14/de-en.tgz" -GZ=de-en.tgz - -if [ ! -d "$SCRIPTS" ]; then - echo "Please set SCRIPTS variable correctly to point to Moses scripts." - exit -fi - -src=de -tgt=en -lang=de-en -prep=iwslt14.tokenized.de-en -tmp=$prep/tmp -orig=orig - -mkdir -p $orig $tmp $prep - -echo "Downloading data from ${URL}..." -cd $orig -wget "$URL" - -if [ -f $GZ ]; then - echo "Data successfully downloaded." -else - echo "Data not successfully downloaded." - exit -fi - -tar zxvf $GZ -cd .. - -echo "pre-processing train data..." -for l in $src $tgt; do - f=train.tags.$lang.$l - tok=train.tags.$lang.tok.$l - - cat $orig/$lang/$f | \ - grep -v '' | \ - grep -v '' | \ - grep -v '' | \ - sed -e 's///g' | \ - sed -e 's/<\/title>//g' | \ - sed -e 's/<description>//g' | \ - sed -e 's/<\/description>//g' | \ - perl $TOKENIZER -threads 8 -l $l > $tmp/$tok - echo "" -done -perl $CLEAN -ratio 1.5 $tmp/train.tags.$lang.tok $src $tgt $tmp/train.tags.$lang.clean 1 175 -for l in $src $tgt; do - perl $LC < $tmp/train.tags.$lang.clean.$l > $tmp/train.tags.$lang.$l -done - -echo "pre-processing valid/test data..." -for l in $src $tgt; do - for o in `ls $orig/$lang/IWSLT14.TED*.$l.xml`; do - fname=${o##*/} - f=$tmp/${fname%.*} - echo $o $f - grep '<seg id' $o | \ - sed -e 's/<seg id="[0-9]*">\s*//g' | \ - sed -e 's/\s*<\/seg>\s*//g' | \ - sed -e "s/\’/\'/g" | \ - perl $TOKENIZER -threads 8 -l $l | \ - perl $LC > $f - echo "" - done -done - - -echo "creating train, valid, test..." -for l in $src $tgt; do - awk '{if (NR%23 == 0) print $0; }' $tmp/train.tags.de-en.$l > $tmp/valid.$l - awk '{if (NR%23 != 0) print $0; }' $tmp/train.tags.de-en.$l > $tmp/train.$l - - cat $tmp/IWSLT14.TED.dev2010.de-en.$l \ - $tmp/IWSLT14.TEDX.dev2012.de-en.$l \ - $tmp/IWSLT14.TED.tst2010.de-en.$l \ - $tmp/IWSLT14.TED.tst2011.de-en.$l \ - $tmp/IWSLT14.TED.tst2012.de-en.$l \ - > $tmp/test.$l -done - -TRAIN=$tmp/train.en-de -BPE_CODE=$prep/code -rm -f $TRAIN -for l in $src $tgt; do - cat $tmp/train.$l >> $TRAIN -done - -echo "learn_bpe.py on ${TRAIN}..." -python $BPEROOT/learn_bpe.py -s $BPE_TOKENS < $TRAIN > $BPE_CODE - -for L in $src $tgt; do - for f in train.$L valid.$L test.$L; do - echo "apply_bpe.py to ${f}..." - python $BPEROOT/apply_bpe.py -c $BPE_CODE < $tmp/$f > $prep/$f - done -done diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/unsupervised_quality_estimation/aggregate_scores.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/unsupervised_quality_estimation/aggregate_scores.py deleted file mode 100644 index 66d50d07ff2067b802b90a2aadd88df23153830a..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/unsupervised_quality_estimation/aggregate_scores.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import argparse -import sys - -import numpy as np - - -aggregate_funcs = { - "std": np.std, - "var": np.var, - "median": np.median, - "mean": np.mean, - "min": np.min, - "max": np.max, -} - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("-i", "--input_file", required=True, type=str) - parser.add_argument("-n", "--repeat_times", required=True, type=int) - parser.add_argument("-o", "--output_file", required=False) - parser.add_argument("-f", "--func", required=False, default="mean") - args = parser.parse_args() - - stream = open(args.output_file, "w") if args.output_file else sys.stdout - - segment_scores = [] - for line in open(args.input_file): - segment_scores.append(float(line.strip())) - if len(segment_scores) == args.repeat_times: - stream.write("{}\n".format(aggregate_funcs[args.func](segment_scores))) - segment_scores = [] - - -if __name__ == "__main__": - main() diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/models/__init__.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/models/__init__.py deleted file mode 100644 index 3e3039b7081a9e3228c8abefb6391a75b4864439..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/models/__init__.py +++ /dev/null @@ -1,11 +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 .wav2vec_u import Wav2vec_U - - -__all__ = [ - "Wav2vec_U", -] diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/indexed_dataset.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/indexed_dataset.py deleted file mode 100644 index a2a6ae1ac01b56d4e3c9b4516bdfe09c114324b6..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/indexed_dataset.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 shutil -import struct -from functools import lru_cache - -import numpy as np -import torch -from fairseq.dataclass.constants import DATASET_IMPL_CHOICES -from fairseq.data.fasta_dataset import FastaDataset -from fairseq.file_io import PathManager -from fairseq.data.huffman import HuffmanMMapIndexedDataset, HuffmanMMapIndex - -from . import FairseqDataset - -from typing import Union - - -def best_fitting_int_dtype( - max_int_to_represent, -) -> Union[np.uint16, np.uint32, np.int64]: - - if max_int_to_represent is None: - return np.uint32 # Safe guess - elif max_int_to_represent < 65500: - return np.uint16 - elif max_int_to_represent < 4294967295: - return np.uint32 - else: - return np.int64 - # we avoid np.uint64 because it doesn't save space and its type promotion behaves unexpectedly - # https://github.com/numpy/numpy/issues/5745 - - -def get_available_dataset_impl(): - return list(map(str, DATASET_IMPL_CHOICES)) - - -def infer_dataset_impl(path): - if IndexedRawTextDataset.exists(path): - return "raw" - elif IndexedDataset.exists(path): - with open(index_file_path(path), "rb") as f: - magic = f.read(8) - if magic == IndexedDataset._HDR_MAGIC: - return "cached" - elif magic == MMapIndexedDataset.Index._HDR_MAGIC[:8]: - return "mmap" - elif magic == HuffmanMMapIndex._HDR_MAGIC[:8]: - return "huffman" - else: - return None - elif FastaDataset.exists(path): - return "fasta" - else: - return None - - -def make_builder(out_file, impl, vocab_size=None): - if impl == "mmap": - return MMapIndexedDatasetBuilder( - out_file, dtype=best_fitting_int_dtype(vocab_size) - ) - elif impl == "fasta": - raise NotImplementedError - elif impl == "huffman": - raise ValueError("Use HuffmanCodeBuilder directly as it has a different interface.") - else: - return IndexedDatasetBuilder(out_file) - - -def make_dataset(path, impl, fix_lua_indexing=False, dictionary=None): - if impl == "raw" and IndexedRawTextDataset.exists(path): - assert dictionary is not None - return IndexedRawTextDataset(path, dictionary) - elif impl == "lazy" and IndexedDataset.exists(path): - return IndexedDataset(path, fix_lua_indexing=fix_lua_indexing) - elif impl == "cached" and IndexedDataset.exists(path): - return IndexedCachedDataset(path, fix_lua_indexing=fix_lua_indexing) - elif impl == "mmap" and MMapIndexedDataset.exists(path): - return MMapIndexedDataset(path) - elif impl == "fasta" and FastaDataset.exists(path): - from fairseq.data.fasta_dataset import EncodedFastaDataset - - return EncodedFastaDataset(path, dictionary) - elif impl == "huffman" and HuffmanMMapIndexedDataset.exists(path): - return HuffmanMMapIndexedDataset(path) - return None - - -def dataset_exists(path, impl): - if impl == "raw": - return IndexedRawTextDataset.exists(path) - elif impl == "mmap": - return MMapIndexedDataset.exists(path) - elif impl == "huffman": - return HuffmanMMapIndexedDataset.exists(path) - else: - return IndexedDataset.exists(path) - - -def read_longs(f, n): - a = np.empty(n, dtype=np.int64) - f.readinto(a) - return a - - -def write_longs(f, a): - f.write(np.array(a, dtype=np.int64)) - - -_code_to_dtype = { - 1: np.uint8, - 2: np.int8, - 3: np.int16, - 4: np.int32, - 5: np.int64, - 6: np.float64, - 7: np.double, - 8: np.uint16, - 9: np.uint32, - 10: np.uint64, -} - - -def _dtype_header_code(dtype) -> int: - for k in _code_to_dtype.keys(): - if _code_to_dtype[k] == dtype: - return k - raise ValueError(dtype) - - -def index_file_path(prefix_path): - return prefix_path + ".idx" - - -def data_file_path(prefix_path): - return prefix_path + ".bin" - - -class IndexedDataset(FairseqDataset): - """Loader for TorchNet IndexedDataset""" - - _HDR_MAGIC = b"TNTIDX\x00\x00" - - def __init__(self, path, fix_lua_indexing=False): - super().__init__() - self.path = path - self.fix_lua_indexing = fix_lua_indexing - self.data_file = None - self.read_index(path) - - def read_index(self, path): - with open(index_file_path(path), "rb") as f: - magic = f.read(8) - assert magic == self._HDR_MAGIC, ( - "Index file doesn't match expected format. " - "Make sure that --dataset-impl is configured properly." - ) - version = f.read(8) - assert struct.unpack("<Q", version) == (1,) - code, self.element_size = struct.unpack("<QQ", f.read(16)) - self.dtype = _code_to_dtype[code] - self._len, self.s = struct.unpack("<QQ", f.read(16)) - self.dim_offsets = read_longs(f, self._len + 1) - self.data_offsets = read_longs(f, self._len + 1) - self.sizes = read_longs(f, self.s) - - def read_data(self, path): - self.data_file = open(data_file_path(path), "rb", buffering=0) - - def check_index(self, i): - if i < 0 or i >= self._len: - raise IndexError("index out of range") - - def __del__(self): - if self.data_file: - self.data_file.close() - - @lru_cache(maxsize=8) - def __getitem__(self, i) -> torch.Tensor: - if not self.data_file: - self.read_data(self.path) - self.check_index(i) - tensor_size = self.sizes[self.dim_offsets[i] : self.dim_offsets[i + 1]] - a = np.empty(tensor_size, dtype=self.dtype) - self.data_file.seek(self.data_offsets[i] * self.element_size) - self.data_file.readinto(a) - item = torch.from_numpy(a).long() - if self.fix_lua_indexing: - item -= 1 # subtract 1 for 0-based indexing - return item - - def __len__(self): - return self._len - - def num_tokens(self, index): - return self.sizes[index] - - def size(self, index): - return self.sizes[index] - - @staticmethod - def exists(path): - return PathManager.exists(index_file_path(path)) and PathManager.exists( - data_file_path(path) - ) - - @property - def supports_prefetch(self): - return False # avoid prefetching to save memory - - -class IndexedCachedDataset(IndexedDataset): - def __init__(self, path, fix_lua_indexing=False): - super().__init__(path, fix_lua_indexing=fix_lua_indexing) - self.cache = None - self.cache_index = {} - - @property - def supports_prefetch(self): - return True - - def prefetch(self, indices): - if all(i in self.cache_index for i in indices): - return - if not self.data_file: - self.read_data(self.path) - indices = sorted(set(indices)) - total_size = 0 - for i in indices: - total_size += self.data_offsets[i + 1] - self.data_offsets[i] - self.cache = np.empty(total_size, dtype=self.dtype) - ptx = 0 - self.cache_index.clear() - for i in indices: - self.cache_index[i] = ptx - size = self.data_offsets[i + 1] - self.data_offsets[i] - a = self.cache[ptx : ptx + size] - self.data_file.seek(self.data_offsets[i] * self.element_size) - self.data_file.readinto(a) - ptx += size - if self.data_file: - # close and delete data file after prefetch so we can pickle - self.data_file.close() - self.data_file = None - - @lru_cache(maxsize=8) - def __getitem__(self, i): - self.check_index(i) - tensor_size = self.sizes[self.dim_offsets[i] : self.dim_offsets[i + 1]] - a = np.empty(tensor_size, dtype=self.dtype) - ptx = self.cache_index[i] - np.copyto(a, self.cache[ptx : ptx + a.size]) - item = torch.from_numpy(a).long() - if self.fix_lua_indexing: - item -= 1 # subtract 1 for 0-based indexing - return item - - -class IndexedRawTextDataset(FairseqDataset): - """Takes a text file as input and binarizes it in memory at instantiation. - Original lines are also kept in memory""" - - def __init__(self, path, dictionary, append_eos=True, reverse_order=False): - self.tokens_list = [] - self.lines = [] - self.sizes = [] - self.append_eos = append_eos - self.reverse_order = reverse_order - self.read_data(path, dictionary) - self.size = len(self.tokens_list) - - def read_data(self, path, dictionary): - with open(path, "r", encoding="utf-8") as f: - for line in f: - self.lines.append(line.strip("\n")) - tokens = dictionary.encode_line( - line, - add_if_not_exist=False, - append_eos=self.append_eos, - reverse_order=self.reverse_order, - ).long() - self.tokens_list.append(tokens) - self.sizes.append(len(tokens)) - self.sizes = np.array(self.sizes) - - def check_index(self, i): - if i < 0 or i >= self.size: - raise IndexError("index out of range") - - @lru_cache(maxsize=8) - def __getitem__(self, i): - self.check_index(i) - return self.tokens_list[i] - - def get_original_text(self, i): - self.check_index(i) - return self.lines[i] - - def __del__(self): - pass - - def __len__(self): - return self.size - - def num_tokens(self, index): - return self.sizes[index] - - def size(self, index): - return self.sizes[index] - - @staticmethod - def exists(path): - return PathManager.exists(path) - - -class IndexedDatasetBuilder: - element_sizes = { - np.uint8: 1, - np.int8: 1, - np.int16: 2, - np.int32: 4, - np.int64: 8, - np.float64: 4, - np.double: 8, - } - - def __init__(self, out_file, dtype=np.int32): - self.out_file = open(out_file, "wb") - self.dtype = dtype - self.data_offsets = [0] - self.dim_offsets = [0] - self.sizes = [] - self.element_size = self.element_sizes[self.dtype] - - def add_item(self, tensor): - # +1 for Lua compatibility - bytes = self.out_file.write(np.array(tensor.numpy() + 1, dtype=self.dtype)) - self.data_offsets.append(self.data_offsets[-1] + bytes / self.element_size) - for s in tensor.size(): - self.sizes.append(s) - self.dim_offsets.append(self.dim_offsets[-1] + len(tensor.size())) - - def merge_file_(self, another_file): - index = IndexedDataset(another_file) - assert index.dtype == self.dtype - - begin = self.data_offsets[-1] - for offset in index.data_offsets[1:]: - self.data_offsets.append(begin + offset) - self.sizes.extend(index.sizes) - begin = self.dim_offsets[-1] - for dim_offset in index.dim_offsets[1:]: - self.dim_offsets.append(begin + dim_offset) - - with open(data_file_path(another_file), "rb") as f: - while True: - data = f.read(1024) - if data: - self.out_file.write(data) - else: - break - - def finalize(self, index_file): - self.out_file.close() - index = open(index_file, "wb") - index.write(b"TNTIDX\x00\x00") - index.write(struct.pack("<Q", 1)) - index.write( - struct.pack("<QQ", _dtype_header_code(self.dtype), self.element_size) - ) - index.write(struct.pack("<QQ", len(self.data_offsets) - 1, len(self.sizes))) - write_longs(index, self.dim_offsets) - write_longs(index, self.data_offsets) - write_longs(index, self.sizes) - index.close() - - -def _warmup_mmap_file(path): - with open(path, "rb") as stream: - while stream.read(100 * 1024 * 1024): - pass - - -class MMapIndexedDataset(torch.utils.data.Dataset): - class Index: - _HDR_MAGIC = b"MMIDIDX\x00\x00" - - @classmethod - def writer(cls, path, dtype): - class _Writer: - def __enter__(self): - self._file = open(path, "wb") - - self._file.write(cls._HDR_MAGIC) - self._file.write(struct.pack("<Q", 1)) - self._file.write(struct.pack("<B", _dtype_header_code(dtype))) - - return self - - @staticmethod - def _get_pointers(sizes): - dtype_size = dtype().itemsize - address = 0 - pointers = [] - - for size in sizes: - pointers.append(address) - address += size * dtype_size - - return pointers - - def write(self, sizes): - pointers = self._get_pointers(sizes) - - self._file.write(struct.pack("<Q", len(sizes))) - - sizes = np.array(sizes, dtype=np.int32) - self._file.write(sizes.tobytes(order="C")) - del sizes - - pointers = np.array(pointers, dtype=np.int64) - self._file.write(pointers.tobytes(order="C")) - del pointers - - def __exit__(self, exc_type, exc_val, exc_tb): - self._file.close() - - return _Writer() - - def __init__(self, path): - with open(path, "rb") as stream: - magic_test = stream.read(9) - assert self._HDR_MAGIC == magic_test, ( - "Index file doesn't match expected format. " - "Make sure that --dataset-impl is configured properly." - ) - version = struct.unpack("<Q", stream.read(8)) - assert (1,) == version - - (dtype_code,) = struct.unpack("<B", stream.read(1)) - self._dtype = _code_to_dtype[dtype_code] - self._dtype_size = self._dtype().itemsize - - self._len = struct.unpack("<Q", stream.read(8))[0] - offset = stream.tell() - - _warmup_mmap_file(path) - - self._bin_buffer_mmap = np.memmap(path, mode="r", order="C") - self._bin_buffer = memoryview(self._bin_buffer_mmap) - self._sizes = np.frombuffer( - self._bin_buffer, dtype=np.int32, count=self._len, offset=offset - ) - self._pointers = np.frombuffer( - self._bin_buffer, - dtype=np.int64, - count=self._len, - offset=offset + self._sizes.nbytes, - ) - - def __del__(self): - self._bin_buffer_mmap._mmap.close() - del self._bin_buffer_mmap - - @property - def dtype(self): - return self._dtype - - @property - def sizes(self): - return self._sizes - - @lru_cache(maxsize=8) - def __getitem__(self, i): - return self._pointers[i], self._sizes[i] - - def __len__(self): - return self._len - - def __init__(self, path): - super().__init__() - - self._path = None - self._index = None - self._bin_buffer = None - - self._do_init(path) - - def __getstate__(self): - return self._path - - def __setstate__(self, state): - self._do_init(state) - - def _do_init(self, path): - self._path = path - self._index = self.Index(index_file_path(self._path)) - - _warmup_mmap_file(data_file_path(self._path)) - self._bin_buffer_mmap = np.memmap( - data_file_path(self._path), mode="r", order="C" - ) - self._bin_buffer = memoryview(self._bin_buffer_mmap) - - def __del__(self): - self._bin_buffer_mmap._mmap.close() - del self._bin_buffer_mmap - del self._index - - def __len__(self): - return len(self._index) - - @lru_cache(maxsize=8) - def __getitem__(self, i): - ptr, size = self._index[i] - np_array = np.frombuffer( - self._bin_buffer, dtype=self._index.dtype, count=size, offset=ptr - ) - if self._index.dtype != np.int64: - np_array = np_array.astype(np.int64) - - return torch.from_numpy(np_array) - - @property - def sizes(self): - return self._index.sizes - - @property - def supports_prefetch(self): - return False - - @staticmethod - def exists(path): - return PathManager.exists(index_file_path(path)) and PathManager.exists( - data_file_path(path) - ) - - -def get_indexed_dataset_to_local(path) -> str: - local_index_path = PathManager.get_local_path(index_file_path(path)) - local_data_path = PathManager.get_local_path(data_file_path(path)) - - assert local_index_path.endswith(".idx") and local_data_path.endswith(".bin"), ( - "PathManager.get_local_path does not return files with expected patterns: " - f"{local_index_path} and {local_data_path}" - ) - - local_path = local_data_path[:-4] # stripping surfix ".bin" - assert local_path == local_index_path[:-4] # stripping surfix ".idx" - return local_path - - -class MMapIndexedDatasetBuilder: - def __init__(self, out_file, dtype=np.int64): - self._data_file = open(out_file, "wb") - self._dtype = dtype - self._sizes = [] - - def add_item(self, tensor): - np_array = np.array(tensor.numpy(), dtype=self._dtype) - self._data_file.write(np_array.tobytes(order="C")) - self._sizes.append(np_array.size) - - def merge_file_(self, another_file): - # Concatenate index - index = MMapIndexedDataset.Index(index_file_path(another_file)) - assert index.dtype == self._dtype - - for size in index.sizes: - self._sizes.append(size) - - # Concatenate data - with open(data_file_path(another_file), "rb") as f: - shutil.copyfileobj(f, self._data_file) - - def finalize(self, index_file): - self._data_file.close() - - with MMapIndexedDataset.Index.writer(index_file, self._dtype) as index: - index.write(self._sizes) diff --git a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/.github/ISSUE_TEMPLATE.md b/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 5c4c4493e4a8e5386b927e4f4554df925955d129..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,3 +0,0 @@ -## 👉 [Please follow one of these issue templates](https://github.com/pytorch/fairseq/issues/new/choose) 👈 - -Note: to keep the backlog clean and actionable, issues may be immediately closed if they do not follow one of the above issue templates. diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_recognition/data/data_utils.py b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_recognition/data/data_utils.py deleted file mode 100644 index cc4729e63c8ef551b29617d1169a44c24f509ad0..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_recognition/data/data_utils.py +++ /dev/null @@ -1,100 +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 - - -def calc_mean_invstddev(feature): - if len(feature.size()) != 2: - raise ValueError("We expect the input feature to be 2-D tensor") - mean = feature.mean(0) - var = feature.var(0) - # avoid division by ~zero - eps = 1e-8 - if (var < eps).any(): - return mean, 1.0 / (torch.sqrt(var) + eps) - return mean, 1.0 / torch.sqrt(var) - - -def apply_mv_norm(features): - # If there is less than 2 spectrograms, the variance cannot be computed (is NaN) - # and normalization is not possible, so return the item as it is - if features.size(0) < 2: - return features - mean, invstddev = calc_mean_invstddev(features) - res = (features - mean) * invstddev - return res - - -def lengths_to_encoder_padding_mask(lengths, batch_first=False): - """ - convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor - - Args: - lengths: a (B, )-shaped tensor - - Return: - max_length: maximum length of B sequences - encoder_padding_mask: a (max_length, B) binary mask, where - [t, b] = 0 for t < lengths[b] and 1 otherwise - - TODO: - kernelize this function if benchmarking shows this function is slow - """ - max_lengths = torch.max(lengths).item() - bsz = lengths.size(0) - encoder_padding_mask = torch.arange( - max_lengths - ).to( # a (T, ) tensor with [0, ..., T-1] - lengths.device - ).view( # move to the right device - 1, max_lengths - ).expand( # reshape to (1, T)-shaped tensor - bsz, -1 - ) >= lengths.view( # expand to (B, T)-shaped tensor - bsz, 1 - ).expand( - -1, max_lengths - ) - if not batch_first: - return encoder_padding_mask.t(), max_lengths - else: - return encoder_padding_mask, max_lengths - - -def encoder_padding_mask_to_lengths( - encoder_padding_mask, max_lengths, batch_size, device -): - """ - convert encoder_padding_mask (2-D binary tensor) to a 1-D tensor - - Conventionally, encoder output contains a encoder_padding_mask, which is - a 2-D mask in a shape (T, B), whose (t, b) element indicate whether - encoder_out[t, b] is a valid output (=0) or not (=1). Occasionally, we - need to convert this mask tensor to a 1-D tensor in shape (B, ), where - [b] denotes the valid length of b-th sequence - - Args: - encoder_padding_mask: a (T, B)-shaped binary tensor or None; if None, - indicating all are valid - Return: - seq_lengths: a (B,)-shaped tensor, where its (b, )-th element is the - number of valid elements of b-th sequence - - max_lengths: maximum length of all sequence, if encoder_padding_mask is - not None, max_lengths must equal to encoder_padding_mask.size(0) - - batch_size: batch size; if encoder_padding_mask is - not None, max_lengths must equal to encoder_padding_mask.size(1) - - device: which device to put the result on - """ - if encoder_padding_mask is None: - return torch.Tensor([max_lengths] * batch_size).to(torch.int32).to(device) - - assert encoder_padding_mask.size(0) == max_lengths, "max_lengths does not match" - assert encoder_padding_mask.size(1) == batch_size, "batch_size does not match" - - return max_lengths - torch.sum(encoder_padding_mask, dim=0) diff --git a/spaces/OmegaYuti/anything-v3.0/app.py b/spaces/OmegaYuti/anything-v3.0/app.py deleted file mode 100644 index 62c8768d6f448b1a0387eaa5d551f3743ebd9462..0000000000000000000000000000000000000000 --- a/spaces/OmegaYuti/anything-v3.0/app.py +++ /dev/null @@ -1,276 +0,0 @@ -from diffusers import AutoencoderKL, UNet2DConditionModel, StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler -import gradio as gr -import torch -from PIL import Image -import utils -import datetime -import time -import psutil - -start_time = time.time() -is_colab = utils.is_google_colab() - -class Model: - def __init__(self, name, path="", prefix=""): - self.name = name - self.path = path - self.prefix = prefix - self.pipe_t2i = None - self.pipe_i2i = None - -models = [ - Model("anything v3", "Linaqruf/anything-v3.0", "anything v3 style"), - ] - # Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "), - # Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "), - # Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "), - # Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy ") - #Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", ""), - #Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", ""), - #Model("Robo Diffusion", "nousr/robo-diffusion", ""), - -scheduler = DPMSolverMultistepScheduler( - beta_start=0.00085, - beta_end=0.012, - beta_schedule="scaled_linear", - num_train_timesteps=1000, - trained_betas=None, - predict_epsilon=True, - thresholding=False, - algorithm_type="dpmsolver++", - solver_type="midpoint", - lower_order_final=True, -) - -custom_model = None -if is_colab: - models.insert(0, Model("Custom model")) - custom_model = models[0] - -last_mode = "txt2img" -current_model = models[1] if is_colab else models[0] -current_model_path = current_model.path - -if is_colab: - pipe = StableDiffusionPipeline.from_pretrained(current_model.path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False)) - -else: # download all models - print(f"{datetime.datetime.now()} Downloading vae...") - vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae", torch_dtype=torch.float16) - for model in models: - try: - print(f"{datetime.datetime.now()} Downloading {model.name} model...") - unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet", torch_dtype=torch.float16) - model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler) - model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler) - except Exception as e: - print(f"{datetime.datetime.now()} Failed to load model " + model.name + ": " + str(e)) - models.remove(model) - pipe = models[0].pipe_t2i - -if torch.cuda.is_available(): - pipe = pipe.to("cuda") - -device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶" - -def error_str(error, title="Error"): - return f"""#### {title} - {error}""" if error else "" - -def custom_model_changed(path): - models[0].path = path - global current_model - current_model = models[0] - -def on_model_change(model_name): - - prefix = "Enter prompt. \"" + next((m.prefix for m in models if m.name == model_name), None) + "\" is prefixed automatically" if model_name != models[0].name else "Don't forget to use the custom model prefix in the prompt!" - - return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix) - -def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""): - - print(psutil.virtual_memory()) # print memory usage - - global current_model - for model in models: - if model.name == model_name: - current_model = model - model_path = current_model.path - - generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None - - try: - if img is not None: - return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None - else: - return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator), None - except Exception as e: - return None, error_str(e) - -def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator): - - print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}") - - global last_mode - global pipe - global current_model_path - if model_path != current_model_path or last_mode != "txt2img": - current_model_path = model_path - - if is_colab or current_model == custom_model: - pipe = StableDiffusionPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False)) - else: - pipe = pipe.to("cpu") - pipe = current_model.pipe_t2i - - if torch.cuda.is_available(): - pipe = pipe.to("cuda") - last_mode = "txt2img" - - prompt = current_model.prefix + prompt - result = pipe( - prompt, - negative_prompt = neg_prompt, - # num_images_per_prompt=n_images, - num_inference_steps = int(steps), - guidance_scale = guidance, - width = width, - height = height, - generator = generator) - - return replace_nsfw_images(result) - -def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator): - - print(f"{datetime.datetime.now()} img_to_img, model: {model_path}") - - global last_mode - global pipe - global current_model_path - if model_path != current_model_path or last_mode != "img2img": - current_model_path = model_path - - if is_colab or current_model == custom_model: - pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False)) - else: - pipe = pipe.to("cpu") - pipe = current_model.pipe_i2i - - if torch.cuda.is_available(): - pipe = pipe.to("cuda") - last_mode = "img2img" - - prompt = current_model.prefix + prompt - ratio = min(height / img.height, width / img.width) - img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS) - result = pipe( - prompt, - negative_prompt = neg_prompt, - # num_images_per_prompt=n_images, - init_image = img, - num_inference_steps = int(steps), - strength = strength, - guidance_scale = guidance, - width = width, - height = height, - generator = generator) - - return replace_nsfw_images(result) - -def replace_nsfw_images(results): - - if is_colab: - return results.images[0] - - for i in range(len(results.images)): - if results.nsfw_content_detected[i]: - results.images[i] = Image.open("nsfw.png") - return results.images[0] - -css = """.finetuned-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.finetuned-diffusion-div div h1{font-weight:900;margin-bottom:7px}.finetuned-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem} -""" -with gr.Blocks(css=css) as demo: - gr.HTML( - f""" - <div class="finetuned-diffusion-div"> - <div> - <h1>Anything V3</h1> - </div> - <p> - Demo for Anything V3 - </p> - <p>You can skip the queue by duplicating this space: <a style="display:inline-block" href="https://huggingface.co/spaces/akhaliq/anything-v3.0?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a> </p> - </p> - </div> - """ - ) - with gr.Row(): - - with gr.Column(scale=55): - with gr.Group(): - model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name) - with gr.Box(visible=False) as custom_model_group: - custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True) - gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>") - - with gr.Row(): - prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False) - generate = gr.Button(value="Generate").style(rounded=(False, True, True, False)) - - - image_out = gr.Image(height=512) - # gallery = gr.Gallery( - # label="Generated images", show_label=False, elem_id="gallery" - # ).style(grid=[1], height="auto") - error_output = gr.Markdown() - - with gr.Column(scale=45): - with gr.Tab("Options"): - with gr.Group(): - neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image") - - # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1) - - with gr.Row(): - guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15) - steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1) - - with gr.Row(): - width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8) - height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8) - - seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1) - - with gr.Tab("Image to image"): - with gr.Group(): - image = gr.Image(label="Image", height=256, tool="editor", type="pil") - strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5) - - if is_colab: - model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False) - custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None) - # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery) - - inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt] - outputs = [image_out, error_output] - prompt.submit(inference, inputs=inputs, outputs=outputs) - generate.click(inference, inputs=inputs, outputs=outputs) - - ex = gr.Examples([ - [models[0].name, "iron man", 7.5, 50], - - ], inputs=[model_name, prompt, guidance, steps, seed], outputs=outputs, fn=inference, cache_examples=False) - - gr.HTML(""" - <div style="border-top: 1px solid #303030;"> - <br> - <p>Model by Linaqruf</p> - </div> - """) - -print(f"Space built in {time.time() - start_time:.2f} seconds") - -if not is_colab: - demo.queue(concurrency_count=1) -demo.launch(debug=is_colab, share=is_colab) \ No newline at end of file diff --git a/spaces/Omnibus/game-test/my-game.html b/spaces/Omnibus/game-test/my-game.html deleted file mode 100644 index 35c992f2a3565be445cb42635ae1fae43ba45f96..0000000000000000000000000000000000000000 --- a/spaces/Omnibus/game-test/my-game.html +++ /dev/null @@ -1,171 +0,0 @@ -<!doctype html> -<html lang="en"> -<head> - <meta charset="UTF-8" /> - <title>Game Test - - - - - - -
      - -
      - - \ No newline at end of file diff --git a/spaces/OpenDILabCommunity/LLMRiddlesChatGPTCN/llmriddles/llms/llm_server.py b/spaces/OpenDILabCommunity/LLMRiddlesChatGPTCN/llmriddles/llms/llm_server.py deleted file mode 100644 index ddf7a21f27eac955e831e5e596d0066a2333b248..0000000000000000000000000000000000000000 --- a/spaces/OpenDILabCommunity/LLMRiddlesChatGPTCN/llmriddles/llms/llm_server.py +++ /dev/null @@ -1,72 +0,0 @@ -from transformers import AutoModelForCausalLM, AutoTokenizer -from flask import Flask, request -import argparse -import logging - - -class LLMInstance: - - def __init__(self, model_path: str, device: str = "cuda"): - - self.model = AutoModelForCausalLM.from_pretrained(model_path) - self.tokenizer = AutoTokenizer.from_pretrained(model_path) - self.model.to(device) - self.device = device - - def query(self, message): - try: - messages = [ - {"role": "user", "content": message}, - ] - encodeds = self.tokenizer.apply_chat_template(messages, return_tensors="pt") - model_inputs = encodeds.to(self.device) - - generated_ids = self.model.generate(model_inputs, max_new_tokens=1000, do_sample=True) - decoded = self.tokenizer.batch_decode(generated_ids) - - # output is the string decoded[0] after "[/INST]". There may exist "", delete it. - output = decoded[0].split("[/INST]")[1].split("")[0] - return { - 'code': 0, - 'ret': True, - 'error_msg': None, - 'output': output - } - except Exception as e: - return { - 'code': 1, - 'ret': False, - 'error_msg': str(e), - 'output': None - } - - -def create_app(core): - app = Flask(__name__) - - @app.route('/ask_llm_for_answer', methods=['POST']) - def ask_llm_for_answer(): - user_text = request.json['user_text'] - return core.query(user_text) - - return app - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument('-m', '--model_path', required=True, default='Mistral-7B-Instruct-v0.1', help='the model path of reward model') - parser.add_argument('--ip', default='0.0.0.0') - parser.add_argument('-p', '--port', default=8001) - parser.add_argument('--debug', action='store_true') - args = parser.parse_args() - - if args.debug: - logging.getLogger().setLevel(logging.DEBUG) - else: - logging.getLogger().setLevel(logging.INFO) - logging.getLogger().addHandler(logging.StreamHandler()) - logging.getLogger().handlers[0].setFormatter(logging.Formatter("%(message)s")) - - core = LLMInstance(args.model_path) - app = create_app(core) - app.run(host=args.ip, port=args.port) diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/detectron2/layers/mask_ops.py b/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/detectron2/layers/mask_ops.py deleted file mode 100644 index e7a9f3a323ddbe75845b668ee6b40c5385d206c3..0000000000000000000000000000000000000000 --- a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/detectron2/layers/mask_ops.py +++ /dev/null @@ -1,275 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import numpy as np -from typing import Tuple -import torch -from PIL import Image -from torch.nn import functional as F - -__all__ = ["paste_masks_in_image"] - - -BYTES_PER_FLOAT = 4 -# TODO: This memory limit may be too much or too little. It would be better to -# determine it based on available resources. -GPU_MEM_LIMIT = 1024 ** 3 # 1 GB memory limit - - -def _do_paste_mask(masks, boxes, img_h: int, img_w: int, skip_empty: bool = True): - """ - Args: - masks: N, 1, H, W - boxes: N, 4 - img_h, img_w (int): - skip_empty (bool): only paste masks within the region that - tightly bound all boxes, and returns the results this region only. - An important optimization for CPU. - - Returns: - if skip_empty == False, a mask of shape (N, img_h, img_w) - if skip_empty == True, a mask of shape (N, h', w'), and the slice - object for the corresponding region. - """ - # On GPU, paste all masks together (up to chunk size) - # by using the entire image to sample the masks - # Compared to pasting them one by one, - # this has more operations but is faster on COCO-scale dataset. - device = masks.device - - if skip_empty and not torch.jit.is_scripting(): - x0_int, y0_int = torch.clamp(boxes.min(dim=0).values.floor()[:2] - 1, min=0).to( - dtype=torch.int32 - ) - x1_int = torch.clamp(boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) - y1_int = torch.clamp(boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) - else: - x0_int, y0_int = 0, 0 - x1_int, y1_int = img_w, img_h - x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1 - - N = masks.shape[0] - - img_y = torch.arange(y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 - img_x = torch.arange(x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 - img_y = (img_y - y0) / (y1 - y0) * 2 - 1 - img_x = (img_x - x0) / (x1 - x0) * 2 - 1 - # img_x, img_y have shapes (N, w), (N, h) - - gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) - gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) - grid = torch.stack([gx, gy], dim=3) - - if not torch.jit.is_scripting(): - if not masks.dtype.is_floating_point: - masks = masks.float() - img_masks = F.grid_sample(masks, grid.to(masks.dtype), align_corners=False) - - if skip_empty and not torch.jit.is_scripting(): - return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) - else: - return img_masks[:, 0], () - - -# Annotate boxes as Tensor (but not Boxes) in order to use scripting -@torch.jit.script_if_tracing -def paste_masks_in_image( - masks: torch.Tensor, boxes: torch.Tensor, image_shape: Tuple[int, int], threshold: float = 0.5 -): - """ - Paste a set of masks that are of a fixed resolution (e.g., 28 x 28) into an image. - The location, height, and width for pasting each mask is determined by their - corresponding bounding boxes in boxes. - - Note: - This is a complicated but more accurate implementation. In actual deployment, it is - often enough to use a faster but less accurate implementation. - See :func:`paste_mask_in_image_old` in this file for an alternative implementation. - - Args: - masks (tensor): Tensor of shape (Bimg, Hmask, Wmask), where Bimg is the number of - detected object instances in the image and Hmask, Wmask are the mask width and mask - height of the predicted mask (e.g., Hmask = Wmask = 28). Values are in [0, 1]. - boxes (Boxes or Tensor): A Boxes of length Bimg or Tensor of shape (Bimg, 4). - boxes[i] and masks[i] correspond to the same object instance. - image_shape (tuple): height, width - threshold (float): A threshold in [0, 1] for converting the (soft) masks to - binary masks. - - Returns: - img_masks (Tensor): A tensor of shape (Bimg, Himage, Wimage), where Bimg is the - number of detected object instances and Himage, Wimage are the image width - and height. img_masks[i] is a binary mask for object instance i. - """ - - assert masks.shape[-1] == masks.shape[-2], "Only square mask predictions are supported" - N = len(masks) - if N == 0: - return masks.new_empty((0,) + image_shape, dtype=torch.uint8) - if not isinstance(boxes, torch.Tensor): - boxes = boxes.tensor - device = boxes.device - assert len(boxes) == N, boxes.shape - - img_h, img_w = image_shape - - # The actual implementation split the input into chunks, - # and paste them chunk by chunk. - if device.type == "cpu" or torch.jit.is_scripting(): - # CPU is most efficient when they are pasted one by one with skip_empty=True - # so that it performs minimal number of operations. - num_chunks = N - else: - # GPU benefits from parallelism for larger chunks, but may have memory issue - # int(img_h) because shape may be tensors in tracing - num_chunks = int(np.ceil(N * int(img_h) * int(img_w) * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) - assert ( - num_chunks <= N - ), "Default GPU_MEM_LIMIT in mask_ops.py is too small; try increasing it" - chunks = torch.chunk(torch.arange(N, device=device), num_chunks) - - img_masks = torch.zeros( - N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8 - ) - for inds in chunks: - masks_chunk, spatial_inds = _do_paste_mask( - masks[inds, None, :, :], boxes[inds], img_h, img_w, skip_empty=device.type == "cpu" - ) - - if threshold >= 0: - masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) - else: - # for visualization and debugging - masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) - - if torch.jit.is_scripting(): # Scripting does not use the optimized codepath - img_masks[inds] = masks_chunk - else: - img_masks[(inds,) + spatial_inds] = masks_chunk - return img_masks - - -# The below are the original paste function (from Detectron1) which has -# larger quantization error. -# It is faster on CPU, while the aligned one is faster on GPU thanks to grid_sample. - - -def paste_mask_in_image_old(mask, box, img_h, img_w, threshold): - """ - Paste a single mask in an image. - This is a per-box implementation of :func:`paste_masks_in_image`. - This function has larger quantization error due to incorrect pixel - modeling and is not used any more. - - Args: - mask (Tensor): A tensor of shape (Hmask, Wmask) storing the mask of a single - object instance. Values are in [0, 1]. - box (Tensor): A tensor of shape (4, ) storing the x0, y0, x1, y1 box corners - of the object instance. - img_h, img_w (int): Image height and width. - threshold (float): Mask binarization threshold in [0, 1]. - - Returns: - im_mask (Tensor): - The resized and binarized object mask pasted into the original - image plane (a tensor of shape (img_h, img_w)). - """ - # Conversion from continuous box coordinates to discrete pixel coordinates - # via truncation (cast to int32). This determines which pixels to paste the - # mask onto. - box = box.to(dtype=torch.int32) # Continuous to discrete coordinate conversion - # An example (1D) box with continuous coordinates (x0=0.7, x1=4.3) will map to - # a discrete coordinates (x0=0, x1=4). Note that box is mapped to 5 = x1 - x0 + 1 - # pixels (not x1 - x0 pixels). - samples_w = box[2] - box[0] + 1 # Number of pixel samples, *not* geometric width - samples_h = box[3] - box[1] + 1 # Number of pixel samples, *not* geometric height - - # Resample the mask from it's original grid to the new samples_w x samples_h grid - mask = Image.fromarray(mask.cpu().numpy()) - mask = mask.resize((samples_w, samples_h), resample=Image.BILINEAR) - mask = np.array(mask, copy=False) - - if threshold >= 0: - mask = np.array(mask > threshold, dtype=np.uint8) - mask = torch.from_numpy(mask) - else: - # for visualization and debugging, we also - # allow it to return an unmodified mask - mask = torch.from_numpy(mask * 255).to(torch.uint8) - - im_mask = torch.zeros((img_h, img_w), dtype=torch.uint8) - x_0 = max(box[0], 0) - x_1 = min(box[2] + 1, img_w) - y_0 = max(box[1], 0) - y_1 = min(box[3] + 1, img_h) - - im_mask[y_0:y_1, x_0:x_1] = mask[ - (y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0]) - ] - return im_mask - - -# Our pixel modeling requires extrapolation for any continuous -# coordinate < 0.5 or > length - 0.5. When sampling pixels on the masks, -# we would like this extrapolation to be an interpolation between boundary values and zero, -# instead of using absolute zero or boundary values. -# Therefore `paste_mask_in_image_old` is often used with zero padding around the masks like this: -# masks, scale = pad_masks(masks[:, 0, :, :], 1) -# boxes = scale_boxes(boxes.tensor, scale) - - -def pad_masks(masks, padding): - """ - Args: - masks (tensor): A tensor of shape (B, M, M) representing B masks. - padding (int): Number of cells to pad on all sides. - - Returns: - The padded masks and the scale factor of the padding size / original size. - """ - B = masks.shape[0] - M = masks.shape[-1] - pad2 = 2 * padding - scale = float(M + pad2) / M - padded_masks = masks.new_zeros((B, M + pad2, M + pad2)) - padded_masks[:, padding:-padding, padding:-padding] = masks - return padded_masks, scale - - -def scale_boxes(boxes, scale): - """ - Args: - boxes (tensor): A tensor of shape (B, 4) representing B boxes with 4 - coords representing the corners x0, y0, x1, y1, - scale (float): The box scaling factor. - - Returns: - Scaled boxes. - """ - w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 - h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 - x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 - y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 - - w_half *= scale - h_half *= scale - - scaled_boxes = torch.zeros_like(boxes) - scaled_boxes[:, 0] = x_c - w_half - scaled_boxes[:, 2] = x_c + w_half - scaled_boxes[:, 1] = y_c - h_half - scaled_boxes[:, 3] = y_c + h_half - return scaled_boxes - - -@torch.jit.script_if_tracing -def _paste_masks_tensor_shape( - masks: torch.Tensor, - boxes: torch.Tensor, - image_shape: Tuple[torch.Tensor, torch.Tensor], - threshold: float = 0.5, -): - """ - A wrapper of paste_masks_in_image where image_shape is Tensor. - During tracing, shapes might be tensors instead of ints. The Tensor->int - conversion should be scripted rather than traced. - """ - return paste_masks_in_image(masks, boxes, (int(image_shape[0]), int(image_shape[1])), threshold) diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/datasets/pascal_voc12_aug.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/datasets/pascal_voc12_aug.py deleted file mode 100644 index 3f23b6717d53ad29f02dd15046802a2631a5076b..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/configs/_base_/datasets/pascal_voc12_aug.py +++ /dev/null @@ -1,9 +0,0 @@ -_base_ = './pascal_voc12.py' -# dataset settings -data = dict( - train=dict( - ann_dir=['SegmentationClass', 'SegmentationClassAug'], - split=[ - 'ImageSets/Segmentation/train.txt', - 'ImageSets/Segmentation/aug.txt' - ])) diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmseg/models/backbones/cgnet.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmseg/models/backbones/cgnet.py deleted file mode 100644 index f8bca442c8f18179f217e40c298fb5ef39df77c4..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmseg/models/backbones/cgnet.py +++ /dev/null @@ -1,367 +0,0 @@ -import torch -import torch.nn as nn -import torch.utils.checkpoint as cp -from annotator.uniformer.mmcv.cnn import (ConvModule, build_conv_layer, build_norm_layer, - constant_init, kaiming_init) -from annotator.uniformer.mmcv.runner import load_checkpoint -from annotator.uniformer.mmcv.utils.parrots_wrapper import _BatchNorm - -from annotator.uniformer.mmseg.utils import get_root_logger -from ..builder import BACKBONES - - -class GlobalContextExtractor(nn.Module): - """Global Context Extractor for CGNet. - - This class is employed to refine the joint feature of both local feature - and surrounding context. - - Args: - channel (int): Number of input feature channels. - reduction (int): Reductions for global context extractor. Default: 16. - with_cp (bool): Use checkpoint or not. Using checkpoint will save some - memory while slowing down the training speed. Default: False. - """ - - def __init__(self, channel, reduction=16, with_cp=False): - super(GlobalContextExtractor, self).__init__() - self.channel = channel - self.reduction = reduction - assert reduction >= 1 and channel >= reduction - self.with_cp = with_cp - self.avg_pool = nn.AdaptiveAvgPool2d(1) - self.fc = nn.Sequential( - nn.Linear(channel, channel // reduction), nn.ReLU(inplace=True), - nn.Linear(channel // reduction, channel), nn.Sigmoid()) - - def forward(self, x): - - def _inner_forward(x): - num_batch, num_channel = x.size()[:2] - y = self.avg_pool(x).view(num_batch, num_channel) - y = self.fc(y).view(num_batch, num_channel, 1, 1) - return x * y - - if self.with_cp and x.requires_grad: - out = cp.checkpoint(_inner_forward, x) - else: - out = _inner_forward(x) - - return out - - -class ContextGuidedBlock(nn.Module): - """Context Guided Block for CGNet. - - This class consists of four components: local feature extractor, - surrounding feature extractor, joint feature extractor and global - context extractor. - - Args: - in_channels (int): Number of input feature channels. - out_channels (int): Number of output feature channels. - dilation (int): Dilation rate for surrounding context extractor. - Default: 2. - reduction (int): Reduction for global context extractor. Default: 16. - skip_connect (bool): Add input to output or not. Default: True. - downsample (bool): Downsample the input to 1/2 or not. Default: False. - conv_cfg (dict): Config dict for convolution layer. - Default: None, which means using conv2d. - norm_cfg (dict): Config dict for normalization layer. - Default: dict(type='BN', requires_grad=True). - act_cfg (dict): Config dict for activation layer. - Default: dict(type='PReLU'). - with_cp (bool): Use checkpoint or not. Using checkpoint will save some - memory while slowing down the training speed. Default: False. - """ - - def __init__(self, - in_channels, - out_channels, - dilation=2, - reduction=16, - skip_connect=True, - downsample=False, - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True), - act_cfg=dict(type='PReLU'), - with_cp=False): - super(ContextGuidedBlock, self).__init__() - self.with_cp = with_cp - self.downsample = downsample - - channels = out_channels if downsample else out_channels // 2 - if 'type' in act_cfg and act_cfg['type'] == 'PReLU': - act_cfg['num_parameters'] = channels - kernel_size = 3 if downsample else 1 - stride = 2 if downsample else 1 - padding = (kernel_size - 1) // 2 - - self.conv1x1 = ConvModule( - in_channels, - channels, - kernel_size, - stride, - padding, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - - self.f_loc = build_conv_layer( - conv_cfg, - channels, - channels, - kernel_size=3, - padding=1, - groups=channels, - bias=False) - self.f_sur = build_conv_layer( - conv_cfg, - channels, - channels, - kernel_size=3, - padding=dilation, - groups=channels, - dilation=dilation, - bias=False) - - self.bn = build_norm_layer(norm_cfg, 2 * channels)[1] - self.activate = nn.PReLU(2 * channels) - - if downsample: - self.bottleneck = build_conv_layer( - conv_cfg, - 2 * channels, - out_channels, - kernel_size=1, - bias=False) - - self.skip_connect = skip_connect and not downsample - self.f_glo = GlobalContextExtractor(out_channels, reduction, with_cp) - - def forward(self, x): - - def _inner_forward(x): - out = self.conv1x1(x) - loc = self.f_loc(out) - sur = self.f_sur(out) - - joi_feat = torch.cat([loc, sur], 1) # the joint feature - joi_feat = self.bn(joi_feat) - joi_feat = self.activate(joi_feat) - if self.downsample: - joi_feat = self.bottleneck(joi_feat) # channel = out_channels - # f_glo is employed to refine the joint feature - out = self.f_glo(joi_feat) - - if self.skip_connect: - return x + out - else: - return out - - if self.with_cp and x.requires_grad: - out = cp.checkpoint(_inner_forward, x) - else: - out = _inner_forward(x) - - return out - - -class InputInjection(nn.Module): - """Downsampling module for CGNet.""" - - def __init__(self, num_downsampling): - super(InputInjection, self).__init__() - self.pool = nn.ModuleList() - for i in range(num_downsampling): - self.pool.append(nn.AvgPool2d(3, stride=2, padding=1)) - - def forward(self, x): - for pool in self.pool: - x = pool(x) - return x - - -@BACKBONES.register_module() -class CGNet(nn.Module): - """CGNet backbone. - - A Light-weight Context Guided Network for Semantic Segmentation - arXiv: https://arxiv.org/abs/1811.08201 - - Args: - in_channels (int): Number of input image channels. Normally 3. - num_channels (tuple[int]): Numbers of feature channels at each stages. - Default: (32, 64, 128). - num_blocks (tuple[int]): Numbers of CG blocks at stage 1 and stage 2. - Default: (3, 21). - dilations (tuple[int]): Dilation rate for surrounding context - extractors at stage 1 and stage 2. Default: (2, 4). - reductions (tuple[int]): Reductions for global context extractors at - stage 1 and stage 2. Default: (8, 16). - conv_cfg (dict): Config dict for convolution layer. - Default: None, which means using conv2d. - norm_cfg (dict): Config dict for normalization layer. - Default: dict(type='BN', requires_grad=True). - act_cfg (dict): Config dict for activation layer. - Default: dict(type='PReLU'). - norm_eval (bool): Whether to set norm layers to eval mode, namely, - freeze running stats (mean and var). Note: Effect on Batch Norm - and its variants only. Default: False. - with_cp (bool): Use checkpoint or not. Using checkpoint will save some - memory while slowing down the training speed. Default: False. - """ - - def __init__(self, - in_channels=3, - num_channels=(32, 64, 128), - num_blocks=(3, 21), - dilations=(2, 4), - reductions=(8, 16), - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True), - act_cfg=dict(type='PReLU'), - norm_eval=False, - with_cp=False): - - super(CGNet, self).__init__() - self.in_channels = in_channels - self.num_channels = num_channels - assert isinstance(self.num_channels, tuple) and len( - self.num_channels) == 3 - self.num_blocks = num_blocks - assert isinstance(self.num_blocks, tuple) and len(self.num_blocks) == 2 - self.dilations = dilations - assert isinstance(self.dilations, tuple) and len(self.dilations) == 2 - self.reductions = reductions - assert isinstance(self.reductions, tuple) and len(self.reductions) == 2 - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.act_cfg = act_cfg - if 'type' in self.act_cfg and self.act_cfg['type'] == 'PReLU': - self.act_cfg['num_parameters'] = num_channels[0] - self.norm_eval = norm_eval - self.with_cp = with_cp - - cur_channels = in_channels - self.stem = nn.ModuleList() - for i in range(3): - self.stem.append( - ConvModule( - cur_channels, - num_channels[0], - 3, - 2 if i == 0 else 1, - padding=1, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg)) - cur_channels = num_channels[0] - - self.inject_2x = InputInjection(1) # down-sample for Input, factor=2 - self.inject_4x = InputInjection(2) # down-sample for Input, factor=4 - - cur_channels += in_channels - self.norm_prelu_0 = nn.Sequential( - build_norm_layer(norm_cfg, cur_channels)[1], - nn.PReLU(cur_channels)) - - # stage 1 - self.level1 = nn.ModuleList() - for i in range(num_blocks[0]): - self.level1.append( - ContextGuidedBlock( - cur_channels if i == 0 else num_channels[1], - num_channels[1], - dilations[0], - reductions[0], - downsample=(i == 0), - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg, - with_cp=with_cp)) # CG block - - cur_channels = 2 * num_channels[1] + in_channels - self.norm_prelu_1 = nn.Sequential( - build_norm_layer(norm_cfg, cur_channels)[1], - nn.PReLU(cur_channels)) - - # stage 2 - self.level2 = nn.ModuleList() - for i in range(num_blocks[1]): - self.level2.append( - ContextGuidedBlock( - cur_channels if i == 0 else num_channels[2], - num_channels[2], - dilations[1], - reductions[1], - downsample=(i == 0), - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg, - with_cp=with_cp)) # CG block - - cur_channels = 2 * num_channels[2] - self.norm_prelu_2 = nn.Sequential( - build_norm_layer(norm_cfg, cur_channels)[1], - nn.PReLU(cur_channels)) - - def forward(self, x): - output = [] - - # stage 0 - inp_2x = self.inject_2x(x) - inp_4x = self.inject_4x(x) - for layer in self.stem: - x = layer(x) - x = self.norm_prelu_0(torch.cat([x, inp_2x], 1)) - output.append(x) - - # stage 1 - for i, layer in enumerate(self.level1): - x = layer(x) - if i == 0: - down1 = x - x = self.norm_prelu_1(torch.cat([x, down1, inp_4x], 1)) - output.append(x) - - # stage 2 - for i, layer in enumerate(self.level2): - x = layer(x) - if i == 0: - down2 = x - x = self.norm_prelu_2(torch.cat([down2, x], 1)) - output.append(x) - - return output - - def init_weights(self, pretrained=None): - """Initialize the weights in backbone. - - Args: - pretrained (str, optional): Path to pre-trained weights. - Defaults to None. - """ - if isinstance(pretrained, str): - logger = get_root_logger() - load_checkpoint(self, pretrained, strict=False, logger=logger) - elif pretrained is None: - for m in self.modules(): - if isinstance(m, (nn.Conv2d, nn.Linear)): - kaiming_init(m) - elif isinstance(m, (_BatchNorm, nn.GroupNorm)): - constant_init(m, 1) - elif isinstance(m, nn.PReLU): - constant_init(m, 0) - else: - raise TypeError('pretrained must be a str or None') - - def train(self, mode=True): - """Convert the model into training mode will keeping the normalization - layer freezed.""" - super(CGNet, self).train(mode) - if mode and self.norm_eval: - for m in self.modules(): - # trick: eval have effect on BatchNorm only - if isinstance(m, _BatchNorm): - m.eval() diff --git a/spaces/PSLD/PSLD/stable-diffusion/ldm/models/diffusion/__init__.py b/spaces/PSLD/PSLD/stable-diffusion/ldm/models/diffusion/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/ice-9/regex.go b/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/ice-9/regex.go deleted file mode 100644 index e4ace196984d0ad03e25265a2fa0449f5bafc228..0000000000000000000000000000000000000000 Binary files a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/ice-9/regex.go and /dev/null differ diff --git a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/language/cps/specialize-primcalls.go b/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/language/cps/specialize-primcalls.go deleted file mode 100644 index b05eb19cea80a9c848af4e33022313dd1205a64c..0000000000000000000000000000000000000000 Binary files a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/language/cps/specialize-primcalls.go and /dev/null differ diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/visualization/color.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/visualization/color.py deleted file mode 100644 index 9041e0e6b7581c3356795d6a3c5e84667c88f025..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/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/Pie31415/control-animation/annotator/uniformer/mmseg/core/evaluation/eval_hooks.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmseg/core/evaluation/eval_hooks.py deleted file mode 100644 index 6fc100c8f96e817a6ed2666f7c9f762af2463b48..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/mmseg/core/evaluation/eval_hooks.py +++ /dev/null @@ -1,109 +0,0 @@ -import os.path as osp - -from annotator.uniformer.mmcv.runner import DistEvalHook as _DistEvalHook -from annotator.uniformer.mmcv.runner import EvalHook as _EvalHook - - -class EvalHook(_EvalHook): - """Single GPU EvalHook, with efficient test support. - - Args: - by_epoch (bool): Determine perform evaluation by epoch or by iteration. - If set to True, it will perform by epoch. Otherwise, by iteration. - Default: False. - efficient_test (bool): Whether save the results as local numpy files to - save CPU memory during evaluation. Default: False. - Returns: - list: The prediction results. - """ - - greater_keys = ['mIoU', 'mAcc', 'aAcc'] - - def __init__(self, *args, by_epoch=False, efficient_test=False, **kwargs): - super().__init__(*args, by_epoch=by_epoch, **kwargs) - self.efficient_test = efficient_test - - def after_train_iter(self, runner): - """After train epoch hook. - - Override default ``single_gpu_test``. - """ - if self.by_epoch or not self.every_n_iters(runner, self.interval): - return - from annotator.uniformer.mmseg.apis import single_gpu_test - runner.log_buffer.clear() - results = single_gpu_test( - runner.model, - self.dataloader, - show=False, - efficient_test=self.efficient_test) - self.evaluate(runner, results) - - def after_train_epoch(self, runner): - """After train epoch hook. - - Override default ``single_gpu_test``. - """ - if not self.by_epoch or not self.every_n_epochs(runner, self.interval): - return - from annotator.uniformer.mmseg.apis import single_gpu_test - runner.log_buffer.clear() - results = single_gpu_test(runner.model, self.dataloader, show=False) - self.evaluate(runner, results) - - -class DistEvalHook(_DistEvalHook): - """Distributed EvalHook, with efficient test support. - - Args: - by_epoch (bool): Determine perform evaluation by epoch or by iteration. - If set to True, it will perform by epoch. Otherwise, by iteration. - Default: False. - efficient_test (bool): Whether save the results as local numpy files to - save CPU memory during evaluation. Default: False. - Returns: - list: The prediction results. - """ - - greater_keys = ['mIoU', 'mAcc', 'aAcc'] - - def __init__(self, *args, by_epoch=False, efficient_test=False, **kwargs): - super().__init__(*args, by_epoch=by_epoch, **kwargs) - self.efficient_test = efficient_test - - def after_train_iter(self, runner): - """After train epoch hook. - - Override default ``multi_gpu_test``. - """ - if self.by_epoch or not self.every_n_iters(runner, self.interval): - return - from annotator.uniformer.mmseg.apis import multi_gpu_test - runner.log_buffer.clear() - results = multi_gpu_test( - runner.model, - self.dataloader, - tmpdir=osp.join(runner.work_dir, '.eval_hook'), - gpu_collect=self.gpu_collect, - efficient_test=self.efficient_test) - if runner.rank == 0: - print('\n') - self.evaluate(runner, results) - - def after_train_epoch(self, runner): - """After train epoch hook. - - Override default ``multi_gpu_test``. - """ - if not self.by_epoch or not self.every_n_epochs(runner, self.interval): - return - from annotator.uniformer.mmseg.apis import multi_gpu_test - runner.log_buffer.clear() - results = multi_gpu_test( - runner.model, - self.dataloader, - tmpdir=osp.join(runner.work_dir, '.eval_hook'), - gpu_collect=self.gpu_collect) - if runner.rank == 0: - print('\n') - self.evaluate(runner, results) diff --git a/spaces/RMXK/RVC_HFF/infer/lib/infer_pack/models_onnx.py b/spaces/RMXK/RVC_HFF/infer/lib/infer_pack/models_onnx.py deleted file mode 100644 index 3e99763bf3ed7988eb2ae33d9066f85d37adf119..0000000000000000000000000000000000000000 --- a/spaces/RMXK/RVC_HFF/infer/lib/infer_pack/models_onnx.py +++ /dev/null @@ -1,824 +0,0 @@ -import math -import logging - -logger = logging.getLogger(__name__) - -import numpy as np -import torch -from torch import nn -from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d -from torch.nn import functional as F -from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm - -from infer.lib.infer_pack import attentions, commons, modules -from infer.lib.infer_pack.commons import get_padding, init_weights - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder768(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(768, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMsNSFsidM(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - version, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - if version == "v1": - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - else: - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - self.speaker_map = None - logger.debug( - "gin_channels: " - + gin_channels - + ", self.spk_embed_dim: " - + self.spk_embed_dim - ) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def construct_spkmixmap(self, n_speaker): - self.speaker_map = torch.zeros((n_speaker, 1, 1, self.gin_channels)) - for i in range(n_speaker): - self.speaker_map[i] = self.emb_g(torch.LongTensor([[i]])) - self.speaker_map = self.speaker_map.unsqueeze(0) - - def forward(self, phone, phone_lengths, pitch, nsff0, g, rnd, max_len=None): - if self.speaker_map is not None: # [N, S] * [S, B, 1, H] - g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1] - g = g * self.speaker_map # [N, S, B, 1, H] - g = torch.sum(g, dim=1) # [N, 1, B, 1, H] - g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N] - else: - g = g.unsqueeze(0) - g = self.emb_g(g).transpose(1, 2) - - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * rnd) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g) - return o - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class MultiPeriodDiscriminatorV2(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminatorV2, self).__init__() - # periods = [2, 3, 5, 7, 11, 17] - periods = [2, 3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/RTL/videomatch/videohash.py b/spaces/RTL/videomatch/videohash.py deleted file mode 100644 index 08789a6c296be5ab4d040e0651280ed61387b1a6..0000000000000000000000000000000000000000 --- a/spaces/RTL/videomatch/videohash.py +++ /dev/null @@ -1,163 +0,0 @@ -import os -import urllib.request -import shutil -import logging -import hashlib -import time - -from PIL import Image -import imagehash -from moviepy.editor import VideoFileClip -from moviepy.video.fx.all import crop -import numpy as np -from pytube import YouTube -import subprocess as sp - -from config import FPS, VIDEO_DIRECTORY - - -def filepath_from_url(url): - """Function to generate filepath from url. - - Args: - url (str): The url of the input video. - - Returns: - (str): Filepath of the video based on md5 hash of the url. - """ - return os.path.join(VIDEO_DIRECTORY, hashlib.md5(url.encode()).hexdigest()) - -def download_video_from_url(url): - """Download video from url or return md5 hash as video name. - - Args: - url (str): The url of the input video - - Returns: - filepath (str): Filepath to the downloaded video from the url. - """ - start = time.time() - - # Generate filepath from url - filepath = filepath_from_url(url) - - # Check if it exists already - if not os.path.exists(filepath): - # For YouTube links - if url.startswith('https://www.youtube.com') or url.startswith('youtube.com') or url.startswith('http://www.youtube.com'): - file_dir = '/'.join(x for x in filepath.split('/')[:-1]) - filename = filepath.split('/')[-1] - logging.info(f"file_dir = {file_dir}") - logging.info(f"filename = {filename}") - YouTube(url).streams.get_highest_resolution().download(file_dir, skip_existing = False, filename = filename) - logging.info(f"Downloaded YouTube video from {url} to {filepath} in {time.time() - start:.1f} seconds.") - return filepath - - # Works for basically all links, except youtube - with (urllib.request.urlopen(url)) as f, open(filepath, 'wb') as fileout: - logging.info(f"Starting copyfileobj on {f}") - shutil.copyfileobj(f, fileout, length=16*1024*1024) - logging.info(f"Downloaded video from {url} to {filepath} in {time.time() - start:.1f} seconds.") - else: - logging.info(f"Skipping downloading from {url} because {filepath} already exists.") - return filepath - -def change_ffmpeg_fps(clip, fps=FPS): - """Change frame rate of a clip. - - Args: - clip (moviepy.editor.VideoFileClip): Input clip. - fps (int): The desired frame rate for the clip. - - Returns: - clip (moviepy.editor.VideoFileClip): New clip with the desired frames per seconds. - """ - # Hacking the ffmpeg call based on - # https://github.com/Zulko/moviepy/blob/master/moviepy/video/io/ffmpeg_reader.py#L126 - - # Define ffmpeg style command - cmd = [arg + ",fps=%d" % fps if arg.startswith("scale=") else arg for arg in clip.reader.proc.args] - clip.reader.close() - clip.reader.proc = sp.Popen(cmd, bufsize=clip.reader.bufsize, - stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.DEVNULL) - clip.fps = clip.reader.fps = fps - clip.reader.lastread = clip.reader.read_frame() - return clip - -def crop_video(clip, crop_percentage=0.75, w=224, h=224): - """Crop video clip to given crop percentage. - - Args: - clip (moviepy.editor.VideoFileClip): Clip to be cropped. - crop_percentage (float): How much of the width and heights needs to remain after cropping. - width (float): Final width the video clip will be resized to. - height (float): Final height the video clip will be resized to. - - Returns: - (moviepy.editor.VideoFileClip): Cropped and resized clip. - """ - # Original width and height- which combined with crop_percentage determines the size of the new video - ow, oh = clip.size - - logging.info(f"Cropping and resizing video to ({w}, {h})") - - # 75% of the width and height from the center of the clip is taken, so 25% is discarded - # The video is then resized to given w,h - for faster computation of hashes - return crop(clip, x_center=ow/2, y_center=oh/2, width=int(ow*crop_percentage), height=int(crop_percentage*oh)).resize((w,h)) - -def compute_hash(frame, hash_size=16): - """Compute (p)hashes of the given frame. - - Args: - frame (numpy.ndarray): Frame from the video. - hash_size (int): Size of the required hash. - - Returns: - (numpy.ndarray): Perceptual hash of the frame of size (hash_size, hash_size) - """ - image = Image.fromarray(np.array(frame)) - - return imagehash.phash(image, hash_size) - -def binary_array_to_uint8s(arr): - """Convert binary array to form uint8s. - - Args: - arr (numpy.ndarray): Frame from the video. - - Returns: - (list): Hash converted from uint8 format - """ - - # First make a bitstring out of the (hash_size, hash_size) ndarray - bit_string = ''.join(str(1 * x) for l in arr for x in l) - - # Converting to uint8- segment at every 8th bit and convert to decimal value - return [int(bit_string[i:i+8], 2) for i in range(0, len(bit_string), 8)] - -def compute_hashes(url: str, fps=FPS): - """Compute hashes of the video at the given url. - - Args: - url (str): Url of the input video. - - Yields: - ({str: int, str: numpy.ndarray}): Dict with the frame number and the corresponding hash. - """ - - # Try downloading the video from url. If that fails, load it directly from the url instead - # Then crop the video - - try: - filepath = download_video_from_url(url) - clip = crop_video(VideoFileClip(filepath)) - except IOError: - logging.warn(f"Falling back to direct streaming from {url} because the downloaded video failed.") - clip = crop_video(VideoFileClip(url)) - - for index, frame in enumerate(change_ffmpeg_fps(clip, fps).iter_frames()): - # Each frame is a triplet of size (height, width, 3) of the video since it is RGB - # The hash itself is of size (hash_size, hash_size) - # The uint8 version of the hash is of size (hash_size * highfreq_factor,) and represents the hash - hashed = np.array(binary_array_to_uint8s(compute_hash(frame).hash), dtype='uint8') - yield {"frame": 1+index*fps, "hash": hashed} \ No newline at end of file diff --git a/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/dataset/transforms/__init__.py b/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/dataset/transforms/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Redgon/bingo/src/pages/api/healthz.ts b/spaces/Redgon/bingo/src/pages/api/healthz.ts deleted file mode 100644 index f6ae44ff0fd66ccd3f7feaa550025fbf2a83bf77..0000000000000000000000000000000000000000 --- a/spaces/Redgon/bingo/src/pages/api/healthz.ts +++ /dev/null @@ -1,7 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - res.status(200).end('ok') -} diff --git a/spaces/RisticksAI/ProfNet3-Snapy-support-chatbot/README.md b/spaces/RisticksAI/ProfNet3-Snapy-support-chatbot/README.md deleted file mode 100644 index 9dad048c60cd8161de7ecbe450cf3157d0ddab7e..0000000000000000000000000000000000000000 --- a/spaces/RisticksAI/ProfNet3-Snapy-support-chatbot/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: ProfNet3-snapy-support-chatbot -emoji: 🎉 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.27.0 -app_file: app.py -pinned: false -duplicated_from: RisticksAI/ProfNet3 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/parallel/distributed_deprecated.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/parallel/distributed_deprecated.py deleted file mode 100644 index 676937a2085d4da20fa87923041a200fca6214eb..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/parallel/distributed_deprecated.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -import torch.distributed as dist -import torch.nn as nn -from torch._utils import (_flatten_dense_tensors, _take_tensors, - _unflatten_dense_tensors) - -from annotator.uniformer.mmcv.utils import TORCH_VERSION, digit_version -from .registry import MODULE_WRAPPERS -from .scatter_gather import scatter_kwargs - - -@MODULE_WRAPPERS.register_module() -class MMDistributedDataParallel(nn.Module): - - def __init__(self, - module, - dim=0, - broadcast_buffers=True, - bucket_cap_mb=25): - super(MMDistributedDataParallel, self).__init__() - self.module = module - self.dim = dim - self.broadcast_buffers = broadcast_buffers - - self.broadcast_bucket_size = bucket_cap_mb * 1024 * 1024 - self._sync_params() - - def _dist_broadcast_coalesced(self, tensors, buffer_size): - for tensors in _take_tensors(tensors, buffer_size): - flat_tensors = _flatten_dense_tensors(tensors) - dist.broadcast(flat_tensors, 0) - for tensor, synced in zip( - tensors, _unflatten_dense_tensors(flat_tensors, tensors)): - tensor.copy_(synced) - - def _sync_params(self): - module_states = list(self.module.state_dict().values()) - if len(module_states) > 0: - self._dist_broadcast_coalesced(module_states, - self.broadcast_bucket_size) - if self.broadcast_buffers: - if (TORCH_VERSION != 'parrots' - and digit_version(TORCH_VERSION) < digit_version('1.0')): - buffers = [b.data for b in self.module._all_buffers()] - else: - buffers = [b.data for b in self.module.buffers()] - if len(buffers) > 0: - self._dist_broadcast_coalesced(buffers, - self.broadcast_bucket_size) - - def scatter(self, inputs, kwargs, device_ids): - return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim) - - def forward(self, *inputs, **kwargs): - inputs, kwargs = self.scatter(inputs, kwargs, - [torch.cuda.current_device()]) - return self.module(*inputs[0], **kwargs[0]) - - def train_step(self, *inputs, **kwargs): - inputs, kwargs = self.scatter(inputs, kwargs, - [torch.cuda.current_device()]) - output = self.module.train_step(*inputs[0], **kwargs[0]) - return output - - def val_step(self, *inputs, **kwargs): - inputs, kwargs = self.scatter(inputs, kwargs, - [torch.cuda.current_device()]) - output = self.module.val_step(*inputs[0], **kwargs[0]) - return output diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/core/bbox/assigners/assign_result.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/core/bbox/assigners/assign_result.py deleted file mode 100644 index 4639fbdba0a5b92778e1ab87d61182e54bfb9b6f..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/core/bbox/assigners/assign_result.py +++ /dev/null @@ -1,204 +0,0 @@ -import torch - -from mmdet.utils import util_mixins - - -class AssignResult(util_mixins.NiceRepr): - """Stores assignments between predicted and truth boxes. - - Attributes: - num_gts (int): the number of truth boxes considered when computing this - assignment - - gt_inds (LongTensor): for each predicted box indicates the 1-based - index of the assigned truth box. 0 means unassigned and -1 means - ignore. - - max_overlaps (FloatTensor): the iou between the predicted box and its - assigned truth box. - - labels (None | LongTensor): If specified, for each predicted box - indicates the category label of the assigned truth box. - - Example: - >>> # An assign result between 4 predicted boxes and 9 true boxes - >>> # where only two boxes were assigned. - >>> num_gts = 9 - >>> max_overlaps = torch.LongTensor([0, .5, .9, 0]) - >>> gt_inds = torch.LongTensor([-1, 1, 2, 0]) - >>> labels = torch.LongTensor([0, 3, 4, 0]) - >>> self = AssignResult(num_gts, gt_inds, max_overlaps, labels) - >>> print(str(self)) # xdoctest: +IGNORE_WANT - - >>> # Force addition of gt labels (when adding gt as proposals) - >>> new_labels = torch.LongTensor([3, 4, 5]) - >>> self.add_gt_(new_labels) - >>> print(str(self)) # xdoctest: +IGNORE_WANT - - """ - - def __init__(self, num_gts, gt_inds, max_overlaps, labels=None): - self.num_gts = num_gts - self.gt_inds = gt_inds - self.max_overlaps = max_overlaps - self.labels = labels - # Interface for possible user-defined properties - self._extra_properties = {} - - @property - def num_preds(self): - """int: the number of predictions in this assignment""" - return len(self.gt_inds) - - def set_extra_property(self, key, value): - """Set user-defined new property.""" - assert key not in self.info - self._extra_properties[key] = value - - def get_extra_property(self, key): - """Get user-defined property.""" - return self._extra_properties.get(key, None) - - @property - def info(self): - """dict: a dictionary of info about the object""" - basic_info = { - 'num_gts': self.num_gts, - 'num_preds': self.num_preds, - 'gt_inds': self.gt_inds, - 'max_overlaps': self.max_overlaps, - 'labels': self.labels, - } - basic_info.update(self._extra_properties) - return basic_info - - def __nice__(self): - """str: a "nice" summary string describing this assign result""" - parts = [] - parts.append(f'num_gts={self.num_gts!r}') - if self.gt_inds is None: - parts.append(f'gt_inds={self.gt_inds!r}') - else: - parts.append(f'gt_inds.shape={tuple(self.gt_inds.shape)!r}') - if self.max_overlaps is None: - parts.append(f'max_overlaps={self.max_overlaps!r}') - else: - parts.append('max_overlaps.shape=' - f'{tuple(self.max_overlaps.shape)!r}') - if self.labels is None: - parts.append(f'labels={self.labels!r}') - else: - parts.append(f'labels.shape={tuple(self.labels.shape)!r}') - return ', '.join(parts) - - @classmethod - def random(cls, **kwargs): - """Create random AssignResult for tests or debugging. - - Args: - num_preds: number of predicted boxes - num_gts: number of true boxes - p_ignore (float): probability of a predicted box assinged to an - ignored truth - p_assigned (float): probability of a predicted box not being - assigned - p_use_label (float | bool): with labels or not - rng (None | int | numpy.random.RandomState): seed or state - - Returns: - :obj:`AssignResult`: Randomly generated assign results. - - Example: - >>> from mmdet.core.bbox.assigners.assign_result import * # NOQA - >>> self = AssignResult.random() - >>> print(self.info) - """ - from mmdet.core.bbox import demodata - rng = demodata.ensure_rng(kwargs.get('rng', None)) - - num_gts = kwargs.get('num_gts', None) - num_preds = kwargs.get('num_preds', None) - p_ignore = kwargs.get('p_ignore', 0.3) - p_assigned = kwargs.get('p_assigned', 0.7) - p_use_label = kwargs.get('p_use_label', 0.5) - num_classes = kwargs.get('p_use_label', 3) - - if num_gts is None: - num_gts = rng.randint(0, 8) - if num_preds is None: - num_preds = rng.randint(0, 16) - - if num_gts == 0: - max_overlaps = torch.zeros(num_preds, dtype=torch.float32) - gt_inds = torch.zeros(num_preds, dtype=torch.int64) - if p_use_label is True or p_use_label < rng.rand(): - labels = torch.zeros(num_preds, dtype=torch.int64) - else: - labels = None - else: - import numpy as np - # Create an overlap for each predicted box - max_overlaps = torch.from_numpy(rng.rand(num_preds)) - - # Construct gt_inds for each predicted box - is_assigned = torch.from_numpy(rng.rand(num_preds) < p_assigned) - # maximum number of assignments constraints - n_assigned = min(num_preds, min(num_gts, is_assigned.sum())) - - assigned_idxs = np.where(is_assigned)[0] - rng.shuffle(assigned_idxs) - assigned_idxs = assigned_idxs[0:n_assigned] - assigned_idxs.sort() - - is_assigned[:] = 0 - is_assigned[assigned_idxs] = True - - is_ignore = torch.from_numpy( - rng.rand(num_preds) < p_ignore) & is_assigned - - gt_inds = torch.zeros(num_preds, dtype=torch.int64) - - true_idxs = np.arange(num_gts) - rng.shuffle(true_idxs) - true_idxs = torch.from_numpy(true_idxs) - gt_inds[is_assigned] = true_idxs[:n_assigned] - - gt_inds = torch.from_numpy( - rng.randint(1, num_gts + 1, size=num_preds)) - gt_inds[is_ignore] = -1 - gt_inds[~is_assigned] = 0 - max_overlaps[~is_assigned] = 0 - - if p_use_label is True or p_use_label < rng.rand(): - if num_classes == 0: - labels = torch.zeros(num_preds, dtype=torch.int64) - else: - labels = torch.from_numpy( - # remind that we set FG labels to [0, num_class-1] - # since mmdet v2.0 - # BG cat_id: num_class - rng.randint(0, num_classes, size=num_preds)) - labels[~is_assigned] = 0 - else: - labels = None - - self = cls(num_gts, gt_inds, max_overlaps, labels) - return self - - def add_gt_(self, gt_labels): - """Add ground truth as assigned results. - - Args: - gt_labels (torch.Tensor): Labels of gt boxes - """ - self_inds = torch.arange( - 1, len(gt_labels) + 1, dtype=torch.long, device=gt_labels.device) - self.gt_inds = torch.cat([self_inds, self.gt_inds]) - - self.max_overlaps = torch.cat( - [self.max_overlaps.new_ones(len(gt_labels)), self.max_overlaps]) - - if self.labels is not None: - self.labels = torch.cat([gt_labels, self.labels]) diff --git a/spaces/SERER/VITS-Umamusume-voice-synthesizer/ONNXVITS_utils.py b/spaces/SERER/VITS-Umamusume-voice-synthesizer/ONNXVITS_utils.py deleted file mode 100644 index b634ce380421571e6e07fb45dd59717b3f63115c..0000000000000000000000000000000000000000 --- a/spaces/SERER/VITS-Umamusume-voice-synthesizer/ONNXVITS_utils.py +++ /dev/null @@ -1,19 +0,0 @@ -import torch -import numpy as np -import random -import onnxruntime as ort -def set_random_seed(seed=0): - ort.set_seed(seed) - torch.manual_seed(seed) - torch.cuda.manual_seed(seed) - torch.backends.cudnn.deterministic = True - random.seed(seed) - np.random.seed(seed) - -def runonnx(model_path, **kwargs): - ort_session = ort.InferenceSession(model_path) - outputs = ort_session.run( - None, - kwargs - ) - return outputs \ No newline at end of file diff --git a/spaces/SUSSYMANBI/Alex-diffusion-beta/README.md b/spaces/SUSSYMANBI/Alex-diffusion-beta/README.md deleted file mode 100644 index 941991689bb775bc4f1a5b06e9d207cd3c569926..0000000000000000000000000000000000000000 --- a/spaces/SUSSYMANBI/Alex-diffusion-beta/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Alexa diffusion -emoji: 👁 -colorFrom: indigo -colorTo: gray -sdk: gradio -sdk_version: 3.10.1 -app_file: app.py -pinned: false -duplicated_from: Rahorus/Alexa-diffusion ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/Salesforce/EDICT/my_half_diffusers/pipelines/ddpm/__init__.py b/spaces/Salesforce/EDICT/my_half_diffusers/pipelines/ddpm/__init__.py deleted file mode 100644 index 8889bdae1224e91916e0f8454bafba0ee566f3b9..0000000000000000000000000000000000000000 --- a/spaces/Salesforce/EDICT/my_half_diffusers/pipelines/ddpm/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# flake8: noqa -from .pipeline_ddpm import DDPMPipeline diff --git a/spaces/ServerX/PorcoDiaz/lib/uvr5_pack/lib_v5/model_param_init.py b/spaces/ServerX/PorcoDiaz/lib/uvr5_pack/lib_v5/model_param_init.py deleted file mode 100644 index b995c0bfb1194746187692e2ab1c2a6dbaaaec6c..0000000000000000000000000000000000000000 --- a/spaces/ServerX/PorcoDiaz/lib/uvr5_pack/lib_v5/model_param_init.py +++ /dev/null @@ -1,69 +0,0 @@ -import json -import os -import pathlib - -default_param = {} -default_param["bins"] = 768 -default_param["unstable_bins"] = 9 # training only -default_param["reduction_bins"] = 762 # training only -default_param["sr"] = 44100 -default_param["pre_filter_start"] = 757 -default_param["pre_filter_stop"] = 768 -default_param["band"] = {} - - -default_param["band"][1] = { - "sr": 11025, - "hl": 128, - "n_fft": 960, - "crop_start": 0, - "crop_stop": 245, - "lpf_start": 61, # inference only - "res_type": "polyphase", -} - -default_param["band"][2] = { - "sr": 44100, - "hl": 512, - "n_fft": 1536, - "crop_start": 24, - "crop_stop": 547, - "hpf_start": 81, # inference only - "res_type": "sinc_best", -} - - -def int_keys(d): - r = {} - for k, v in d: - if k.isdigit(): - k = int(k) - r[k] = v - return r - - -class ModelParameters(object): - def __init__(self, config_path=""): - if ".pth" == pathlib.Path(config_path).suffix: - import zipfile - - with zipfile.ZipFile(config_path, "r") as zip: - self.param = json.loads( - zip.read("param.json"), object_pairs_hook=int_keys - ) - elif ".json" == pathlib.Path(config_path).suffix: - with open(config_path, "r") as f: - self.param = json.loads(f.read(), object_pairs_hook=int_keys) - else: - self.param = default_param - - for k in [ - "mid_side", - "mid_side_b", - "mid_side_b2", - "stereo_w", - "stereo_n", - "reverse", - ]: - if not k in self.param: - self.param[k] = False diff --git a/spaces/ShadowDominator/image-to-text-khmer-ocr/app.py b/spaces/ShadowDominator/image-to-text-khmer-ocr/app.py deleted file mode 100644 index a1d23d44a313c93484852bb83e7805ba63c1456f..0000000000000000000000000000000000000000 --- a/spaces/ShadowDominator/image-to-text-khmer-ocr/app.py +++ /dev/null @@ -1,25 +0,0 @@ -from PIL import Image -import pytesseract -import gradio as gr -blocks = gr.Blocks() - -def run_khm_eng(image): - result = pytesseract.image_to_string( - image, lang="khm+eng") - return result - - -with gr.Blocks() as demo: - gr.Markdown("## English+Khmer OCR") - with gr.Row(): - with gr.Column(): - image_in = gr.Image(type="pil") - btn = gr.Button("Run") - with gr.Column(): - text_out = gr.TextArea() - - examples = gr.Examples([["./demo.png", None]], fn=run_khm_eng, inputs=[ - image_in], outputs=[text_out], cache_examples=False) - btn.click(fn=run_khm_eng, inputs=[image_in], outputs=[text_out]) - -demo.launch() diff --git a/spaces/Silence1412/Stable_Diffusion_Cpu/app.py b/spaces/Silence1412/Stable_Diffusion_Cpu/app.py deleted file mode 100644 index 04fe42431ff9b903c83c267019edb961cacf3eb5..0000000000000000000000000000000000000000 --- a/spaces/Silence1412/Stable_Diffusion_Cpu/app.py +++ /dev/null @@ -1,160 +0,0 @@ -import gradio as gr -import numpy as np -import torch -from PIL import Image -from diffusers import StableDiffusionPipeline -from transformers import pipeline, set_seed -import random -import re - -model_id = "runwayml/stable-diffusion-v1-5" - -pipe = StableDiffusionPipeline.from_pretrained(model_id).to('cpu') - -gpt2_pipe = pipeline('text-generation', model='Gustavosta/MagicPrompt-Stable-Diffusion', tokenizer='gpt2') -gpt2_pipe2 = pipeline('text-generation', model='succinctly/text2image-prompt-generator') - -def infer1(starting_text): - seed = random.randint(100, 1000000) - set_seed(seed) - - if starting_text == "": - starting_text: str = re.sub(r"[,:\-–.!;?_]", '', starting_text) - - response = gpt2_pipe(starting_text, max_length=(len(starting_text) + random.randint(60, 90)), num_return_sequences=4) - response_list = [] - for x in response: - resp = x['generated_text'].strip() - if resp != starting_text and len(resp) > (len(starting_text) + 4) and resp.endswith((":", "-", "—")) is False: - response_list.append(resp+'\n') - - response_end = "\n".join(response_list) - response_end = re.sub('[^ ]+\.[^ ]+','', response_end) - response_end = response_end.replace("<", "").replace(">", "") - - if response_end != "": - return response_end - -def infer2(starting_text): - for count in range(6): - seed = random.randint(100, 1000000) - set_seed(seed) - - # If the text field is empty - if starting_text == "": - starting_text: str = line[random.randrange(0, len(line))].replace("\n", "").lower().capitalize() - starting_text: str = re.sub(r"[,:\-–.!;?_]", '', starting_text) - print(starting_text) - - response = gpt2_pipe2(starting_text, max_length=random.randint(60, 90), num_return_sequences=8) - response_list = [] - for x in response: - resp = x['generated_text'].strip() - if resp != starting_text and len(resp) > (len(starting_text) + 4) and resp.endswith((":", "-", "—")) is False: - response_list.append(resp) - - response_end = "\n".join(response_list) - response_end = re.sub('[^ ]+\.[^ ]+','', response_end) - response_end = response_end.replace("<", "").replace(">", "") - if response_end != "": - return response_end - if count == 5: - return response_end - -def infer3(prompt, negative, steps, scale, seed): - generator = torch.Generator(device='cpu').manual_seed(seed) - img = pipe( - prompt, - height=512, - width=512, - num_inference_steps=steps, - guidance_scale=scale, - negative_prompt = negative, - generator=generator, - ).images - return img - -block = gr.Blocks() - -with block: - with gr.Group(): - with gr.Box(): - gr.Markdown( - """ - Model: Gustavosta/MagicPrompt-Stable-Diffusion - """ - ) - with gr.Row() as row: - with gr.Column(): - txt = gr.Textbox(lines=1, label="Initial Text", placeholder="English Text here") - gpt_btn = gr.Button("Generate prompt").style( - margin=False, - rounded=(False, True, True, False), - ) - with gr.Column(): - out = gr.Textbox(lines=4, label="Generated Prompts") - - with gr.Box(): - gr.Markdown( - """ - Model: succinctly/text2image-prompt-generator - """ - ) - with gr.Row() as row: - with gr.Column(): - txt2 = gr.Textbox(lines=1, label="Initial Text", placeholder="English Text here") - gpt_btn2 = gr.Button("Generate prompt").style( - margin=False, - rounded=(False, True, True, False), - ) - with gr.Column(): - out2 = gr.Textbox(lines=4, label="Generated Prompts") - - with gr.Box(): - gr.Markdown( - """ - Model: stable diffusion v1.5 - """ - ) - with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True): - with gr.Column(): - text = gr.Textbox( - label="Enter your prompt", - show_label=False, - max_lines=1, - placeholder="Enter your prompt", - ).style( - border=(True, False, True, True), - rounded=(True, False, False, True), - container=False, - ) - - negative = gr.Textbox( - label="Enter your negative prompt", - show_label=False, - placeholder="Enter a negative prompt", - elem_id="negative-prompt-text-input", - ).style( - border=(True, False, True, True), - rounded=(True, False, False, True),container=False, - ) - - btn = gr.Button("Generate image").style( - margin=False, - rounded=(False, True, True, False), - ) - gallery = gr.Gallery( - label="Generated images", show_label=False, elem_id="gallery" - ).style(columns=(1, 2), height="auto") - - with gr.Row(elem_id="advanced-options"): - samples = gr.Slider(label="Images", minimum=1, maximum=1, value=1, step=1, interactive=False) - steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=12, step=1, interactive=True) - scale = gr.Slider(label="Guidance Scale", minimum=0, maximum=50, value=7.5, step=0.1, interactive=True) - seed = gr.Slider(label="Random seed",minimum=0,maximum=2147483647,step=1,randomize=True,interactive=True) - - gpt_btn.click(infer1,inputs=txt,outputs=out) - gpt_btn2.click(infer2,inputs=txt2,outputs=out2) - btn.click(infer3, inputs=[text, negative, steps, scale, seed], outputs=[gallery]) - -block.launch(show_api=False,enable_queue=True, debug=True) \ No newline at end of file diff --git a/spaces/Sk4372/stabilityai-stable-diffusion-2-base/app.py b/spaces/Sk4372/stabilityai-stable-diffusion-2-base/app.py deleted file mode 100644 index bb0db4901f9306537a13ee658d4cb65e9d89551a..0000000000000000000000000000000000000000 --- a/spaces/Sk4372/stabilityai-stable-diffusion-2-base/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/stabilityai/stable-diffusion-2-base").launch() \ No newline at end of file diff --git a/spaces/StephanST/OpenLanderONNXonline/20230608_onnx_416_mbnv2_dl3/vis_data/config.py b/spaces/StephanST/OpenLanderONNXonline/20230608_onnx_416_mbnv2_dl3/vis_data/config.py deleted file mode 100644 index 637305d9d927bc5d31e638755ca8ec0d9f0d997d..0000000000000000000000000000000000000000 --- a/spaces/StephanST/OpenLanderONNXonline/20230608_onnx_416_mbnv2_dl3/vis_data/config.py +++ /dev/null @@ -1,221 +0,0 @@ -norm_cfg = dict(type='SyncBN', requires_grad=True) -data_preprocessor = dict( - type='SegDataPreProcessor', - mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375], - bgr_to_rgb=True, - pad_val=0, - seg_pad_val=255, - size=(416, 416)) -model = dict( - type='EncoderDecoder', - data_preprocessor=dict( - type='SegDataPreProcessor', - mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375], - bgr_to_rgb=True, - pad_val=0, - seg_pad_val=255, - size=(416, 416)), - pretrained='mmcls://mobilenet_v2', - backbone=dict( - type='MobileNetV2', - widen_factor=1.0, - strides=(1, 2, 2, 1, 1, 1, 1), - dilations=(1, 1, 1, 2, 2, 4, 4), - out_indices=(1, 2, 4, 6), - norm_cfg=dict(type='SyncBN', requires_grad=True)), - decode_head=dict( - type='DepthwiseSeparableASPPHead', - in_channels=320, - in_index=3, - channels=128, - dilations=(1, 12, 24, 36), - c1_in_channels=24, - c1_channels=12, - dropout_ratio=0.1, - num_classes=3, - norm_cfg=dict(type='SyncBN', requires_grad=True), - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - auxiliary_head=dict( - type='FCNHead', - in_channels=96, - in_index=2, - channels=64, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=3, - norm_cfg=dict(type='SyncBN', requires_grad=True), - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), - train_cfg=dict(), - test_cfg=dict(mode='whole')) -dataset_type = 'DroneDataset' -data_root = 'data/drone_custom_dataset' -crop_size = (416, 416) -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations'), - dict( - type='RandomResize', - scale=(2048, 416), - ratio_range=(0.5, 2.0), - keep_ratio=True), - dict(type='RandomCrop', crop_size=(416, 416), cat_max_ratio=0.75), - dict(type='RandomFlip', prob=0.5), - dict(type='PhotoMetricDistortion'), - dict(type='PackSegInputs') -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='Resize', scale=(2048, 416), keep_ratio=True), - dict(type='LoadAnnotations'), - dict(type='PackSegInputs') -] -img_ratios = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75] -tta_pipeline = [ - dict(type='LoadImageFromFile', backend_args=None), - dict( - type='TestTimeAug', - transforms=[[{ - 'type': 'Resize', - 'scale_factor': 0.5, - 'keep_ratio': True - }, { - 'type': 'Resize', - 'scale_factor': 0.75, - 'keep_ratio': True - }, { - 'type': 'Resize', - 'scale_factor': 1.0, - 'keep_ratio': True - }, { - 'type': 'Resize', - 'scale_factor': 1.25, - 'keep_ratio': True - }, { - 'type': 'Resize', - 'scale_factor': 1.5, - 'keep_ratio': True - }, { - 'type': 'Resize', - 'scale_factor': 1.75, - 'keep_ratio': True - }], - [{ - 'type': 'RandomFlip', - 'prob': 0.0, - 'direction': 'horizontal' - }, { - 'type': 'RandomFlip', - 'prob': 1.0, - 'direction': 'horizontal' - }], [{ - 'type': 'LoadAnnotations' - }], [{ - 'type': 'PackSegInputs' - }]]) -] -train_dataloader = dict( - batch_size=24, - num_workers=1, - persistent_workers=True, - sampler=dict(type='InfiniteSampler', shuffle=True), - dataset=dict( - type='DroneDataset', - data_root='data/drone_custom_dataset', - data_prefix=dict(img_path='images', seg_map_path='anns'), - ann_file='train.txt', - pipeline=[ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations'), - dict( - type='RandomResize', - scale=(2048, 416), - ratio_range=(0.5, 2.0), - keep_ratio=True), - dict(type='RandomCrop', crop_size=(416, 416), cat_max_ratio=0.75), - dict(type='RandomFlip', prob=0.5), - dict(type='PhotoMetricDistortion'), - dict(type='PackSegInputs') - ])) -val_dataloader = dict( - batch_size=1, - num_workers=4, - persistent_workers=True, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=dict( - type='DroneDataset', - data_root='data/drone_custom_dataset', - data_prefix=dict(img_path='images', seg_map_path='anns'), - ann_file='val.txt', - pipeline=[ - dict(type='LoadImageFromFile'), - dict(type='Resize', scale=(2048, 416), keep_ratio=True), - dict(type='LoadAnnotations'), - dict(type='PackSegInputs') - ])) -test_dataloader = dict( - batch_size=1, - num_workers=4, - persistent_workers=True, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=dict( - type='DroneDataset', - data_root='data/drone_custom_dataset', - data_prefix=dict(img_path='images', seg_map_path='anns'), - ann_file='val.txt', - pipeline=[ - dict(type='LoadImageFromFile'), - dict(type='Resize', scale=(2048, 416), keep_ratio=True), - dict(type='LoadAnnotations'), - dict(type='PackSegInputs') - ])) -val_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) -test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) -default_scope = 'mmseg' -env_cfg = dict( - cudnn_benchmark=True, - mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), - dist_cfg=dict(backend='nccl')) -vis_backends = [dict(type='LocalVisBackend')] -visualizer = dict( - type='SegLocalVisualizer', - vis_backends=[dict(type='LocalVisBackend')], - name='visualizer') -log_processor = dict(by_epoch=False) -log_level = 'INFO' -load_from = None -resume = False -tta_model = dict(type='SegTTAModel') -optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) -optim_wrapper = dict( - type='OptimWrapper', - optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005), - clip_grad=None) -param_scheduler = [ - dict( - type='PolyLR', - eta_min=0.0001, - power=0.9, - begin=0, - end=240000, - by_epoch=False) -] -train_cfg = dict( - type='IterBasedTrainLoop', max_iters=240000, val_interval=24000) -val_cfg = dict(type='ValLoop') -test_cfg = dict(type='TestLoop') -default_hooks = dict( - timer=dict(type='IterTimerHook'), - logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), - param_scheduler=dict(type='ParamSchedulerHook'), - checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=24000), - sampler_seed=dict(type='DistSamplerSeedHook'), - visualization=dict(type='SegVisualizationHook')) -launcher = 'pytorch' -work_dir = './work_dirs/mobilenet_deeplab_drone' diff --git a/spaces/SuYuanS/AudioCraft_Plus/tests/quantization/test_vq.py b/spaces/SuYuanS/AudioCraft_Plus/tests/quantization/test_vq.py deleted file mode 100644 index c215099fedacae35c6798fdd9b8420a447aa16bb..0000000000000000000000000000000000000000 --- a/spaces/SuYuanS/AudioCraft_Plus/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/Sultannn/Text_summarization_with-MT5/README.md b/spaces/Sultannn/Text_summarization_with-MT5/README.md deleted file mode 100644 index a9add4ee0402b10e340b4540173cfd6ff0cc34fc..0000000000000000000000000000000000000000 --- a/spaces/Sultannn/Text_summarization_with-MT5/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Text_summarization_with MT5(45 languages) -emoji: 📃 -colorFrom: purple -colorTo: pink -sdk: gradio -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/ImageQt.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/ImageQt.py deleted file mode 100644 index ad607a97b1a84e20a73b5c6b5316d0d8b06f0333..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/ImageQt.py +++ /dev/null @@ -1,229 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# a simple Qt image interface. -# -# history: -# 2006-06-03 fl: created -# 2006-06-04 fl: inherit from QImage instead of wrapping it -# 2006-06-05 fl: removed toimage helper; move string support to ImageQt -# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com) -# -# Copyright (c) 2006 by Secret Labs AB -# Copyright (c) 2006 by Fredrik Lundh -# -# See the README file for information on usage and redistribution. -# - -import sys -from io import BytesIO - -from . import Image -from ._deprecate import deprecate -from ._util import is_path - -qt_versions = [ - ["6", "PyQt6"], - ["side6", "PySide6"], - ["5", "PyQt5"], - ["side2", "PySide2"], -] - -# If a version has already been imported, attempt it first -qt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True) -for qt_version, qt_module in qt_versions: - try: - if qt_module == "PyQt6": - from PyQt6.QtCore import QBuffer, QIODevice - from PyQt6.QtGui import QImage, QPixmap, qRgba - elif qt_module == "PySide6": - from PySide6.QtCore import QBuffer, QIODevice - from PySide6.QtGui import QImage, QPixmap, qRgba - elif qt_module == "PyQt5": - from PyQt5.QtCore import QBuffer, QIODevice - from PyQt5.QtGui import QImage, QPixmap, qRgba - - deprecate("Support for PyQt5", 10, "PyQt6 or PySide6") - elif qt_module == "PySide2": - from PySide2.QtCore import QBuffer, QIODevice - from PySide2.QtGui import QImage, QPixmap, qRgba - - deprecate("Support for PySide2", 10, "PyQt6 or PySide6") - except (ImportError, RuntimeError): - continue - qt_is_installed = True - break -else: - qt_is_installed = False - qt_version = None - - -def rgb(r, g, b, a=255): - """(Internal) Turns an RGB color into a Qt compatible color integer.""" - # use qRgb to pack the colors, and then turn the resulting long - # into a negative integer with the same bitpattern. - return qRgba(r, g, b, a) & 0xFFFFFFFF - - -def fromqimage(im): - """ - :param im: QImage or PIL ImageQt object - """ - buffer = QBuffer() - if qt_version == "6": - try: - qt_openmode = QIODevice.OpenModeFlag - except AttributeError: - qt_openmode = QIODevice.OpenMode - else: - qt_openmode = QIODevice - buffer.open(qt_openmode.ReadWrite) - # preserve alpha channel with png - # otherwise ppm is more friendly with Image.open - if im.hasAlphaChannel(): - im.save(buffer, "png") - else: - im.save(buffer, "ppm") - - b = BytesIO() - b.write(buffer.data()) - buffer.close() - b.seek(0) - - return Image.open(b) - - -def fromqpixmap(im): - return fromqimage(im) - # buffer = QBuffer() - # buffer.open(QIODevice.ReadWrite) - # # im.save(buffer) - # # What if png doesn't support some image features like animation? - # im.save(buffer, 'ppm') - # bytes_io = BytesIO() - # bytes_io.write(buffer.data()) - # buffer.close() - # bytes_io.seek(0) - # return Image.open(bytes_io) - - -def align8to32(bytes, width, mode): - """ - converts each scanline of data from 8 bit to 32 bit aligned - """ - - bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode] - - # calculate bytes per line and the extra padding if needed - bits_per_line = bits_per_pixel * width - full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8) - bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0) - - extra_padding = -bytes_per_line % 4 - - # already 32 bit aligned by luck - if not extra_padding: - return bytes - - new_data = [] - for i in range(len(bytes) // bytes_per_line): - new_data.append( - bytes[i * bytes_per_line : (i + 1) * bytes_per_line] - + b"\x00" * extra_padding - ) - - return b"".join(new_data) - - -def _toqclass_helper(im): - data = None - colortable = None - exclusive_fp = False - - # handle filename, if given instead of image name - if hasattr(im, "toUtf8"): - # FIXME - is this really the best way to do this? - im = str(im.toUtf8(), "utf-8") - if is_path(im): - im = Image.open(im) - exclusive_fp = True - - qt_format = QImage.Format if qt_version == "6" else QImage - if im.mode == "1": - format = qt_format.Format_Mono - elif im.mode == "L": - format = qt_format.Format_Indexed8 - colortable = [] - for i in range(256): - colortable.append(rgb(i, i, i)) - elif im.mode == "P": - format = qt_format.Format_Indexed8 - colortable = [] - palette = im.getpalette() - for i in range(0, len(palette), 3): - colortable.append(rgb(*palette[i : i + 3])) - elif im.mode == "RGB": - # Populate the 4th channel with 255 - im = im.convert("RGBA") - - data = im.tobytes("raw", "BGRA") - format = qt_format.Format_RGB32 - elif im.mode == "RGBA": - data = im.tobytes("raw", "BGRA") - format = qt_format.Format_ARGB32 - elif im.mode == "I;16" and hasattr(qt_format, "Format_Grayscale16"): # Qt 5.13+ - im = im.point(lambda i: i * 256) - - format = qt_format.Format_Grayscale16 - else: - if exclusive_fp: - im.close() - msg = f"unsupported image mode {repr(im.mode)}" - raise ValueError(msg) - - size = im.size - __data = data or align8to32(im.tobytes(), size[0], im.mode) - if exclusive_fp: - im.close() - return {"data": __data, "size": size, "format": format, "colortable": colortable} - - -if qt_is_installed: - - class ImageQt(QImage): - def __init__(self, im): - """ - An PIL image wrapper for Qt. This is a subclass of PyQt's QImage - class. - - :param im: A PIL Image object, or a file name (given either as - Python string or a PyQt string object). - """ - im_data = _toqclass_helper(im) - # must keep a reference, or Qt will crash! - # All QImage constructors that take data operate on an existing - # buffer, so this buffer has to hang on for the life of the image. - # Fixes https://github.com/python-pillow/Pillow/issues/1370 - self.__data = im_data["data"] - super().__init__( - self.__data, - im_data["size"][0], - im_data["size"][1], - im_data["format"], - ) - if im_data["colortable"]: - self.setColorTable(im_data["colortable"]) - - -def toqimage(im): - return ImageQt(im) - - -def toqpixmap(im): - # # This doesn't work. For now using a dumb approach. - # im_data = _toqclass_helper(im) - # result = QPixmap(im_data["size"][0], im_data["size"][1]) - # result.loadFromData(im_data["data"]) - qimage = toqimage(im) - return QPixmap.fromImage(qimage) diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/PSDraw.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/PSDraw.py deleted file mode 100644 index 13b3048f67e18ac58170c3a1bd25cb18d66b30fe..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/PSDraw.py +++ /dev/null @@ -1,229 +0,0 @@ -# -# The Python Imaging Library -# $Id$ -# -# Simple PostScript graphics interface -# -# History: -# 1996-04-20 fl Created -# 1999-01-10 fl Added gsave/grestore to image method -# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge) -# -# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved. -# Copyright (c) 1996 by Fredrik Lundh. -# -# See the README file for information on usage and redistribution. -# - -import sys - -from . import EpsImagePlugin - -## -# Simple PostScript graphics interface. - - -class PSDraw: - """ - Sets up printing to the given file. If ``fp`` is omitted, - ``sys.stdout.buffer`` or ``sys.stdout`` is assumed. - """ - - def __init__(self, fp=None): - if not fp: - try: - fp = sys.stdout.buffer - except AttributeError: - fp = sys.stdout - self.fp = fp - - def begin_document(self, id=None): - """Set up printing of a document. (Write PostScript DSC header.)""" - # FIXME: incomplete - self.fp.write( - b"%!PS-Adobe-3.0\n" - b"save\n" - b"/showpage { } def\n" - b"%%EndComments\n" - b"%%BeginDocument\n" - ) - # self.fp.write(ERROR_PS) # debugging! - self.fp.write(EDROFF_PS) - self.fp.write(VDI_PS) - self.fp.write(b"%%EndProlog\n") - self.isofont = {} - - def end_document(self): - """Ends printing. (Write PostScript DSC footer.)""" - self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n") - if hasattr(self.fp, "flush"): - self.fp.flush() - - def setfont(self, font, size): - """ - Selects which font to use. - - :param font: A PostScript font name - :param size: Size in points. - """ - font = bytes(font, "UTF-8") - if font not in self.isofont: - # reencode font - self.fp.write(b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font, font)) - self.isofont[font] = 1 - # rough - self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font)) - - def line(self, xy0, xy1): - """ - Draws a line between the two points. Coordinates are given in - PostScript point coordinates (72 points per inch, (0, 0) is the lower - left corner of the page). - """ - self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1)) - - def rectangle(self, box): - """ - Draws a rectangle. - - :param box: A tuple of four integers, specifying left, bottom, width and - height. - """ - self.fp.write(b"%d %d M 0 %d %d Vr\n" % box) - - def text(self, xy, text): - """ - Draws text at the given position. You must use - :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method. - """ - text = bytes(text, "UTF-8") - text = b"\\(".join(text.split(b"(")) - text = b"\\)".join(text.split(b")")) - xy += (text,) - self.fp.write(b"%d %d M (%s) S\n" % xy) - - def image(self, box, im, dpi=None): - """Draw a PIL image, centered in the given box.""" - # default resolution depends on mode - if not dpi: - if im.mode == "1": - dpi = 200 # fax - else: - dpi = 100 # greyscale - # image size (on paper) - x = im.size[0] * 72 / dpi - y = im.size[1] * 72 / dpi - # max allowed size - xmax = float(box[2] - box[0]) - ymax = float(box[3] - box[1]) - if x > xmax: - y = y * xmax / x - x = xmax - if y > ymax: - x = x * ymax / y - y = ymax - dx = (xmax - x) / 2 + box[0] - dy = (ymax - y) / 2 + box[1] - self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy)) - if (x, y) != im.size: - # EpsImagePlugin._save prints the image at (0,0,xsize,ysize) - sx = x / im.size[0] - sy = y / im.size[1] - self.fp.write(b"%f %f scale\n" % (sx, sy)) - EpsImagePlugin._save(im, self.fp, None, 0) - self.fp.write(b"\ngrestore\n") - - -# -------------------------------------------------------------------- -# PostScript driver - -# -# EDROFF.PS -- PostScript driver for Edroff 2 -# -# History: -# 94-01-25 fl: created (edroff 2.04) -# -# Copyright (c) Fredrik Lundh 1994. -# - - -EDROFF_PS = b"""\ -/S { show } bind def -/P { moveto show } bind def -/M { moveto } bind def -/X { 0 rmoveto } bind def -/Y { 0 exch rmoveto } bind def -/E { findfont - dup maxlength dict begin - { - 1 index /FID ne { def } { pop pop } ifelse - } forall - /Encoding exch def - dup /FontName exch def - currentdict end definefont pop -} bind def -/F { findfont exch scalefont dup setfont - [ exch /setfont cvx ] cvx bind def -} bind def -""" - -# -# VDI.PS -- PostScript driver for VDI meta commands -# -# History: -# 94-01-25 fl: created (edroff 2.04) -# -# Copyright (c) Fredrik Lundh 1994. -# - -VDI_PS = b"""\ -/Vm { moveto } bind def -/Va { newpath arcn stroke } bind def -/Vl { moveto lineto stroke } bind def -/Vc { newpath 0 360 arc closepath } bind def -/Vr { exch dup 0 rlineto - exch dup 0 exch rlineto - exch neg 0 rlineto - 0 exch neg rlineto - setgray fill } bind def -/Tm matrix def -/Ve { Tm currentmatrix pop - translate scale newpath 0 0 .5 0 360 arc closepath - Tm setmatrix -} bind def -/Vf { currentgray exch setgray fill setgray } bind def -""" - -# -# ERROR.PS -- Error handler -# -# History: -# 89-11-21 fl: created (pslist 1.10) -# - -ERROR_PS = b"""\ -/landscape false def -/errorBUF 200 string def -/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def -errordict begin /handleerror { - initmatrix /Courier findfont 10 scalefont setfont - newpath 72 720 moveto $error begin /newerror false def - (PostScript Error) show errorNL errorNL - (Error: ) show - /errorname load errorBUF cvs show errorNL errorNL - (Command: ) show - /command load dup type /stringtype ne { errorBUF cvs } if show - errorNL errorNL - (VMstatus: ) show - vmstatus errorBUF cvs show ( bytes available, ) show - errorBUF cvs show ( bytes used at level ) show - errorBUF cvs show errorNL errorNL - (Operand stargck: ) show errorNL /ostargck load { - dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL - } forall errorNL - (Execution stargck: ) show errorNL /estargck load { - dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL - } forall - end showpage -} def end -""" diff --git a/spaces/Suniilkumaar/MusicGen-updated/MODEL_CARD.md b/spaces/Suniilkumaar/MusicGen-updated/MODEL_CARD.md deleted file mode 100644 index 6c2c9f883969eb905e74ad3376966d156cc5ca00..0000000000000000000000000000000000000000 --- a/spaces/Suniilkumaar/MusicGen-updated/MODEL_CARD.md +++ /dev/null @@ -1,81 +0,0 @@ -# MusicGen Model Card - -## Model details - -**Organization developing the model:** The FAIR team of Meta AI. - -**Model date:** MusicGen was trained between April 2023 and May 2023. - -**Model version:** This is the version 1 of the model. - -**Model type:** MusicGen consists of an EnCodec model for audio tokenization, an auto-regressive language model based on the transformer architecture for music modeling. The model comes in different sizes: 300M, 1.5B and 3.3B parameters ; and two variants: a model trained for text-to-music generation task and a model trained for melody-guided music generation. - -**Paper or resources for more information:** More information can be found in the paper [Simple and Controllable Music Generation][arxiv]. - -**Citation details** See [our paper][arxiv] - -**License** Code is released under MIT, model weights are released under CC-BY-NC 4.0. - -**Where to send questions or comments about the model:** Questions and comments about MusicGen can be sent via the [Github repository](https://github.com/facebookresearch/audiocraft) of the project, or by opening an issue. - -## Intended use -**Primary intended use:** The primary use of MusicGen is research on AI-based music generation, including: - -- Research efforts, such as probing and better understanding the limitations of generative models to further improve the state of science -- Generation of music guided by text or melody to understand current abilities of generative AI models by machine learning amateurs - -**Primary intended users:** The primary intended users of the model are researchers in audio, machine learning and artificial intelligence, as well as amateur seeking to better understand those models. - -**Out-of-scope use cases** The model should not be used on downstream applications without further risk evaluation and mitigation. The model should not be used to intentionally create or disseminate music pieces that create hostile or alienating environments for people. This includes generating music that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes. - -## Metrics - -**Models performance measures:** We used the following objective measure to evaluate the model on a standard music benchmark: - -- Frechet Audio Distance computed on features extracted from a pre-trained audio classifier (VGGish) -- Kullback-Leibler Divergence on label distributions extracted from a pre-trained audio classifier (PaSST) -- CLAP Score between audio embedding and text embedding extracted from a pre-trained CLAP model - -Additionally, we run qualitative studies with human participants, evaluating the performance of the model with the following axes: - -- Overall quality of the music samples; -- Text relevance to the provided text input; -- Adherence to the melody for melody-guided music generation. - -More details on performance measures and human studies can be found in the paper. - -**Decision thresholds:** Not applicable. - -## Evaluation datasets - -The model was evaluated on the [MusicCaps benchmark](https://www.kaggle.com/datasets/googleai/musiccaps) and on an in-domain held-out evaluation set, with no artist overlap with the training set. - -## Training datasets - -The model was trained on licensed data using the following sources: the [Meta Music Initiative Sound Collection](https://www.fb.com/sound), [Shutterstock music collection](https://www.shutterstock.com/music) and the [Pond5 music collection](https://www.pond5.com/). See the paper for more details about the training set and corresponding preprocessing. - -## Quantitative analysis - -More information can be found in the paper [Simple and Controllable Music Generation][arxiv], in the Experimental Setup section. - -## Limitations and biases - -**Data:** The data sources used to train the model are created by music professionals and covered by legal agreements with the right holders. The model is trained on 20K hours of data, we believe that scaling the model on larger datasets can further improve the performance of the model. - -**Mitigations:** Vocals have been removed from the data source using corresponding tags, and then using using a state-of-the-art music source separation method, namely using the open source [Hybrid Transformer for Music Source Separation](https://github.com/facebookresearch/demucs) (HT-Demucs). - -**Limitations:** - -- The model is not able to generate realistic vocals. -- The model has been trained with English descriptions and will not perform as well in other languages. -- The model does not perform equally well for all music styles and cultures. -- The model sometimes generates end of songs, collapsing to silence. -- It is sometimes difficult to assess what types of text descriptions provide the best generations. Prompt engineering may be required to obtain satisfying results. - -**Biases:** The source of data is potentially lacking diversity and all music cultures are not equally represented in the dataset. The model may not perform equally well on the wide variety of music genres that exists. The generated samples from the model will reflect the biases from the training data. Further work on this model should include methods for balanced and just representations of cultures, for example, by scaling the training data to be both diverse and inclusive. - -**Risks and harms:** Biases and limitations of the model may lead to generation of samples that may be considered as biased, inappropriate or offensive. We believe that providing the code to reproduce the research and train new models will allow to broaden the application to new and more representative data. - -**Use cases:** Users must be aware of the biases, limitations and risks of the model. MusicGen is a model developed for artificial intelligence research on controllable music generation. As such, it should not be used for downstream applications without further investigation and mitigation of risks. - -[arxiv]: https://arxiv.org/abs/2306.05284 diff --git a/spaces/Suniilkumaar/MusicGen-updated/Makefile b/spaces/Suniilkumaar/MusicGen-updated/Makefile deleted file mode 100644 index 5bfd89dd833d7448b21073eb6ee7cfac1d5157dd..0000000000000000000000000000000000000000 --- a/spaces/Suniilkumaar/MusicGen-updated/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -default: linter tests - -install: - pip install -U pip - pip install -U -e '.[dev]' - -linter: - flake8 audiocraft && mypy audiocraft - flake8 tests && mypy tests - -tests: - coverage run -m pytest tests - coverage report --include 'audiocraft/*' - -docs: - pdoc3 --html -o docs -f audiocraft - -dist: - python setup.py sdist - -.PHONY: linter tests docs dist diff --git a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/export/__init__.py b/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/export/__init__.py deleted file mode 100644 index 5a58758f64aae6071fa688be4400622ce6036efa..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/export/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# -*- coding: utf-8 -*- - -import warnings - -from .flatten import TracingAdapter -from .torchscript import dump_torchscript_IR, scripting_with_instances - -try: - from caffe2.proto import caffe2_pb2 as _tmp - from caffe2.python import core - - # caffe2 is optional -except ImportError: - pass -else: - from .api import * - - -# TODO: Update ONNX Opset version and run tests when a newer PyTorch is supported -STABLE_ONNX_OPSET_VERSION = 11 - - -def add_export_config(cfg): - warnings.warn( - "add_export_config has been deprecated and behaves as no-op function.", DeprecationWarning - ) - return cfg - - -__all__ = [k for k in globals().keys() if not k.startswith("_")] diff --git a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/utils/analysis.py b/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/utils/analysis.py deleted file mode 100644 index d63e14bcb6d9582df8a647c9a2ca46f2f7e4cd1d..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/oneformer/detectron2/utils/analysis.py +++ /dev/null @@ -1,188 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -*- coding: utf-8 -*- - -import typing -from typing import Any, List -import fvcore -from fvcore.nn import activation_count, flop_count, parameter_count, parameter_count_table -from torch import nn - -from annotator.oneformer.detectron2.export import TracingAdapter - -__all__ = [ - "activation_count_operators", - "flop_count_operators", - "parameter_count_table", - "parameter_count", - "FlopCountAnalysis", -] - -FLOPS_MODE = "flops" -ACTIVATIONS_MODE = "activations" - - -# Some extra ops to ignore from counting, including elementwise and reduction ops -_IGNORED_OPS = { - "aten::add", - "aten::add_", - "aten::argmax", - "aten::argsort", - "aten::batch_norm", - "aten::constant_pad_nd", - "aten::div", - "aten::div_", - "aten::exp", - "aten::log2", - "aten::max_pool2d", - "aten::meshgrid", - "aten::mul", - "aten::mul_", - "aten::neg", - "aten::nonzero_numpy", - "aten::reciprocal", - "aten::repeat_interleave", - "aten::rsub", - "aten::sigmoid", - "aten::sigmoid_", - "aten::softmax", - "aten::sort", - "aten::sqrt", - "aten::sub", - "torchvision::nms", # TODO estimate flop for nms -} - - -class FlopCountAnalysis(fvcore.nn.FlopCountAnalysis): - """ - Same as :class:`fvcore.nn.FlopCountAnalysis`, but supports detectron2 models. - """ - - def __init__(self, model, inputs): - """ - Args: - model (nn.Module): - inputs (Any): inputs of the given model. Does not have to be tuple of tensors. - """ - wrapper = TracingAdapter(model, inputs, allow_non_tensor=True) - super().__init__(wrapper, wrapper.flattened_inputs) - self.set_op_handle(**{k: None for k in _IGNORED_OPS}) - - -def flop_count_operators(model: nn.Module, inputs: list) -> typing.DefaultDict[str, float]: - """ - Implement operator-level flops counting using jit. - This is a wrapper of :func:`fvcore.nn.flop_count` and adds supports for standard - detection models in detectron2. - Please use :class:`FlopCountAnalysis` for more advanced functionalities. - - Note: - The function runs the input through the model to compute flops. - The flops of a detection model is often input-dependent, for example, - the flops of box & mask head depends on the number of proposals & - the number of detected objects. - Therefore, the flops counting using a single input may not accurately - reflect the computation cost of a model. It's recommended to average - across a number of inputs. - - Args: - model: a detectron2 model that takes `list[dict]` as input. - inputs (list[dict]): inputs to model, in detectron2's standard format. - Only "image" key will be used. - supported_ops (dict[str, Handle]): see documentation of :func:`fvcore.nn.flop_count` - - Returns: - Counter: Gflop count per operator - """ - old_train = model.training - model.eval() - ret = FlopCountAnalysis(model, inputs).by_operator() - model.train(old_train) - return {k: v / 1e9 for k, v in ret.items()} - - -def activation_count_operators( - model: nn.Module, inputs: list, **kwargs -) -> typing.DefaultDict[str, float]: - """ - Implement operator-level activations counting using jit. - This is a wrapper of fvcore.nn.activation_count, that supports standard detection models - in detectron2. - - Note: - The function runs the input through the model to compute activations. - The activations of a detection model is often input-dependent, for example, - the activations of box & mask head depends on the number of proposals & - the number of detected objects. - - Args: - model: a detectron2 model that takes `list[dict]` as input. - inputs (list[dict]): inputs to model, in detectron2's standard format. - Only "image" key will be used. - - Returns: - Counter: activation count per operator - """ - return _wrapper_count_operators(model=model, inputs=inputs, mode=ACTIVATIONS_MODE, **kwargs) - - -def _wrapper_count_operators( - model: nn.Module, inputs: list, mode: str, **kwargs -) -> typing.DefaultDict[str, float]: - # ignore some ops - supported_ops = {k: lambda *args, **kwargs: {} for k in _IGNORED_OPS} - supported_ops.update(kwargs.pop("supported_ops", {})) - kwargs["supported_ops"] = supported_ops - - assert len(inputs) == 1, "Please use batch size=1" - tensor_input = inputs[0]["image"] - inputs = [{"image": tensor_input}] # remove other keys, in case there are any - - old_train = model.training - if isinstance(model, (nn.parallel.distributed.DistributedDataParallel, nn.DataParallel)): - model = model.module - wrapper = TracingAdapter(model, inputs) - wrapper.eval() - if mode == FLOPS_MODE: - ret = flop_count(wrapper, (tensor_input,), **kwargs) - elif mode == ACTIVATIONS_MODE: - ret = activation_count(wrapper, (tensor_input,), **kwargs) - else: - raise NotImplementedError("Count for mode {} is not supported yet.".format(mode)) - # compatible with change in fvcore - if isinstance(ret, tuple): - ret = ret[0] - model.train(old_train) - return ret - - -def find_unused_parameters(model: nn.Module, inputs: Any) -> List[str]: - """ - Given a model, find parameters that do not contribute - to the loss. - - Args: - model: a model in training mode that returns losses - inputs: argument or a tuple of arguments. Inputs of the model - - Returns: - list[str]: the name of unused parameters - """ - assert model.training - for _, prm in model.named_parameters(): - prm.grad = None - - if isinstance(inputs, tuple): - losses = model(*inputs) - else: - losses = model(inputs) - - if isinstance(losses, dict): - losses = sum(losses.values()) - losses.backward() - - unused: List[str] = [] - for name, prm in model.named_parameters(): - if prm.grad is None: - unused.append(name) - prm.grad = None - return unused diff --git a/spaces/TFanon/TFanon/Dockerfile b/spaces/TFanon/TFanon/Dockerfile deleted file mode 100644 index eef259fa372a804549fb0af0913718a13344da34..0000000000000000000000000000000000000000 --- a/spaces/TFanon/TFanon/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:18-bullseye-slim -RUN apt-get update && \ - apt-get install -y git -RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app -WORKDIR /app -RUN npm install -COPY Dockerfile greeting.md* .env* ./ -RUN npm run build -EXPOSE 7860 -ENV NODE_ENV=production -CMD [ "npm", "start" ] diff --git a/spaces/TH5314/newbing/cloudflare/worker.js b/spaces/TH5314/newbing/cloudflare/worker.js deleted file mode 100644 index 7e0c8e17e2b428fb30be0bc9b5539a3a1b9b8563..0000000000000000000000000000000000000000 --- a/spaces/TH5314/newbing/cloudflare/worker.js +++ /dev/null @@ -1,18 +0,0 @@ -const TRAGET_HOST='vip.thchatai.website' // 请将此域名改成你自己的,域名信息在设置》站点域名查看。 - -export default { - async fetch(request) { - const uri = new URL(request.url); - if (uri.protocol === 'http:') { - uri.protocol = 'https:'; - return new Response('', { - status: 301, - headers: { - location: uri.toString(), - }, - }) - } - uri.host = TRAGET_HOST - return fetch(new Request(uri.toString(), request)); - }, -}; diff --git a/spaces/TabPFN/TabPFNPrediction/TabPFN/priors/utils.py b/spaces/TabPFN/TabPFNPrediction/TabPFN/priors/utils.py deleted file mode 100644 index 58408d3dafd54d9e0aea8b7d24a0197e7e54de44..0000000000000000000000000000000000000000 --- a/spaces/TabPFN/TabPFNPrediction/TabPFN/priors/utils.py +++ /dev/null @@ -1,174 +0,0 @@ -import random - -import torch -import seaborn as sns - -from utils import set_locals_in_self -from .prior import PriorDataLoader -from torch import nn -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.gridspec as gridspec -import scipy.stats as stats -import math - -def get_batch_to_dataloader(get_batch_method_): - class DL(PriorDataLoader): - get_batch_method = get_batch_method_ - - # Caution, you might need to set self.num_features manually if it is not part of the args. - def __init__(self, num_steps, **get_batch_kwargs): - set_locals_in_self(locals()) - - # The stuff outside the or is set as class attribute before instantiation. - self.num_features = get_batch_kwargs.get('num_features') or self.num_features - self.epoch_count = 0 - print('DataLoader.__dict__', self.__dict__) - - @staticmethod - def gbm(*args, eval_pos_seq_len_sampler, **kwargs): - kwargs['single_eval_pos'], kwargs['seq_len'] = eval_pos_seq_len_sampler() - # Scales the batch size dynamically with the power of 'dynamic_batch_size'. - # A transformer with quadratic memory usage in the seq len would need a power of 2 to keep memory constant. - if 'dynamic_batch_size' in kwargs and kwargs['dynamic_batch_size'] > 0 and kwargs['dynamic_batch_size']: - kwargs['batch_size'] = kwargs['batch_size'] * math.floor(math.pow(kwargs['seq_len_maximum'], kwargs['dynamic_batch_size']) / math.pow(kwargs['seq_len'], kwargs['dynamic_batch_size'])) - batch = get_batch_method_(*args, **kwargs) - x, y, target_y, style = batch if len(batch) == 4 else (batch[0], batch[1], batch[2], None) - return (style, x, y), target_y, kwargs['single_eval_pos'] - - def __len__(self): - return self.num_steps - - def get_test_batch(self): # does not increase epoch_count - return self.gbm(**self.get_batch_kwargs, epoch=self.epoch_count, model=self.model if hasattr(self, 'model') else None) - - def __iter__(self): - assert hasattr(self, 'model'), "Please assign model with `dl.model = ...` before training." - self.epoch_count += 1 - return iter(self.gbm(**self.get_batch_kwargs, epoch=self.epoch_count - 1, model=self.model) for _ in range(self.num_steps)) - - return DL - -def plot_features(data, targets, fig=None, categorical=True): - if torch.is_tensor(data): - data = data.detach().cpu().numpy() - targets = targets.detach().cpu().numpy() - #data = np.concatenate([data, np.expand_dims(targets, -1)], -1) - #df = pd.DataFrame(data, columns=list(range(0, data.shape[1]))) - #g = sns.pairplot(df, hue=data.shape[1]-1, palette="Set2", diag_kind="kde", height=2.5) - #plt.legend([], [], frameon=False) - #g._legend.remove() - #g = sns.PairGrid(df, hue=data.shape[1]-1) - #g.map_diag(sns.histplot) - #g.map_offdiag(sns.scatterplot) - #g._legend.remove() - - fig2 = fig if fig else plt.figure(figsize=(8, 8)) - spec2 = gridspec.GridSpec(ncols=data.shape[1], nrows=data.shape[1], figure=fig2) - for d in range(0, data.shape[1]): - for d2 in range(0, data.shape[1]): - if d > d2: - continue - sub_ax = fig2.add_subplot(spec2[d, d2]) - sub_ax.set_xticks([]) - sub_ax.set_yticks([]) - if d == d2: - if categorical: - sns.kdeplot(data[:, d],hue=targets[:],ax=sub_ax,legend=False, palette="deep") - else: - sns.kdeplot(data[:, d], ax=sub_ax, legend=False) - sub_ax.set(ylabel=None) - else: - if categorical: - sns.scatterplot(x=data[:, d], y=data[:, d2], - hue=targets[:],legend=False, palette="deep") - else: - sns.scatterplot(x=data[:, d], y=data[:, d2], - hue=targets[:], legend=False) - #plt.scatter(data[:, d], data[:, d2], - # c=targets[:]) - #sub_ax.get_xaxis().set_ticks([]) - #sub_ax.get_yaxis().set_ticks([]) - plt.subplots_adjust(wspace=0.05, hspace=0.05) - fig2.show() - - -def plot_prior(prior): - s = np.array([prior() for _ in range(0, 1000)]) - count, bins, ignored = plt.hist(s, 50, density=True) - print(s.min()) - plt.show() - -trunc_norm_sampler_f = lambda mu, sigma : lambda: stats.truncnorm((0 - mu) / sigma, (1000000 - mu) / sigma, loc=mu, scale=sigma).rvs(1)[0] -beta_sampler_f = lambda a, b : lambda : np.random.beta(a, b) -gamma_sampler_f = lambda a, b : lambda : np.random.gamma(a, b) -uniform_sampler_f = lambda a, b : lambda : np.random.uniform(a, b) -uniform_int_sampler_f = lambda a, b : lambda : round(np.random.uniform(a, b)) -def zipf_sampler_f(a, b, c): - x = np.arange(b, c) - weights = x ** (-a) - weights /= weights.sum() - return lambda : stats.rv_discrete(name='bounded_zipf', values=(x, weights)).rvs(1) -scaled_beta_sampler_f = lambda a, b, scale, minimum : lambda : minimum + round(beta_sampler_f(a, b)() * (scale - minimum)) - - -def normalize_by_used_features_f(x, num_features_used, num_features, normalize_with_sqrt=False): - if normalize_with_sqrt: - return x / (num_features_used / num_features)**(1 / 2) - return x / (num_features_used / num_features) - - -def order_by_y(x, y): - order = torch.argsort(y if random.randint(0, 1) else -y, dim=0)[:, 0, 0] - order = order.reshape(2, -1).transpose(0, 1).reshape(-1)#.reshape(seq_len) - x = x[order] # .reshape(2, -1).transpose(0, 1).reshape(-1).flip([0]).reshape(seq_len, 1, -1) - y = y[order] # .reshape(2, -1).transpose(0, 1).reshape(-1).reshape(seq_len, 1, -1) - - return x, y - -def randomize_classes(x, num_classes): - classes = torch.arange(0, num_classes, device=x.device) - random_classes = torch.randperm(num_classes, device=x.device).type(x.type()) - x = ((x.unsqueeze(-1) == classes) * random_classes).sum(-1) - return x - - -class CategoricalActivation(nn.Module): - def __init__(self, categorical_p=0.1, ordered_p=0.7 - , keep_activation_size=False - , num_classes_sampler=zipf_sampler_f(0.8, 1, 10)): - self.categorical_p = categorical_p - self.ordered_p = ordered_p - self.keep_activation_size = keep_activation_size - self.num_classes_sampler = num_classes_sampler - - super().__init__() - - def forward(self, x): - # x shape: T, B, H - - x = nn.Softsign()(x) - - num_classes = self.num_classes_sampler() - hid_strength = torch.abs(x).mean(0).unsqueeze(0) if self.keep_activation_size else None - - categorical_classes = torch.rand((x.shape[1], x.shape[2])) < self.categorical_p - class_boundaries = torch.zeros((num_classes - 1, x.shape[1], x.shape[2]), device=x.device, dtype=x.dtype) - # Sample a different index for each hidden dimension, but shared for all batches - for b in range(x.shape[1]): - for h in range(x.shape[2]): - ind = torch.randint(0, x.shape[0], (num_classes - 1,)) - class_boundaries[:, b, h] = x[ind, b, h] - - for b in range(x.shape[1]): - x_rel = x[:, b, categorical_classes[b]] - boundaries_rel = class_boundaries[:, b, categorical_classes[b]].unsqueeze(1) - x[:, b, categorical_classes[b]] = (x_rel > boundaries_rel).sum(dim=0).float() - num_classes / 2 - - ordered_classes = torch.rand((x.shape[1],x.shape[2])) < self.ordered_p - ordered_classes = torch.logical_and(ordered_classes, categorical_classes) - x[:, ordered_classes] = randomize_classes(x[:, ordered_classes], num_classes) - - x = x * hid_strength if self.keep_activation_size else x - - return x diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pkg_resources/_vendor/importlib_resources/readers.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pkg_resources/_vendor/importlib_resources/readers.py deleted file mode 100644 index ab34db74091c8a04ee9004ce9a786de3146ec917..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pkg_resources/_vendor/importlib_resources/readers.py +++ /dev/null @@ -1,120 +0,0 @@ -import collections -import pathlib -import operator - -from . import abc - -from ._itertools import unique_everseen -from ._compat import ZipPath - - -def remove_duplicates(items): - return iter(collections.OrderedDict.fromkeys(items)) - - -class FileReader(abc.TraversableResources): - def __init__(self, loader): - self.path = pathlib.Path(loader.path).parent - - def resource_path(self, resource): - """ - Return the file system path to prevent - `resources.path()` from creating a temporary - copy. - """ - return str(self.path.joinpath(resource)) - - def files(self): - return self.path - - -class ZipReader(abc.TraversableResources): - def __init__(self, loader, module): - _, _, name = module.rpartition('.') - self.prefix = loader.prefix.replace('\\', '/') + name + '/' - self.archive = loader.archive - - def open_resource(self, resource): - try: - return super().open_resource(resource) - except KeyError as exc: - raise FileNotFoundError(exc.args[0]) - - def is_resource(self, path): - # workaround for `zipfile.Path.is_file` returning true - # for non-existent paths. - target = self.files().joinpath(path) - return target.is_file() and target.exists() - - def files(self): - return ZipPath(self.archive, self.prefix) - - -class MultiplexedPath(abc.Traversable): - """ - Given a series of Traversable objects, implement a merged - version of the interface across all objects. Useful for - namespace packages which may be multihomed at a single - name. - """ - - def __init__(self, *paths): - self._paths = list(map(pathlib.Path, remove_duplicates(paths))) - if not self._paths: - message = 'MultiplexedPath must contain at least one path' - raise FileNotFoundError(message) - if not all(path.is_dir() for path in self._paths): - raise NotADirectoryError('MultiplexedPath only supports directories') - - def iterdir(self): - files = (file for path in self._paths for file in path.iterdir()) - return unique_everseen(files, key=operator.attrgetter('name')) - - def read_bytes(self): - raise FileNotFoundError(f'{self} is not a file') - - def read_text(self, *args, **kwargs): - raise FileNotFoundError(f'{self} is not a file') - - def is_dir(self): - return True - - def is_file(self): - return False - - def joinpath(self, *descendants): - try: - return super().joinpath(*descendants) - except abc.TraversalError: - # One of the paths did not resolve (a directory does not exist). - # Just return something that will not exist. - return self._paths[0].joinpath(*descendants) - - def open(self, *args, **kwargs): - raise FileNotFoundError(f'{self} is not a file') - - @property - def name(self): - return self._paths[0].name - - def __repr__(self): - paths = ', '.join(f"'{path}'" for path in self._paths) - return f'MultiplexedPath({paths})' - - -class NamespaceReader(abc.TraversableResources): - def __init__(self, namespace_path): - if 'NamespacePath' not in str(namespace_path): - raise ValueError('Invalid path') - self.path = MultiplexedPath(*list(namespace_path)) - - def resource_path(self, resource): - """ - Return the file system path to prevent - `resources.path()` from creating a temporary - copy. - """ - return str(self.path.joinpath(resource)) - - def files(self): - return self.path diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_distutils/dist.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_distutils/dist.py deleted file mode 100644 index 7c0f0e5b78c0451711d7225481e1d3c9160e37fe..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_distutils/dist.py +++ /dev/null @@ -1,1287 +0,0 @@ -"""distutils.dist - -Provides the Distribution class, which represents the module distribution -being built/installed/distributed. -""" - -import sys -import os -import re -import pathlib -import contextlib -import logging -from email import message_from_file - -try: - import warnings -except ImportError: - warnings = None - -from .errors import ( - DistutilsOptionError, - DistutilsModuleError, - DistutilsArgError, - DistutilsClassError, -) -from .fancy_getopt import FancyGetopt, translate_longopt -from .util import check_environ, strtobool, rfc822_escape -from ._log import log -from .debug import DEBUG - -# Regex to define acceptable Distutils command names. This is not *quite* -# the same as a Python NAME -- I don't allow leading underscores. The fact -# that they're very similar is no coincidence; the default naming scheme is -# to look for a Python module named after the command. -command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$') - - -def _ensure_list(value, fieldname): - if isinstance(value, str): - # a string containing comma separated values is okay. It will - # be converted to a list by Distribution.finalize_options(). - pass - elif not isinstance(value, list): - # passing a tuple or an iterator perhaps, warn and convert - typename = type(value).__name__ - msg = "Warning: '{fieldname}' should be a list, got type '{typename}'" - msg = msg.format(**locals()) - log.warning(msg) - value = list(value) - return value - - -class Distribution: - """The core of the Distutils. Most of the work hiding behind 'setup' - is really done within a Distribution instance, which farms the work out - to the Distutils commands specified on the command line. - - Setup scripts will almost never instantiate Distribution directly, - unless the 'setup()' function is totally inadequate to their needs. - However, it is conceivable that a setup script might wish to subclass - Distribution for some specialized purpose, and then pass the subclass - to 'setup()' as the 'distclass' keyword argument. If so, it is - necessary to respect the expectations that 'setup' has of Distribution. - See the code for 'setup()', in core.py, for details. - """ - - # 'global_options' describes the command-line options that may be - # supplied to the setup script prior to any actual commands. - # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of - # these global options. This list should be kept to a bare minimum, - # since every global option is also valid as a command option -- and we - # don't want to pollute the commands with too many options that they - # have minimal control over. - # The fourth entry for verbose means that it can be repeated. - global_options = [ - ('verbose', 'v', "run verbosely (default)", 1), - ('quiet', 'q', "run quietly (turns verbosity off)"), - ('dry-run', 'n', "don't actually do anything"), - ('help', 'h', "show detailed help message"), - ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'), - ] - - # 'common_usage' is a short (2-3 line) string describing the common - # usage of the setup script. - common_usage = """\ -Common commands: (see '--help-commands' for more) - - setup.py build will build the package underneath 'build/' - setup.py install will install the package -""" - - # options that are not propagated to the commands - display_options = [ - ('help-commands', None, "list all available commands"), - ('name', None, "print package name"), - ('version', 'V', "print package version"), - ('fullname', None, "print -"), - ('author', None, "print the author's name"), - ('author-email', None, "print the author's email address"), - ('maintainer', None, "print the maintainer's name"), - ('maintainer-email', None, "print the maintainer's email address"), - ('contact', None, "print the maintainer's name if known, else the author's"), - ( - 'contact-email', - None, - "print the maintainer's email address if known, else the author's", - ), - ('url', None, "print the URL for this package"), - ('license', None, "print the license of the package"), - ('licence', None, "alias for --license"), - ('description', None, "print the package description"), - ('long-description', None, "print the long package description"), - ('platforms', None, "print the list of platforms"), - ('classifiers', None, "print the list of classifiers"), - ('keywords', None, "print the list of keywords"), - ('provides', None, "print the list of packages/modules provided"), - ('requires', None, "print the list of packages/modules required"), - ('obsoletes', None, "print the list of packages/modules made obsolete"), - ] - display_option_names = [translate_longopt(x[0]) for x in display_options] - - # negative options are options that exclude other options - negative_opt = {'quiet': 'verbose'} - - # -- Creation/initialization methods ------------------------------- - - def __init__(self, attrs=None): # noqa: C901 - """Construct a new Distribution instance: initialize all the - attributes of a Distribution, and then use 'attrs' (a dictionary - mapping attribute names to values) to assign some of those - attributes their "real" values. (Any attributes not mentioned in - 'attrs' will be assigned to some null value: 0, None, an empty list - or dictionary, etc.) Most importantly, initialize the - 'command_obj' attribute to the empty dictionary; this will be - filled in with real command objects by 'parse_command_line()'. - """ - - # Default values for our command-line options - self.verbose = 1 - self.dry_run = 0 - self.help = 0 - for attr in self.display_option_names: - setattr(self, attr, 0) - - # Store the distribution meta-data (name, version, author, and so - # forth) in a separate object -- we're getting to have enough - # information here (and enough command-line options) that it's - # worth it. Also delegate 'get_XXX()' methods to the 'metadata' - # object in a sneaky and underhanded (but efficient!) way. - self.metadata = DistributionMetadata() - for basename in self.metadata._METHOD_BASENAMES: - method_name = "get_" + basename - setattr(self, method_name, getattr(self.metadata, method_name)) - - # 'cmdclass' maps command names to class objects, so we - # can 1) quickly figure out which class to instantiate when - # we need to create a new command object, and 2) have a way - # for the setup script to override command classes - self.cmdclass = {} - - # 'command_packages' is a list of packages in which commands - # are searched for. The factory for command 'foo' is expected - # to be named 'foo' in the module 'foo' in one of the packages - # named here. This list is searched from the left; an error - # is raised if no named package provides the command being - # searched for. (Always access using get_command_packages().) - self.command_packages = None - - # 'script_name' and 'script_args' are usually set to sys.argv[0] - # and sys.argv[1:], but they can be overridden when the caller is - # not necessarily a setup script run from the command-line. - self.script_name = None - self.script_args = None - - # 'command_options' is where we store command options between - # parsing them (from config files, the command-line, etc.) and when - # they are actually needed -- ie. when the command in question is - # instantiated. It is a dictionary of dictionaries of 2-tuples: - # command_options = { command_name : { option : (source, value) } } - self.command_options = {} - - # 'dist_files' is the list of (command, pyversion, file) that - # have been created by any dist commands run so far. This is - # filled regardless of whether the run is dry or not. pyversion - # gives sysconfig.get_python_version() if the dist file is - # specific to a Python version, 'any' if it is good for all - # Python versions on the target platform, and '' for a source - # file. pyversion should not be used to specify minimum or - # maximum required Python versions; use the metainfo for that - # instead. - self.dist_files = [] - - # These options are really the business of various commands, rather - # than of the Distribution itself. We provide aliases for them in - # Distribution as a convenience to the developer. - self.packages = None - self.package_data = {} - self.package_dir = None - self.py_modules = None - self.libraries = None - self.headers = None - self.ext_modules = None - self.ext_package = None - self.include_dirs = None - self.extra_path = None - self.scripts = None - self.data_files = None - self.password = '' - - # And now initialize bookkeeping stuff that can't be supplied by - # the caller at all. 'command_obj' maps command names to - # Command instances -- that's how we enforce that every command - # class is a singleton. - self.command_obj = {} - - # 'have_run' maps command names to boolean values; it keeps track - # of whether we have actually run a particular command, to make it - # cheap to "run" a command whenever we think we might need to -- if - # it's already been done, no need for expensive filesystem - # operations, we just check the 'have_run' dictionary and carry on. - # It's only safe to query 'have_run' for a command class that has - # been instantiated -- a false value will be inserted when the - # command object is created, and replaced with a true value when - # the command is successfully run. Thus it's probably best to use - # '.get()' rather than a straight lookup. - self.have_run = {} - - # Now we'll use the attrs dictionary (ultimately, keyword args from - # the setup script) to possibly override any or all of these - # distribution options. - - if attrs: - # Pull out the set of command options and work on them - # specifically. Note that this order guarantees that aliased - # command options will override any supplied redundantly - # through the general options dictionary. - options = attrs.get('options') - if options is not None: - del attrs['options'] - for command, cmd_options in options.items(): - opt_dict = self.get_option_dict(command) - for opt, val in cmd_options.items(): - opt_dict[opt] = ("setup script", val) - - if 'licence' in attrs: - attrs['license'] = attrs['licence'] - del attrs['licence'] - msg = "'licence' distribution option is deprecated; use 'license'" - if warnings is not None: - warnings.warn(msg) - else: - sys.stderr.write(msg + "\n") - - # Now work on the rest of the attributes. Any attribute that's - # not already defined is invalid! - for key, val in attrs.items(): - if hasattr(self.metadata, "set_" + key): - getattr(self.metadata, "set_" + key)(val) - elif hasattr(self.metadata, key): - setattr(self.metadata, key, val) - elif hasattr(self, key): - setattr(self, key, val) - else: - msg = "Unknown distribution option: %s" % repr(key) - warnings.warn(msg) - - # no-user-cfg is handled before other command line args - # because other args override the config files, and this - # one is needed before we can load the config files. - # If attrs['script_args'] wasn't passed, assume false. - # - # This also make sure we just look at the global options - self.want_user_cfg = True - - if self.script_args is not None: - for arg in self.script_args: - if not arg.startswith('-'): - break - if arg == '--no-user-cfg': - self.want_user_cfg = False - break - - self.finalize_options() - - def get_option_dict(self, command): - """Get the option dictionary for a given command. If that - command's option dictionary hasn't been created yet, then create it - and return the new dictionary; otherwise, return the existing - option dictionary. - """ - dict = self.command_options.get(command) - if dict is None: - dict = self.command_options[command] = {} - return dict - - def dump_option_dicts(self, header=None, commands=None, indent=""): - from pprint import pformat - - if commands is None: # dump all command option dicts - commands = sorted(self.command_options.keys()) - - if header is not None: - self.announce(indent + header) - indent = indent + " " - - if not commands: - self.announce(indent + "no commands known yet") - return - - for cmd_name in commands: - opt_dict = self.command_options.get(cmd_name) - if opt_dict is None: - self.announce(indent + "no option dict for '%s' command" % cmd_name) - else: - self.announce(indent + "option dict for '%s' command:" % cmd_name) - out = pformat(opt_dict) - for line in out.split('\n'): - self.announce(indent + " " + line) - - # -- Config file finding/parsing methods --------------------------- - - def find_config_files(self): - """Find as many configuration files as should be processed for this - platform, and return a list of filenames in the order in which they - should be parsed. The filenames returned are guaranteed to exist - (modulo nasty race conditions). - - There are multiple possible config files: - - distutils.cfg in the Distutils installation directory (i.e. - where the top-level Distutils __inst__.py file lives) - - a file in the user's home directory named .pydistutils.cfg - on Unix and pydistutils.cfg on Windows/Mac; may be disabled - with the ``--no-user-cfg`` option - - setup.cfg in the current directory - - a file named by an environment variable - """ - check_environ() - files = [str(path) for path in self._gen_paths() if os.path.isfile(path)] - - if DEBUG: - self.announce("using config files: %s" % ', '.join(files)) - - return files - - def _gen_paths(self): - # The system-wide Distutils config file - sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent - yield sys_dir / "distutils.cfg" - - # The per-user config file - prefix = '.' * (os.name == 'posix') - filename = prefix + 'pydistutils.cfg' - if self.want_user_cfg: - yield pathlib.Path('~').expanduser() / filename - - # All platforms support local setup.cfg - yield pathlib.Path('setup.cfg') - - # Additional config indicated in the environment - with contextlib.suppress(TypeError): - yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG")) - - def parse_config_files(self, filenames=None): # noqa: C901 - from configparser import ConfigParser - - # Ignore install directory options if we have a venv - if sys.prefix != sys.base_prefix: - ignore_options = [ - 'install-base', - 'install-platbase', - 'install-lib', - 'install-platlib', - 'install-purelib', - 'install-headers', - 'install-scripts', - 'install-data', - 'prefix', - 'exec-prefix', - 'home', - 'user', - 'root', - ] - else: - ignore_options = [] - - ignore_options = frozenset(ignore_options) - - if filenames is None: - filenames = self.find_config_files() - - if DEBUG: - self.announce("Distribution.parse_config_files():") - - parser = ConfigParser() - for filename in filenames: - if DEBUG: - self.announce(" reading %s" % filename) - parser.read(filename) - for section in parser.sections(): - options = parser.options(section) - opt_dict = self.get_option_dict(section) - - for opt in options: - if opt != '__name__' and opt not in ignore_options: - val = parser.get(section, opt) - opt = opt.replace('-', '_') - opt_dict[opt] = (filename, val) - - # Make the ConfigParser forget everything (so we retain - # the original filenames that options come from) - parser.__init__() - - # If there was a "global" section in the config file, use it - # to set Distribution options. - - if 'global' in self.command_options: - for opt, (src, val) in self.command_options['global'].items(): - alias = self.negative_opt.get(opt) - try: - if alias: - setattr(self, alias, not strtobool(val)) - elif opt in ('verbose', 'dry_run'): # ugh! - setattr(self, opt, strtobool(val)) - else: - setattr(self, opt, val) - except ValueError as msg: - raise DistutilsOptionError(msg) - - # -- Command-line parsing methods ---------------------------------- - - def parse_command_line(self): - """Parse the setup script's command line, taken from the - 'script_args' instance attribute (which defaults to 'sys.argv[1:]' - -- see 'setup()' in core.py). This list is first processed for - "global options" -- options that set attributes of the Distribution - instance. Then, it is alternately scanned for Distutils commands - and options for that command. Each new command terminates the - options for the previous command. The allowed options for a - command are determined by the 'user_options' attribute of the - command class -- thus, we have to be able to load command classes - in order to parse the command line. Any error in that 'options' - attribute raises DistutilsGetoptError; any error on the - command-line raises DistutilsArgError. If no Distutils commands - were found on the command line, raises DistutilsArgError. Return - true if command-line was successfully parsed and we should carry - on with executing commands; false if no errors but we shouldn't - execute commands (currently, this only happens if user asks for - help). - """ - # - # We now have enough information to show the Macintosh dialog - # that allows the user to interactively specify the "command line". - # - toplevel_options = self._get_toplevel_options() - - # We have to parse the command line a bit at a time -- global - # options, then the first command, then its options, and so on -- - # because each command will be handled by a different class, and - # the options that are valid for a particular class aren't known - # until we have loaded the command class, which doesn't happen - # until we know what the command is. - - self.commands = [] - parser = FancyGetopt(toplevel_options + self.display_options) - parser.set_negative_aliases(self.negative_opt) - parser.set_aliases({'licence': 'license'}) - args = parser.getopt(args=self.script_args, object=self) - option_order = parser.get_option_order() - logging.getLogger().setLevel(logging.WARN - 10 * self.verbose) - - # for display options we return immediately - if self.handle_display_options(option_order): - return - while args: - args = self._parse_command_opts(parser, args) - if args is None: # user asked for help (and got it) - return - - # Handle the cases of --help as a "global" option, ie. - # "setup.py --help" and "setup.py --help command ...". For the - # former, we show global options (--verbose, --dry-run, etc.) - # and display-only options (--name, --version, etc.); for the - # latter, we omit the display-only options and show help for - # each command listed on the command line. - if self.help: - self._show_help( - parser, display_options=len(self.commands) == 0, commands=self.commands - ) - return - - # Oops, no commands found -- an end-user error - if not self.commands: - raise DistutilsArgError("no commands supplied") - - # All is well: return true - return True - - def _get_toplevel_options(self): - """Return the non-display options recognized at the top level. - - This includes options that are recognized *only* at the top - level as well as options recognized for commands. - """ - return self.global_options + [ - ( - "command-packages=", - None, - "list of packages that provide distutils commands", - ), - ] - - def _parse_command_opts(self, parser, args): # noqa: C901 - """Parse the command-line options for a single command. - 'parser' must be a FancyGetopt instance; 'args' must be the list - of arguments, starting with the current command (whose options - we are about to parse). Returns a new version of 'args' with - the next command at the front of the list; will be the empty - list if there are no more commands on the command line. Returns - None if the user asked for help on this command. - """ - # late import because of mutual dependence between these modules - from distutils.cmd import Command - - # Pull the current command from the head of the command line - command = args[0] - if not command_re.match(command): - raise SystemExit("invalid command name '%s'" % command) - self.commands.append(command) - - # Dig up the command class that implements this command, so we - # 1) know that it's a valid command, and 2) know which options - # it takes. - try: - cmd_class = self.get_command_class(command) - except DistutilsModuleError as msg: - raise DistutilsArgError(msg) - - # Require that the command class be derived from Command -- want - # to be sure that the basic "command" interface is implemented. - if not issubclass(cmd_class, Command): - raise DistutilsClassError( - "command class %s must subclass Command" % cmd_class - ) - - # Also make sure that the command object provides a list of its - # known options. - if not ( - hasattr(cmd_class, 'user_options') - and isinstance(cmd_class.user_options, list) - ): - msg = ( - "command class %s must provide " - "'user_options' attribute (a list of tuples)" - ) - raise DistutilsClassError(msg % cmd_class) - - # If the command class has a list of negative alias options, - # merge it in with the global negative aliases. - negative_opt = self.negative_opt - if hasattr(cmd_class, 'negative_opt'): - negative_opt = negative_opt.copy() - negative_opt.update(cmd_class.negative_opt) - - # Check for help_options in command class. They have a different - # format (tuple of four) so we need to preprocess them here. - if hasattr(cmd_class, 'help_options') and isinstance( - cmd_class.help_options, list - ): - help_options = fix_help_options(cmd_class.help_options) - else: - help_options = [] - - # All commands support the global options too, just by adding - # in 'global_options'. - parser.set_option_table( - self.global_options + cmd_class.user_options + help_options - ) - parser.set_negative_aliases(negative_opt) - (args, opts) = parser.getopt(args[1:]) - if hasattr(opts, 'help') and opts.help: - self._show_help(parser, display_options=0, commands=[cmd_class]) - return - - if hasattr(cmd_class, 'help_options') and isinstance( - cmd_class.help_options, list - ): - help_option_found = 0 - for help_option, short, desc, func in cmd_class.help_options: - if hasattr(opts, parser.get_attr_name(help_option)): - help_option_found = 1 - if callable(func): - func() - else: - raise DistutilsClassError( - "invalid help function %r for help option '%s': " - "must be a callable object (function, etc.)" - % (func, help_option) - ) - - if help_option_found: - return - - # Put the options from the command-line into their official - # holding pen, the 'command_options' dictionary. - opt_dict = self.get_option_dict(command) - for name, value in vars(opts).items(): - opt_dict[name] = ("command line", value) - - return args - - def finalize_options(self): - """Set final values for all the options on the Distribution - instance, analogous to the .finalize_options() method of Command - objects. - """ - for attr in ('keywords', 'platforms'): - value = getattr(self.metadata, attr) - if value is None: - continue - if isinstance(value, str): - value = [elm.strip() for elm in value.split(',')] - setattr(self.metadata, attr, value) - - def _show_help(self, parser, global_options=1, display_options=1, commands=[]): - """Show help for the setup script command-line in the form of - several lists of command-line options. 'parser' should be a - FancyGetopt instance; do not expect it to be returned in the - same state, as its option table will be reset to make it - generate the correct help text. - - If 'global_options' is true, lists the global options: - --verbose, --dry-run, etc. If 'display_options' is true, lists - the "display-only" options: --name, --version, etc. Finally, - lists per-command help for every command name or command class - in 'commands'. - """ - # late import because of mutual dependence between these modules - from distutils.core import gen_usage - from distutils.cmd import Command - - if global_options: - if display_options: - options = self._get_toplevel_options() - else: - options = self.global_options - parser.set_option_table(options) - parser.print_help(self.common_usage + "\nGlobal options:") - print('') - - if display_options: - parser.set_option_table(self.display_options) - parser.print_help( - "Information display options (just display " - + "information, ignore any commands)" - ) - print('') - - for command in self.commands: - if isinstance(command, type) and issubclass(command, Command): - klass = command - else: - klass = self.get_command_class(command) - if hasattr(klass, 'help_options') and isinstance(klass.help_options, list): - parser.set_option_table( - klass.user_options + fix_help_options(klass.help_options) - ) - else: - parser.set_option_table(klass.user_options) - parser.print_help("Options for '%s' command:" % klass.__name__) - print('') - - print(gen_usage(self.script_name)) - - def handle_display_options(self, option_order): - """If there were any non-global "display-only" options - (--help-commands or the metadata display options) on the command - line, display the requested info and return true; else return - false. - """ - from distutils.core import gen_usage - - # User just wants a list of commands -- we'll print it out and stop - # processing now (ie. if they ran "setup --help-commands foo bar", - # we ignore "foo bar"). - if self.help_commands: - self.print_commands() - print('') - print(gen_usage(self.script_name)) - return 1 - - # If user supplied any of the "display metadata" options, then - # display that metadata in the order in which the user supplied the - # metadata options. - any_display_options = 0 - is_display_option = {} - for option in self.display_options: - is_display_option[option[0]] = 1 - - for opt, val in option_order: - if val and is_display_option.get(opt): - opt = translate_longopt(opt) - value = getattr(self.metadata, "get_" + opt)() - if opt in ('keywords', 'platforms'): - print(','.join(value)) - elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): - print('\n'.join(value)) - else: - print(value) - any_display_options = 1 - - return any_display_options - - def print_command_list(self, commands, header, max_length): - """Print a subset of the list of all commands -- used by - 'print_commands()'. - """ - print(header + ":") - - for cmd in commands: - klass = self.cmdclass.get(cmd) - if not klass: - klass = self.get_command_class(cmd) - try: - description = klass.description - except AttributeError: - description = "(no description available)" - - print(" %-*s %s" % (max_length, cmd, description)) - - def print_commands(self): - """Print out a help message listing all available commands with a - description of each. The list is divided into "standard commands" - (listed in distutils.command.__all__) and "extra commands" - (mentioned in self.cmdclass, but not a standard command). The - descriptions come from the command class attribute - 'description'. - """ - import distutils.command - - std_commands = distutils.command.__all__ - is_std = {} - for cmd in std_commands: - is_std[cmd] = 1 - - extra_commands = [] - for cmd in self.cmdclass.keys(): - if not is_std.get(cmd): - extra_commands.append(cmd) - - max_length = 0 - for cmd in std_commands + extra_commands: - if len(cmd) > max_length: - max_length = len(cmd) - - self.print_command_list(std_commands, "Standard commands", max_length) - if extra_commands: - print() - self.print_command_list(extra_commands, "Extra commands", max_length) - - def get_command_list(self): - """Get a list of (command, description) tuples. - The list is divided into "standard commands" (listed in - distutils.command.__all__) and "extra commands" (mentioned in - self.cmdclass, but not a standard command). The descriptions come - from the command class attribute 'description'. - """ - # Currently this is only used on Mac OS, for the Mac-only GUI - # Distutils interface (by Jack Jansen) - import distutils.command - - std_commands = distutils.command.__all__ - is_std = {} - for cmd in std_commands: - is_std[cmd] = 1 - - extra_commands = [] - for cmd in self.cmdclass.keys(): - if not is_std.get(cmd): - extra_commands.append(cmd) - - rv = [] - for cmd in std_commands + extra_commands: - klass = self.cmdclass.get(cmd) - if not klass: - klass = self.get_command_class(cmd) - try: - description = klass.description - except AttributeError: - description = "(no description available)" - rv.append((cmd, description)) - return rv - - # -- Command class/object methods ---------------------------------- - - def get_command_packages(self): - """Return a list of packages from which commands are loaded.""" - pkgs = self.command_packages - if not isinstance(pkgs, list): - if pkgs is None: - pkgs = '' - pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != ''] - if "distutils.command" not in pkgs: - pkgs.insert(0, "distutils.command") - self.command_packages = pkgs - return pkgs - - def get_command_class(self, command): - """Return the class that implements the Distutils command named by - 'command'. First we check the 'cmdclass' dictionary; if the - command is mentioned there, we fetch the class object from the - dictionary and return it. Otherwise we load the command module - ("distutils.command." + command) and fetch the command class from - the module. The loaded class is also stored in 'cmdclass' - to speed future calls to 'get_command_class()'. - - Raises DistutilsModuleError if the expected module could not be - found, or if that module does not define the expected class. - """ - klass = self.cmdclass.get(command) - if klass: - return klass - - for pkgname in self.get_command_packages(): - module_name = "{}.{}".format(pkgname, command) - klass_name = command - - try: - __import__(module_name) - module = sys.modules[module_name] - except ImportError: - continue - - try: - klass = getattr(module, klass_name) - except AttributeError: - raise DistutilsModuleError( - "invalid command '%s' (no class '%s' in module '%s')" - % (command, klass_name, module_name) - ) - - self.cmdclass[command] = klass - return klass - - raise DistutilsModuleError("invalid command '%s'" % command) - - def get_command_obj(self, command, create=1): - """Return the command object for 'command'. Normally this object - is cached on a previous call to 'get_command_obj()'; if no command - object for 'command' is in the cache, then we either create and - return it (if 'create' is true) or return None. - """ - cmd_obj = self.command_obj.get(command) - if not cmd_obj and create: - if DEBUG: - self.announce( - "Distribution.get_command_obj(): " - "creating '%s' command object" % command - ) - - klass = self.get_command_class(command) - cmd_obj = self.command_obj[command] = klass(self) - self.have_run[command] = 0 - - # Set any options that were supplied in config files - # or on the command line. (NB. support for error - # reporting is lame here: any errors aren't reported - # until 'finalize_options()' is called, which means - # we won't report the source of the error.) - options = self.command_options.get(command) - if options: - self._set_command_options(cmd_obj, options) - - return cmd_obj - - def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 - """Set the options for 'command_obj' from 'option_dict'. Basically - this means copying elements of a dictionary ('option_dict') to - attributes of an instance ('command'). - - 'command_obj' must be a Command instance. If 'option_dict' is not - supplied, uses the standard option dictionary for this command - (from 'self.command_options'). - """ - command_name = command_obj.get_command_name() - if option_dict is None: - option_dict = self.get_option_dict(command_name) - - if DEBUG: - self.announce(" setting options for '%s' command:" % command_name) - for option, (source, value) in option_dict.items(): - if DEBUG: - self.announce(" {} = {} (from {})".format(option, value, source)) - try: - bool_opts = [translate_longopt(o) for o in command_obj.boolean_options] - except AttributeError: - bool_opts = [] - try: - neg_opt = command_obj.negative_opt - except AttributeError: - neg_opt = {} - - try: - is_string = isinstance(value, str) - if option in neg_opt and is_string: - setattr(command_obj, neg_opt[option], not strtobool(value)) - elif option in bool_opts and is_string: - setattr(command_obj, option, strtobool(value)) - elif hasattr(command_obj, option): - setattr(command_obj, option, value) - else: - raise DistutilsOptionError( - "error in %s: command '%s' has no such option '%s'" - % (source, command_name, option) - ) - except ValueError as msg: - raise DistutilsOptionError(msg) - - def reinitialize_command(self, command, reinit_subcommands=0): - """Reinitializes a command to the state it was in when first - returned by 'get_command_obj()': ie., initialized but not yet - finalized. This provides the opportunity to sneak option - values in programmatically, overriding or supplementing - user-supplied values from the config files and command line. - You'll have to re-finalize the command object (by calling - 'finalize_options()' or 'ensure_finalized()') before using it for - real. - - 'command' should be a command name (string) or command object. If - 'reinit_subcommands' is true, also reinitializes the command's - sub-commands, as declared by the 'sub_commands' class attribute (if - it has one). See the "install" command for an example. Only - reinitializes the sub-commands that actually matter, ie. those - whose test predicates return true. - - Returns the reinitialized command object. - """ - from distutils.cmd import Command - - if not isinstance(command, Command): - command_name = command - command = self.get_command_obj(command_name) - else: - command_name = command.get_command_name() - - if not command.finalized: - return command - command.initialize_options() - command.finalized = 0 - self.have_run[command_name] = 0 - self._set_command_options(command) - - if reinit_subcommands: - for sub in command.get_sub_commands(): - self.reinitialize_command(sub, reinit_subcommands) - - return command - - # -- Methods that operate on the Distribution ---------------------- - - def announce(self, msg, level=logging.INFO): - log.log(level, msg) - - def run_commands(self): - """Run each command that was seen on the setup script command line. - Uses the list of commands found and cache of command objects - created by 'get_command_obj()'. - """ - for cmd in self.commands: - self.run_command(cmd) - - # -- Methods that operate on its Commands -------------------------- - - def run_command(self, command): - """Do whatever it takes to run a command (including nothing at all, - if the command has already been run). Specifically: if we have - already created and run the command named by 'command', return - silently without doing anything. If the command named by 'command' - doesn't even have a command object yet, create one. Then invoke - 'run()' on that command object (or an existing one). - """ - # Already been here, done that? then return silently. - if self.have_run.get(command): - return - - log.info("running %s", command) - cmd_obj = self.get_command_obj(command) - cmd_obj.ensure_finalized() - cmd_obj.run() - self.have_run[command] = 1 - - # -- Distribution query methods ------------------------------------ - - def has_pure_modules(self): - return len(self.packages or self.py_modules or []) > 0 - - def has_ext_modules(self): - return self.ext_modules and len(self.ext_modules) > 0 - - def has_c_libraries(self): - return self.libraries and len(self.libraries) > 0 - - def has_modules(self): - return self.has_pure_modules() or self.has_ext_modules() - - def has_headers(self): - return self.headers and len(self.headers) > 0 - - def has_scripts(self): - return self.scripts and len(self.scripts) > 0 - - def has_data_files(self): - return self.data_files and len(self.data_files) > 0 - - def is_pure(self): - return ( - self.has_pure_modules() - and not self.has_ext_modules() - and not self.has_c_libraries() - ) - - # -- Metadata query methods ---------------------------------------- - - # If you're looking for 'get_name()', 'get_version()', and so forth, - # they are defined in a sneaky way: the constructor binds self.get_XXX - # to self.metadata.get_XXX. The actual code is in the - # DistributionMetadata class, below. - - -class DistributionMetadata: - """Dummy class to hold the distribution meta-data: name, version, - author, and so forth. - """ - - _METHOD_BASENAMES = ( - "name", - "version", - "author", - "author_email", - "maintainer", - "maintainer_email", - "url", - "license", - "description", - "long_description", - "keywords", - "platforms", - "fullname", - "contact", - "contact_email", - "classifiers", - "download_url", - # PEP 314 - "provides", - "requires", - "obsoletes", - ) - - def __init__(self, path=None): - if path is not None: - self.read_pkg_file(open(path)) - else: - self.name = None - self.version = None - self.author = None - self.author_email = None - self.maintainer = None - self.maintainer_email = None - self.url = None - self.license = None - self.description = None - self.long_description = None - self.keywords = None - self.platforms = None - self.classifiers = None - self.download_url = None - # PEP 314 - self.provides = None - self.requires = None - self.obsoletes = None - - def read_pkg_file(self, file): - """Reads the metadata values from a file object.""" - msg = message_from_file(file) - - def _read_field(name): - value = msg[name] - if value and value != "UNKNOWN": - return value - - def _read_list(name): - values = msg.get_all(name, None) - if values == []: - return None - return values - - metadata_version = msg['metadata-version'] - self.name = _read_field('name') - self.version = _read_field('version') - self.description = _read_field('summary') - # we are filling author only. - self.author = _read_field('author') - self.maintainer = None - self.author_email = _read_field('author-email') - self.maintainer_email = None - self.url = _read_field('home-page') - self.license = _read_field('license') - - if 'download-url' in msg: - self.download_url = _read_field('download-url') - else: - self.download_url = None - - self.long_description = _read_field('description') - self.description = _read_field('summary') - - if 'keywords' in msg: - self.keywords = _read_field('keywords').split(',') - - self.platforms = _read_list('platform') - self.classifiers = _read_list('classifier') - - # PEP 314 - these fields only exist in 1.1 - if metadata_version == '1.1': - self.requires = _read_list('requires') - self.provides = _read_list('provides') - self.obsoletes = _read_list('obsoletes') - else: - self.requires = None - self.provides = None - self.obsoletes = None - - def write_pkg_info(self, base_dir): - """Write the PKG-INFO file into the release tree.""" - with open( - os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8' - ) as pkg_info: - self.write_pkg_file(pkg_info) - - def write_pkg_file(self, file): - """Write the PKG-INFO format data to a file object.""" - version = '1.0' - if ( - self.provides - or self.requires - or self.obsoletes - or self.classifiers - or self.download_url - ): - version = '1.1' - - # required fields - file.write('Metadata-Version: %s\n' % version) - file.write('Name: %s\n' % self.get_name()) - file.write('Version: %s\n' % self.get_version()) - - def maybe_write(header, val): - if val: - file.write(f"{header}: {val}\n") - - # optional fields - maybe_write("Summary", self.get_description()) - maybe_write("Home-page", self.get_url()) - maybe_write("Author", self.get_contact()) - maybe_write("Author-email", self.get_contact_email()) - maybe_write("License", self.get_license()) - maybe_write("Download-URL", self.download_url) - maybe_write("Description", rfc822_escape(self.get_long_description() or "")) - maybe_write("Keywords", ",".join(self.get_keywords())) - - self._write_list(file, 'Platform', self.get_platforms()) - self._write_list(file, 'Classifier', self.get_classifiers()) - - # PEP 314 - self._write_list(file, 'Requires', self.get_requires()) - self._write_list(file, 'Provides', self.get_provides()) - self._write_list(file, 'Obsoletes', self.get_obsoletes()) - - def _write_list(self, file, name, values): - values = values or [] - for value in values: - file.write('{}: {}\n'.format(name, value)) - - # -- Metadata query methods ---------------------------------------- - - def get_name(self): - return self.name or "UNKNOWN" - - def get_version(self): - return self.version or "0.0.0" - - def get_fullname(self): - return "{}-{}".format(self.get_name(), self.get_version()) - - def get_author(self): - return self.author - - def get_author_email(self): - return self.author_email - - def get_maintainer(self): - return self.maintainer - - def get_maintainer_email(self): - return self.maintainer_email - - def get_contact(self): - return self.maintainer or self.author - - def get_contact_email(self): - return self.maintainer_email or self.author_email - - def get_url(self): - return self.url - - def get_license(self): - return self.license - - get_licence = get_license - - def get_description(self): - return self.description - - def get_long_description(self): - return self.long_description - - def get_keywords(self): - return self.keywords or [] - - def set_keywords(self, value): - self.keywords = _ensure_list(value, 'keywords') - - def get_platforms(self): - return self.platforms - - def set_platforms(self, value): - self.platforms = _ensure_list(value, 'platforms') - - def get_classifiers(self): - return self.classifiers or [] - - def set_classifiers(self, value): - self.classifiers = _ensure_list(value, 'classifiers') - - def get_download_url(self): - return self.download_url - - # PEP 314 - def get_requires(self): - return self.requires or [] - - def set_requires(self, value): - import distutils.versionpredicate - - for v in value: - distutils.versionpredicate.VersionPredicate(v) - self.requires = list(value) - - def get_provides(self): - return self.provides or [] - - def set_provides(self, value): - value = [v.strip() for v in value] - for v in value: - import distutils.versionpredicate - - distutils.versionpredicate.split_provision(v) - self.provides = value - - def get_obsoletes(self): - return self.obsoletes or [] - - def set_obsoletes(self, value): - import distutils.versionpredicate - - for v in value: - distutils.versionpredicate.VersionPredicate(v) - self.obsoletes = list(value) - - -def fix_help_options(options): - """Convert a 4-tuple 'help_options' list as found in various command - classes to the 3-tuple form required by FancyGetopt. - """ - new_options = [] - for help_tuple in options: - new_options.append(help_tuple[0:3]) - return new_options diff --git a/spaces/TencentARC/MasaCtrl/masactrl/masactrl_utils.py b/spaces/TencentARC/MasaCtrl/masactrl/masactrl_utils.py deleted file mode 100644 index efb161f4f16e8282ac5fe88a0dd0e948a179b4d9..0000000000000000000000000000000000000000 --- a/spaces/TencentARC/MasaCtrl/masactrl/masactrl_utils.py +++ /dev/null @@ -1,212 +0,0 @@ -import os -import cv2 -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F - -from typing import Optional, Union, Tuple, List, Callable, Dict - -from torchvision.utils import save_image -from einops import rearrange, repeat - - -class AttentionBase: - def __init__(self): - self.cur_step = 0 - self.num_att_layers = -1 - self.cur_att_layer = 0 - - def after_step(self): - pass - - def __call__(self, q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs): - out = self.forward(q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs) - self.cur_att_layer += 1 - if self.cur_att_layer == self.num_att_layers: - self.cur_att_layer = 0 - self.cur_step += 1 - # after step - self.after_step() - return out - - def forward(self, q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs): - out = torch.einsum('b i j, b j d -> b i d', attn, v) - out = rearrange(out, '(b h) n d -> b n (h d)', h=num_heads) - return out - - def reset(self): - self.cur_step = 0 - self.cur_att_layer = 0 - - -class AttentionStore(AttentionBase): - def __init__(self, res=[32], min_step=0, max_step=1000): - super().__init__() - self.res = res - self.min_step = min_step - self.max_step = max_step - self.valid_steps = 0 - - self.self_attns = [] # store the all attns - self.cross_attns = [] - - self.self_attns_step = [] # store the attns in each step - self.cross_attns_step = [] - - def after_step(self): - if self.cur_step > self.min_step and self.cur_step < self.max_step: - self.valid_steps += 1 - if len(self.self_attns) == 0: - self.self_attns = self.self_attns_step - self.cross_attns = self.cross_attns_step - else: - for i in range(len(self.self_attns)): - self.self_attns[i] += self.self_attns_step[i] - self.cross_attns[i] += self.cross_attns_step[i] - self.self_attns_step.clear() - self.cross_attns_step.clear() - - def forward(self, q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs): - if attn.shape[1] <= 64 ** 2: # avoid OOM - if is_cross: - self.cross_attns_step.append(attn) - else: - self.self_attns_step.append(attn) - return super().forward(q, k, v, sim, attn, is_cross, place_in_unet, num_heads, **kwargs) - - -def regiter_attention_editor_diffusers(model, editor: AttentionBase): - """ - Register a attention editor to Diffuser Pipeline, refer from [Prompt-to-Prompt] - """ - def ca_forward(self, place_in_unet): - def forward(x, encoder_hidden_states=None, attention_mask=None, context=None, mask=None): - """ - The attention is similar to the original implementation of LDM CrossAttention class - except adding some modifications on the attention - """ - if encoder_hidden_states is not None: - context = encoder_hidden_states - if attention_mask is not None: - mask = attention_mask - - to_out = self.to_out - if isinstance(to_out, nn.modules.container.ModuleList): - to_out = self.to_out[0] - else: - to_out = self.to_out - - h = self.heads - q = self.to_q(x) - is_cross = context is not None - context = context if is_cross else x - k = self.to_k(context) - v = self.to_v(context) - q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) - - sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale - - if mask is not None: - mask = rearrange(mask, 'b ... -> b (...)') - max_neg_value = -torch.finfo(sim.dtype).max - mask = repeat(mask, 'b j -> (b h) () j', h=h) - mask = mask[:, None, :].repeat(h, 1, 1) - sim.masked_fill_(~mask, max_neg_value) - - attn = sim.softmax(dim=-1) - # the only difference - out = editor( - q, k, v, sim, attn, is_cross, place_in_unet, - self.heads, scale=self.scale) - - return to_out(out) - - return forward - - def register_editor(net, count, place_in_unet): - for name, subnet in net.named_children(): - if net.__class__.__name__ == 'Attention': # spatial Transformer layer - net.forward = ca_forward(net, place_in_unet) - return count + 1 - elif hasattr(net, 'children'): - count = register_editor(subnet, count, place_in_unet) - return count - - cross_att_count = 0 - for net_name, net in model.unet.named_children(): - if "down" in net_name: - cross_att_count += register_editor(net, 0, "down") - elif "mid" in net_name: - cross_att_count += register_editor(net, 0, "mid") - elif "up" in net_name: - cross_att_count += register_editor(net, 0, "up") - editor.num_att_layers = cross_att_count - - -def regiter_attention_editor_ldm(model, editor: AttentionBase): - """ - Register a attention editor to Stable Diffusion model, refer from [Prompt-to-Prompt] - """ - def ca_forward(self, place_in_unet): - def forward(x, encoder_hidden_states=None, attention_mask=None, context=None, mask=None): - """ - The attention is similar to the original implementation of LDM CrossAttention class - except adding some modifications on the attention - """ - if encoder_hidden_states is not None: - context = encoder_hidden_states - if attention_mask is not None: - mask = attention_mask - - to_out = self.to_out - if isinstance(to_out, nn.modules.container.ModuleList): - to_out = self.to_out[0] - else: - to_out = self.to_out - - h = self.heads - q = self.to_q(x) - is_cross = context is not None - context = context if is_cross else x - k = self.to_k(context) - v = self.to_v(context) - q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) - - sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale - - if mask is not None: - mask = rearrange(mask, 'b ... -> b (...)') - max_neg_value = -torch.finfo(sim.dtype).max - mask = repeat(mask, 'b j -> (b h) () j', h=h) - mask = mask[:, None, :].repeat(h, 1, 1) - sim.masked_fill_(~mask, max_neg_value) - - attn = sim.softmax(dim=-1) - # the only difference - out = editor( - q, k, v, sim, attn, is_cross, place_in_unet, - self.heads, scale=self.scale) - - return to_out(out) - - return forward - - def register_editor(net, count, place_in_unet): - for name, subnet in net.named_children(): - if net.__class__.__name__ == 'CrossAttention': # spatial Transformer layer - net.forward = ca_forward(net, place_in_unet) - return count + 1 - elif hasattr(net, 'children'): - count = register_editor(subnet, count, place_in_unet) - return count - - cross_att_count = 0 - for net_name, net in model.model.diffusion_model.named_children(): - if "input" in net_name: - cross_att_count += register_editor(net, 0, "input") - elif "middle" in net_name: - cross_att_count += register_editor(net, 0, "middle") - elif "output" in net_name: - cross_att_count += register_editor(net, 0, "output") - editor.num_att_layers = cross_att_count diff --git a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/detectron2/utils/comm.py b/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/detectron2/utils/comm.py deleted file mode 100644 index 7e2a0c44278cf00c16dcf360da4779d8f0c6e8e6..0000000000000000000000000000000000000000 --- a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/detectron2/utils/comm.py +++ /dev/null @@ -1,199 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -""" -This file contains primitives for multi-gpu communication. -This is useful when doing distributed training. -""" - -import functools -import numpy as np -import torch -import torch.distributed as dist - -_LOCAL_PROCESS_GROUP = None -""" -A torch process group which only includes processes that on the same machine as the current process. -This variable is set when processes are spawned by `launch()` in "engine/launch.py". -""" - - -def get_world_size() -> int: - if not dist.is_available(): - return 1 - if not dist.is_initialized(): - return 1 - return dist.get_world_size() - - -def get_rank() -> int: - if not dist.is_available(): - return 0 - if not dist.is_initialized(): - return 0 - return dist.get_rank() - - -def get_local_rank() -> int: - """ - Returns: - The rank of the current process within the local (per-machine) process group. - """ - if not dist.is_available(): - return 0 - if not dist.is_initialized(): - return 0 - assert ( - _LOCAL_PROCESS_GROUP is not None - ), "Local process group is not created! Please use launch() to spawn processes!" - return dist.get_rank(group=_LOCAL_PROCESS_GROUP) - - -def get_local_size() -> int: - """ - Returns: - The size of the per-machine process group, - i.e. the number of processes per machine. - """ - if not dist.is_available(): - return 1 - if not dist.is_initialized(): - return 1 - return dist.get_world_size(group=_LOCAL_PROCESS_GROUP) - - -def is_main_process() -> bool: - return get_rank() == 0 - - -def synchronize(): - """ - Helper function to synchronize (barrier) among all processes when - using distributed training - """ - if not dist.is_available(): - return - if not dist.is_initialized(): - return - world_size = dist.get_world_size() - if world_size == 1: - return - if dist.get_backend() == dist.Backend.NCCL: - # This argument is needed to avoid warnings. - # It's valid only for NCCL backend. - dist.barrier(device_ids=[torch.cuda.current_device()]) - else: - dist.barrier() - - -@functools.lru_cache() -def _get_global_gloo_group(): - """ - Return a process group based on gloo backend, containing all the ranks - The result is cached. - """ - if dist.get_backend() == "nccl": - return dist.new_group(backend="gloo") - else: - return dist.group.WORLD - - -def all_gather(data, group=None): - """ - Run all_gather on arbitrary picklable data (not necessarily tensors). - - Args: - data: any picklable object - group: a torch process group. By default, will use a group which - contains all ranks on gloo backend. - - Returns: - list[data]: list of data gathered from each rank - """ - if get_world_size() == 1: - return [data] - if group is None: - group = _get_global_gloo_group() # use CPU group by default, to reduce GPU RAM usage. - world_size = dist.get_world_size(group) - if world_size == 1: - return [data] - - output = [None for _ in range(world_size)] - dist.all_gather_object(output, data, group=group) - return output - - -def gather(data, dst=0, group=None): - """ - Run gather on arbitrary picklable data (not necessarily tensors). - - Args: - data: any picklable object - dst (int): destination rank - group: a torch process group. By default, will use a group which - contains all ranks on gloo backend. - - Returns: - list[data]: on dst, a list of data gathered from each rank. Otherwise, - an empty list. - """ - if get_world_size() == 1: - return [data] - if group is None: - group = _get_global_gloo_group() - world_size = dist.get_world_size(group=group) - if world_size == 1: - return [data] - rank = dist.get_rank(group=group) - - if rank == dst: - output = [None for _ in range(world_size)] - dist.gather_object(data, output, dst=dst, group=group) - return output - else: - dist.gather_object(data, None, dst=dst, group=group) - return [] - - -def shared_random_seed(): - """ - Returns: - int: a random number that is the same across all workers. - If workers need a shared RNG, they can use this shared seed to - create one. - - All workers must call this function, otherwise it will deadlock. - """ - ints = np.random.randint(2 ** 31) - all_ints = all_gather(ints) - return all_ints[0] - - -def reduce_dict(input_dict, average=True): - """ - Reduce the values in the dictionary from all processes so that process with rank - 0 has the reduced results. - - Args: - input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. - average (bool): whether to do average or sum - - Returns: - a dict with the same keys as input_dict, after reduction. - """ - world_size = get_world_size() - if world_size < 2: - return input_dict - with torch.no_grad(): - names = [] - values = [] - # sort the keys so that they are consistent across processes - for k in sorted(input_dict.keys()): - names.append(k) - values.append(input_dict[k]) - values = torch.stack(values, dim=0) - dist.reduce(values, dst=0) - if dist.get_rank() == 0 and average: - # only main process gets accumulated, so only divide by - # world_size in this case - values /= world_size - reduced_dict = {k: v for k, v in zip(names, values)} - return reduced_dict diff --git a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/tests/config/root_cfg.py b/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/tests/config/root_cfg.py deleted file mode 100644 index 33d1d4bd2d9ddf31d55c655c49d13a8b7ac7b376..0000000000000000000000000000000000000000 --- a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/tests/config/root_cfg.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from itertools import count - -from detectron2.config import LazyCall as L - -from .dir1.dir1_a import dir1a_dict, dir1a_str - -dir1a_dict.a = "modified" - -# modification above won't affect future imports -from .dir1.dir1_b import dir1b_dict, dir1b_str - - -lazyobj = L(count)(x=dir1a_str, y=dir1b_str) diff --git a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/tools/__init__.py b/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/tools/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/TheKitten/Images/README.md b/spaces/TheKitten/Images/README.md deleted file mode 100644 index 588f7fcc84860e5d4dad9a8948c205bee26c6ca1..0000000000000000000000000000000000000000 --- a/spaces/TheKitten/Images/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 490 Models Fast Diffusion -emoji: 🪅🌐 -colorFrom: gray -colorTo: green -sdk: gradio -sdk_version: 3.15.0 -app_file: app.py -pinned: true -duplicated_from: Omnibus/maximum_multiplier_places ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Tipbs/wikipedia_summary/app.py b/spaces/Tipbs/wikipedia_summary/app.py deleted file mode 100644 index 6753f8a41e9d9f2dd42bde96f7b43fc8cc96fd87..0000000000000000000000000000000000000000 --- a/spaces/Tipbs/wikipedia_summary/app.py +++ /dev/null @@ -1,32 +0,0 @@ -import wikipediaapi -import gradio as gr - -def get_wiki_summary(search): - wiki_wiki = wikipediaapi.Wikipedia('en') - page = wiki_wiki.page(search) - - isExist = page.exists() - if not isExist: - return isExist, "Not found", "Not found", "Not found", "Not found" - - url = page.fullurl - tittle = page.title - summary = page.summary[0:60] - text = page.text - - return isExist, url, tittle, summary, text - -if __name__ == '__main__': - wiki_summary = gr.Interface( - get_wiki_summary, - gr.Text(label="Search Wikipedia"), - [ - gr.Text(label="Page exists?"), - gr.Text(label="URL"), - gr.Text(label="Title"), - gr.Text(label="Summary"), - gr.Text(label="Text") - ] - ) - wiki_summary.launch() - diff --git a/spaces/Xenova/semantic-image-search-client/_next/static/chunks/200.06935266f469fb97.js b/spaces/Xenova/semantic-image-search-client/_next/static/chunks/200.06935266f469fb97.js deleted file mode 100644 index 52fc1ce5caf37f865112d793b1c9d95e57841050..0000000000000000000000000000000000000000 --- a/spaces/Xenova/semantic-image-search-client/_next/static/chunks/200.06935266f469fb97.js +++ /dev/null @@ -1 +0,0 @@ -!function(){var t,e,n,r,o,i,a,s,c={495:function(){},7147:function(){},1418:function(){},3380:function(){},319:function(){},8386:function(){},3342:function(){},4549:function(t,e,n){"use strict";var r=n(552);async function o(t){let e;try{e=await caches.open("image-database");let n=await e.match(t);if(n)return await n.arrayBuffer()}catch(t){console.warn("Unable to open cache",t)}let n=await fetch(t),r=await n.arrayBuffer();if(e)try{await e.put(t,new Response(r,{headers:n.headers}))}catch(t){console.warn("Unable to cache file",t)}return r}async function i(t){let e=await o(t);return JSON.parse(new TextDecoder("utf-8").decode(e))}r.OBj.allowLocalModels=!1;class a{static async getInstance(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return null===this.tokenizer&&(this.tokenizer=r.t25.from_pretrained(this.model_id,{progress_callback:t})),null===this.text_model&&(this.text_model=r.v3$.from_pretrained(this.model_id,{progress_callback:t})),null===this.metadata&&(this.metadata=i(this.BASE_URL+"image-embeddings.json")),null===this.embeddings&&(this.embeddings=new Promise((t,e)=>{o(this.BASE_URL+"image-embeddings_25k-512-32bit.bin").then(e=>{t(new Float32Array(e))}).catch(e)})),Promise.all([this.tokenizer,this.text_model,this.metadata,this.embeddings])}}a.model_id="Xenova/clip-vit-base-patch16",a.BASE_URL="https://huggingface.co/datasets/Xenova/semantic-image-search-assets/resolve/main/",a.tokenizer=null,a.text_model=null,a.metadata=null,a.embeddings=null,self.addEventListener("message",async t=>{let[e,n,r,o]=await a.getInstance(self.postMessage);self.postMessage({status:"ready"});let i=e(t.data.text,{padding:!0,truncation:!0}),{text_embeds:s}=await n(i),c=function(t,e){let n=e.length/512,r=Array(n);for(let o=0;oe.score-t.score),u=u.slice(0,100),self.postMessage({status:"complete",output:u})})}},u={};function l(t){var e=u[t];if(void 0!==e)return e.exports;var n=u[t]={exports:{}},r=!0;try{c[t](n,n.exports,l),r=!1}finally{r&&delete u[t]}return n.exports}l.m=c,l.x=function(){var t=l.O(void 0,[15,990],function(){return l(4549)});return l.O(t)},t=[],l.O=function(e,n,r,o){if(n){o=o||0;for(var i=t.length;i>0&&t[i-1][2]>o;i--)t[i]=t[i-1];t[i]=[n,r,o];return}for(var a=1/0,i=0;i=o&&Object.keys(l.O).every(function(t){return l.O[t](n[c])})?n.splice(c--,1):(s=!1,o= 8: # Too many words - # Rather split on whitespace instead of punctuation - split_text = split_on_whitespace - else: - word_level = True - else: - raise ValueError('Unknown granularity') - - segment_end = parsed_transcript[i]['end'] - if i < len(parsed_transcript) - 1: - segment_end = min(segment_end, parsed_transcript[i+1]['start']) - - segment_duration = segment_end - parsed_transcript[i]['start'] - - num_chars_in_text = sum(map(len, split_text)) - - num_char_count = 0 - current_offset = 0 - for s in split_text: - num_char_count += len(s) - - next_offset = (num_char_count/num_chars_in_text) * segment_duration - - word_start = round( - parsed_transcript[i]['start'] + current_offset, NUM_DECIMALS) - word_end = round( - parsed_transcript[i]['start'] + next_offset, NUM_DECIMALS) - - # Make the reasonable assumption that min wps is 1.5 - final_parsed_transcript.append({ - 'text': s, - 'start': word_start, - 'end': min(word_end, word_start + 1.5) if word_level else word_end - }) - current_offset = next_offset - - return final_parsed_transcript - - -def list_transcripts(video_id): - try: - return YouTubeTranscriptApi.list_transcripts(video_id) - except json.decoder.JSONDecodeError: - return None - - -WORDS_TO_REMOVE = [ - CustomTokens.MUSIC.value, - CustomTokens.APPLAUSE.value, - CustomTokens.LAUGHTER.value -] - - -@lru_cache(maxsize=16) -def get_words(video_id, process=True, transcript_type='auto', fallback='manual', filter_words_to_remove=True, download=False, granularity='word'): - """Get parsed video transcript with caching system - returns None if not processed yet and process is False - """ - # NOTE: granularity='chunk' should only be used for generating training data... nowhere else - - transcript_path = os.path.join( # TODO use relative path to this - 'transcripts', transcript_type, f'{video_id}.json') - - raw_transcript_json = None - try: - if not download and os.path.exists(transcript_path): # Load from file - with open(transcript_path) as fp: - raw_transcript_json = json.load(fp) # May be empty - - elif process: - transcript_list = list_transcripts(video_id) - - if transcript_list is not None: - if transcript_type == 'manual': - ts = transcript_list.find_manually_created_transcript( - LANGUAGE_PREFERENCE_LIST) - else: - ts = transcript_list.find_generated_transcript( - LANGUAGE_PREFERENCE_LIST) - raw_transcript = ts._http_client.get( - f'{ts._url}&fmt=json3').content - if raw_transcript: - raw_transcript_json = json.loads(raw_transcript) - - except (TooManyRequests, YouTubeRequestFailed): - raise # Cannot recover from these errors and do not mark as empty transcript - - except requests.exceptions.RequestException: # Can recover - time.sleep(10) # Timeout - return get_words(video_id, process, transcript_type, fallback, granularity) - - except CouldNotRetrieveTranscript: # Retrying won't solve - pass # Mark as empty transcript - - except json.decoder.JSONDecodeError: - logger.warning(f'JSONDecodeError for {video_id}') - if os.path.exists(transcript_path): - os.remove(transcript_path) # Remove file and try again - return get_words(video_id, process, transcript_type, fallback, granularity) - - # Tried to process it, but it was empty... - if download or (process and not os.path.exists(transcript_path)): - with open(transcript_path, 'w') as fp: - json.dump(raw_transcript_json, fp) - - if not raw_transcript_json and fallback is not None: - return get_words(video_id, process, transcript_type=fallback, fallback=None, granularity=granularity) - - if raw_transcript_json: - processed_transcript = parse_transcript_json( - raw_transcript_json, granularity) - if filter_words_to_remove: - processed_transcript = list( - filter(lambda x: x['text'] not in WORDS_TO_REMOVE, processed_transcript)) - else: - processed_transcript = raw_transcript_json # Either None or [] - - return processed_transcript - - -# TODO make min_sponsor_segment_length param -# TODO rename to extract_segments -def extract_sponsors(words, min_sponsor_segment_length=3): - if not words: - return [] - - paragraphs = [] - current = [] - prev_category = None - - for i in range(len(words) + 1): - unimportant = i == len(words) or words[i].get('category') is None - - if unimportant or words[i].get('category') != prev_category: - if current: # Save the current batch - paragraphs.append({ - 'words': current, - 'category': current[-1].get('category'), - }) - - current = [] - - if not unimportant: # Some useful information to save - current.append(words[i]) - prev_category = words[i].get('category') - - # Remove all too short: - return list(filter(lambda x: len(x['words']) >= min_sponsor_segment_length, paragraphs)) - - -def clean_text(text): - - # Replace impossibly long words with a special token - # Usually the result of incorrect labelling - text = re.sub(r'\w{64,}', CustomTokens.LONG_WORD.value, text) - - SHORT_HYPHENATED_REGEX = r'\w{1,2}(?:-\w{1,2}){3,}(?:-?\w*)' - - # Replace hyphenated URLs with special token - # For some reason, youtube sometimes transcribes urls in this form: - # 'b-a-b-b-e-l-dot-com', 'g-e-t-r-o-m-a-n-com' - # not 'e-commerce' - text = re.sub(f'{SHORT_HYPHENATED_REGEX}(?:com|org|net)', - CustomTokens.HYPHENATED_URL.value, text) - - # Replace short+hyphenated text with a special token. Of the form: - # 'i-i-i-i-i-i-i-i-i-i-i-i', 'b-u-m-f-u-z-z-l-e', 'v-e-r-i-t-a-s-i-u-m', 'do-do-do-do-do' - text = re.sub(SHORT_HYPHENATED_REGEX, - CustomTokens.SHORT_HYPHENATED.value, text) - - # Replace URLs with URL_TOKEN - URL_REGEX = r'(?:(?:http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.(?:[a-zA-Z]){2,6}(?:[a-zA-Z0-9\.\&\/\?\:@\-_=#%])*' - text = re.sub(URL_REGEX, CustomTokens.URL.value, text) - - NUM_REGEX = r'(?:\d+,)*(?:\d*[.])?\d+' - - # Encode specific numeric words - # Of the form: 12%, 12.34% - # Usually included in sponsorships - text = re.sub(f'{NUM_REGEX}%', - CustomTokens.NUMBER_PERCENTAGE.value, text) - - # Normal numbers, should not have an effect on sponsorship - text = re.sub(NUM_REGEX, CustomTokens.NUMBER.value, text) - - # Replace profanity with special token - text = text.replace(PROFANITY_RAW, CustomTokens.PROFANITY.value) - text = text.replace(PROFANITY_CONVERTED, CustomTokens.PROFANITY.value) - - return text.strip() - - -def remove_duplicate_segments(segments): - # Algorithm based on SponsorBlock algorithm - # https://blog.ajay.app/voting-and-pseudo-randomness-or-sponsorblock-or-youtube-sponsorship-segment-blocker - # Find sponsors that are overlapping - - best = [] - for i in segments: - similar_segments = [] - for j in segments: - if jaccard(i['start'], i['end'], j['start'], j['end']) > 0.1: # Some overlap - similar_segments.append(j) - - if similar_segments: - best_similar_seg = max(similar_segments, key=lambda item: ( - item['locked'], - item['votes'], - item['views'], - item['reputation'] - )) - if best_similar_seg not in best: - best.append(best_similar_seg) - - if len(segments) != len(best): # Saw some reduction... try again - return remove_duplicate_segments(best) - - return best - - -@dataclass -class PreprocessArguments: - """ - Arguments pertaining to what data we are going to preprocess. - """ - update_database: bool = field( - default=False, metadata={'help': 'Download the raw database.'} - ) - - do_create: bool = field( - default=False, metadata={'help': 'Merge sponsor segments into single file'} - ) - - min_votes: int = field( - default=0, metadata={'help': 'Minimum number of votes'}) - # Downvotes will make this negative. - # 1 = At least one positive vote - - max_segment_duration: float = field( - default=180, # 3 minutes - # >180 => 2.8% - # >200 => 2.1% - # >250 => 1.1% - # >300 => 0.06% - metadata={'help': 'Ignore all segments whose duration in seconds is longer than this value (negative means no limit)'}) - - min_views: int = field( - default=5, metadata={'help': 'Minimum number of views a segment must have to be considered. 0 = show all'}) - - # min_reputation: int = field( - # default=0, metadata={'help': 'Minimum reputation a user must have for the segment to be included'}) - - min_date: str = field( - # default='08/06/2020', # release of v2.0 (https://github.com/ajayyy/SponsorBlock/releases/tag/2.0) - # release of v3.0 (https://github.com/ajayyy/SponsorBlock/releases/tag/3.0) - default='20/08/2021', - # default='01/10/2020', # No more autovote - metadata={'help': 'Only use submissions from after this date (inclusive)'}) - - max_date: str = field( - # default='01/01/9999', # Include all - default='15/04/2022', - metadata={'help': 'Only use videos that have some segment from before this date (exclusive). This allows for videos to have segments be corrected, but ignores new videos (posted after this date) to enter the pool.'}) - - # max_unseen_date: str = field( # TODO - # default='02/03/2022', - # metadata={'help': 'Generate test and validation data from `max_date` to `max_unseen_date`'}) - # Specify min/max video id for splitting (seen vs. unseen) - - keep_duplicate_segments: bool = field( - default=False, metadata={'help': 'Keep duplicate segments'} - ) - - do_process_database: bool = field( - default=False, metadata={'help': 'Process the raw database'} - ) - do_transcribe: bool = field( - default=False, metadata={'help': 'Get transcripts for videos'} - ) - num_jobs: int = field( - default=4, metadata={'help': 'Number of transcripts to download in parallel'}) - - # overwrite: bool = field( - # default=False, metadata={'help': 'Overwrite training, testing and validation data, if present.'} - # ) - - do_generate: bool = field( - default=False, metadata={'help': 'Generate labelled data.'} - ) - - do_split: bool = field( - default=False, metadata={'help': 'Generate training, testing and validation data.'} - ) - - positive_file: Optional[str] = field( - default='sponsor_segments.json', metadata={'help': 'File to output sponsored segments to (a jsonlines file).'} - ) - negative_file: Optional[str] = field( - default='normal_segments.json', metadata={'help': 'File to output normal segments to (a jsonlines file).'} - ) - - percentage_positive: float = field( - default=0.5, metadata={'help': 'Ratio of positive (sponsor) segments to include in final output'}) - - train_split: float = field( - default=0.9, metadata={'help': 'Ratio of training data. Value between 0 and 1.'}) - - # TODO play around with ratios? lower test/validation split? - test_split: float = field( - default=0.05, metadata={'help': 'Ratio of testing data. Value between 0 and 1.'}) - valid_split: float = field( - default=0.05, metadata={'help': 'Ratio of validation data. Value between 0 and 1.'}) - - start_index: int = field(default=None, metadata={ - 'help': 'Video to start at.'}) - - max_videos: int = field(default=None, metadata={ - 'help': 'Maximum number of videos to preprocess.'}) - - max_segments: int = field(default=None, metadata={ - 'help': 'Maximum number of segments to produce to preprocess.'}) - - raw_data_dir: Optional[str] = field( - default='raw', - metadata={ - 'help': 'Raw data directory' - }, - ) - raw_data_file: Optional[str] = field( - default='sponsorTimes.csv', - metadata={ - 'help': 'Raw data file' - }, - ) - - min_wps: float = field( - default=1.5, metadata={'help': 'Ignore videos with not enough words spoken per second. This is usually indicitive of video whose captions aren\'t English.'}) - # 0.1 ~ 1% - # 0.4 ~ 2.5% - # 0.9 ~ 5% - - -# Mirrors for database -MIRRORS = [ - 'https://sponsor.ajay.app/database/sponsorTimes.csv', # Latest - 'https://sb-mirror.mchang.xyz/sponsorTimes.csv', # 5 minute delay - 'https://sb.ltn.fi/database/sponsorTimes.csv', # 5 minute delay -] -# TODO only download latest updates/changes - - -def download_file(url, filename): - """ - Helper method handling downloading large files from `url` to `filename`. - - Adapted from https://stackoverflow.com/a/42071418 - """ - chunk_size = 1024 - r = requests.get(url, stream=True) - total_bytes = int(r.headers['Content-Length']) - with open(filename, 'wb') as f, tqdm(unit='B', total=total_bytes) as progress: - for chunk in r.iter_content(chunk_size=chunk_size): - if chunk: # filter out keep-alive new chunks - progress.update(len(chunk)) - f.write(chunk) - - return total_bytes == os.path.getsize(filename) - - -def main(): - # Responsible for getting transcrips using youtube_transcript_api, - # then labelling it according to SponsorBlock's API - logger.setLevel(logging.DEBUG) - - # Generate final.json from sponsorTimes.csv - hf_parser = HfArgumentParser(( - PreprocessArguments, - DatasetArguments, - segment.SegmentationArguments, - model_module.ModelArguments, - GeneralArguments - )) - preprocess_args, dataset_args, segmentation_args, model_args, general_args = hf_parser.parse_args_into_dataclasses() - - raw_dataset_path = os.path.join( - preprocess_args.raw_data_dir, preprocess_args.raw_data_file) - - if preprocess_args.update_database: - logger.info('Updating database') - for mirror in MIRRORS: - logger.info(f'Downloading from {mirror}') - if download_file(mirror, raw_dataset_path): - break - logger.warning('Failed, trying next') - - os.makedirs(dataset_args.data_dir, exist_ok=True) - processed_db_path = os.path.join( - dataset_args.data_dir, dataset_args.processed_database) - - # TODO process all valid possible items and then do filtering only later - @lru_cache(maxsize=1) - def read_db(): - # if not preprocess_args.overwrite and os.path.exists(processed_db_path): - # logger.info( - # 'Using cached processed database (use `--overwrite` to avoid this behaviour).') - # with open(processed_db_path) as fp: - # return json.load(fp) - logger.info('Processing raw database') - db = {} - - allowed_categories = list(map(str.lower, CATGEGORY_OPTIONS)) - with open(raw_dataset_path, newline='') as csvfile: - reader = csv.DictReader(csvfile) - - for line in reader: - - # Never show: - if line['service'] != 'YouTube': - continue - if len(line['videoID']) != 11: - continue # Invalid youtube video ID - - if line['category'] not in allowed_categories: - continue - if line['actionType'] not in ACTION_OPTIONS: - continue - - # Ignore hidden items - if line['hidden'] == '1' or line['shadowHidden'] == '1': - continue - - # Skip those that aren't highly voted - votes = int(line['votes']) - if votes < preprocess_args.min_votes: - continue - - locked = line['locked'] == '1' - - reputation = float(line['reputation']) - # if reputation < preprocess_args.min_reputation: - # continue # TODO add back? - # Problems like mGVn1wCkBrE - - # TODO ignore if over max_duration - - if line['videoID'] not in db: - db[line['videoID']] = [] - - db[line['videoID']].append({ - 'uuid': line['UUID'], - 'start': float(line['startTime']), - 'end': float(line['endTime']), - 'votes': votes, - 'locked': locked, - 'views': int(line['views']), - 'submission_time': float(line['timeSubmitted'])/1e3, - 'reputation': reputation, - 'category': line['category'], - 'action': line['actionType'], - }) - - # First, remove videos that contain a full-video label - # (may confuse model since disclaimers and such aren't labelled) - # Must do it here before removing duplicate segments - for key in list(db): - if any(x['action'] == 'full' for x in db[key]): - del db[key] - - # Remove duplicate sponsor segments by choosing best (most votes) - if not preprocess_args.keep_duplicate_segments: - logger.info('Remove duplicate segments') - for key in db: - db[key] = remove_duplicate_segments(db[key]) - - # We now remove whole videos from the list - # Helps with obtaining "fully-labelled" videos - min_date = datetime.strptime(preprocess_args.min_date, '%d/%m/%Y') - max_date = datetime.strptime(preprocess_args.max_date, '%d/%m/%Y') - for key in list(db): - if preprocess_args.max_segment_duration >= 0 and any(x['end'] - x['start'] > preprocess_args.max_segment_duration for x in db[key]): - # Remove videos that have at least one segment that is longer than - # the maximum allowed segment duration. This avoids introducing - # segments into training that might contain ignored context (since - # they are too long, so the middle might be normal content) - del db[key] - elif any(datetime.fromtimestamp(x['submission_time']) < min_date for x in db[key]): - # Remove videos where any of its segments were submitted before min_date - # (essentially removes videos uploaded before min_date) - # Prevents issues where some segments of a video are excluded - del db[key] - elif all(datetime.fromtimestamp(x['submission_time']) > max_date for x in db[key]): - # Remove videos where all of its segments were submitted after max_date - # (essentially removes videos uploaded after max_date) - # Allows for segments to be corrected for past videos - del db[key] - elif any(not x['locked'] and x['views'] < preprocess_args.min_views for x in db[key]): - # Remove videos where any of its non-locked segments do not have enough views - # (essentially skips videos that have not been fully watched/reviewed) - # Always include segments locked by VIPs, regardless of view count - del db[key] - - logger.info(f'Saved {len(db)} videos') - - with open(processed_db_path, 'w') as fp: - json.dump(db, fp) - - return db - - if preprocess_args.do_process_database: - read_db() - - # 'videoID', 'startTime', 'endTime', 'votes', 'locked', 'incorrectVotes', 'UUID', - # 'userID', 'timeSubmitted', 'views', 'category', 'actionType', 'service', 'videoDuration', - # 'hidden', 'reputation', 'shadowHidden', 'hashedVideoID', 'userAgent', 'description' - if preprocess_args.do_transcribe: - logger.info('Collecting videos') - parsed_database = read_db() - - # Remove transcripts already processed - finished = set(x.split('.')[0] for x in os.listdir( - 'transcripts/auto/') + os.listdir('transcripts/manual/')) - - video_ids = list(parsed_database.keys() - finished) - - # https://stackoverflow.com/a/63495323 - import concurrent - POLL_INTERVAL = 0.1 - - # Wrap get words function to return video_id after completion - def get_words_wrapper(video_id): - get_words(video_id) - return video_id - - logger.info('Setting up ThreadPoolExecutor') - with concurrent.futures.ThreadPoolExecutor(max_workers=preprocess_args.num_jobs) as pool, \ - tqdm(total=len(video_ids)) as progress: - - all_futures = (pool.submit(get_words_wrapper, video_id) - for video_id in video_ids) - to_process = set(itertools.islice( - all_futures, preprocess_args.num_jobs)) - try: - while to_process: - just_finished, to_process = concurrent.futures.wait( - to_process, timeout=POLL_INTERVAL) - to_process |= set(itertools.islice( - all_futures, len(just_finished))) - - for d in just_finished: - progress.set_description(f'Processed {d.result()}') - progress.update() - - except KeyboardInterrupt: - logger.info( - 'Gracefully shutting down: Cancelling unscheduled tasks') - - # only futures that are not done will prevent exiting - for future in to_process: - future.cancel() - - logger.info('Waiting for in-progress tasks to complete') - concurrent.futures.wait(to_process, timeout=None) - logger.info('Cancellation successful') - - final_path = os.path.join( - dataset_args.data_dir, dataset_args.processed_file) - - if preprocess_args.do_create: - logger.info('Create final data') - - final_data = {} - - parsed_database = read_db() - - transcribed = set(x.split('.')[0] for x in os.listdir( - 'transcripts/auto/') + os.listdir('transcripts/manual/')) - - # Only consider videos that have been transcribed already - video_ids = parsed_database.keys() & transcribed - - with tqdm(total=len(video_ids)) as progress: - for index, video_id in enumerate(video_ids): - if preprocess_args.max_videos is not None and index >= preprocess_args.max_videos: - break - progress.set_description(f'Processing {video_id}') - progress.update() - - video_words = get_words(video_id, process=False) - if not video_words: - continue - - final_vid_segs = [] - # Only add segments with high enough wps - for seg in parsed_database[video_id]: - segment_words = segment.extract_segment( - video_words, seg['start'], seg['end']) - - if len(segment_words) <= 1: - continue # Useless to add segment since no words - - # duration = segment.word_end(segment_words[-1]) - segment.word_start(segment_words[0]) - duration = seg['end'] - seg['start'] - wps = len(segment_words)/duration if duration > 0 else 0 - - # print(video_id, wps) - if wps < preprocess_args.min_wps: - # Skip sponsor segments without many words - # e.g. music ads with some words on each side - # progress.set_description(f'Skipping bad segment in {video_id} (wps={wps})') - continue - final_vid_segs.append(seg) - - if final_vid_segs: - final_data[video_id] = final_vid_segs - - # Save data - with open(final_path, 'w') as fp: - json.dump(final_data, fp) - - # final_data = preprocess( - # raw_dataset_path, final_path, preprocess_args.min_votes) - # # TODO save metadata in final.json? - - elif os.path.exists(final_path): - # Already exists - logging.info(f'{final_path} exists, opening file') - with open(final_path) as fp: - final_data = json.load(fp) - logging.info(f'Found {len(final_data)} videos') - else: - return # Do not continue - - # TODO shuffle final_data - # if not os.path.exists(excess_path) or preprocess_args.overwrite - # TODO use overwrite param - - positive_file = os.path.join( - dataset_args.data_dir, preprocess_args.positive_file) - negative_file = os.path.join( - dataset_args.data_dir, preprocess_args.negative_file) - - if preprocess_args.do_generate: - logger.info('Generating') - # max_videos=preprocess_args.max_videos, - # max_segments=preprocess_args.max_segments, - # , max_videos, max_segments - - from model import get_model_tokenizer - model, tokenizer = get_model_tokenizer(model_args, general_args) - - # TODO - # count_videos = 0 - # count_segments = 0 - - data = final_data.items() - - start_index = preprocess_args.start_index or 0 - end_index = (preprocess_args.max_videos or len(data)) + start_index - - data = list(itertools.islice(data, start_index, end_index)) - - write_mode = 'w' # if preprocess_args.overwrite else 'a' - with open(positive_file, write_mode, encoding='utf-8') as positive, \ - open(negative_file, write_mode, encoding='utf-8') as negative, \ - tqdm(data) as progress: - - for offset, (video_id, sponsor_segments) in enumerate(data): - - progress.set_description(f'Processing {video_id}') - progress.update() - - # Use chunk granularity to improve manual transcripts - words = get_words(video_id, process=False, granularity='chunk') - if not words: - continue - - if len(words) <= 1: - continue - - segments = segment.generate_labelled_segments( - words, tokenizer, segmentation_args, sponsor_segments) - - if not segments: - continue - - for seg in segments: - seg_start = segment.word_start(seg[0]) - seg_end = segment.word_end(seg[-1]) - duration = seg_end - seg_start - wps = len(seg)/duration if duration > 0 else 0 - - # Ignore segments with "not enough words" in the transcript - # Must do here since this includes non-sponsor segments - if wps < preprocess_args.min_wps: - continue - - d = { - # 'video_index': offset + start_index, - 'video_id': video_id, - # 'uuid': video_id, # TODO add uuid - 'text': ' '.join(x['cleaned'] for x in seg), - 'start': seg_start, - 'end': seg_end, - } - - extracted_segments = extract_sponsors(seg) - if extracted_segments: - extracted_texts = [] - for s in extracted_segments: - w = ' '.join(q['cleaned'] for q in s['words']) - category = s['category'].upper() - extracted_texts.append( - f'{START_SEGMENT_TEMPLATE.format(category)} {w} {END_SEGMENT_TEMPLATE.format(category)}' - ) - - d['extracted'] = f' {CustomTokens.BETWEEN_SEGMENTS.value} '.join( - extracted_texts) - print(json.dumps(d), file=positive) - - else: - d['extracted'] = CustomTokens.NO_SEGMENT.value - print(json.dumps(d), file=negative) - - if preprocess_args.do_split: - logger.info('Splitting') - logger.info('Read files') - - with open(positive_file, encoding='utf-8') as positive: - sponsors = positive.readlines() - - with open(negative_file, encoding='utf-8') as negative: - non_sponsors = negative.readlines() - - logger.info('Shuffle') - random.shuffle(sponsors) - random.shuffle(non_sponsors) - - logger.info('Calculate ratios') - # Ensure correct ratio of positive to negative segments - percentage_negative = 1 - preprocess_args.percentage_positive - - if preprocess_args.percentage_positive * len(sponsors) > len(non_sponsors): - # Negative is limiting - z = int(preprocess_args.percentage_positive / - percentage_negative * len(non_sponsors)) - - # excess = sponsors[z:] - sponsors = sponsors[:z] - - else: - # Positive is limiting - z = int(percentage_negative / - preprocess_args.percentage_positive * len(sponsors)) - - # excess = non_sponsors[z:] - non_sponsors = non_sponsors[:z] - - logger.info('Join') - all_labelled_segments = sponsors + non_sponsors - - random.shuffle(all_labelled_segments) - - # TODO split based on video ids - logger.info('Split') - ratios = [preprocess_args.train_split, - preprocess_args.test_split, - preprocess_args.valid_split] - - train_data, test_data, valid_data = split( - all_labelled_segments, ratios) - - splits = { - dataset_args.train_file: train_data, - dataset_args.test_file: test_data, - dataset_args.validation_file: valid_data - } - - # Output training, testing and validation data - for name, items in splits.items(): - outfile = os.path.join(dataset_args.data_dir, name) - with open(outfile, 'w', encoding='utf-8') as fp: - fp.writelines(items) - - classifier_splits = { - dataset_args.c_train_file: train_data, - dataset_args.c_test_file: test_data, - dataset_args.c_validation_file: valid_data - } - - none_category = CATEGORIES.index(None) - - # Output training, testing and validation data - for name, items in classifier_splits.items(): - outfile = os.path.join(dataset_args.data_dir, name) - with open(outfile, 'w', encoding='utf-8') as fp: - for item in items: - parsed_item = json.loads(item) # TODO add uuid - - matches = extract_sponsor_matches_from_text( - parsed_item['extracted']) - - if matches: - for match in matches: - print(json.dumps({ - 'text': match['text'], - 'label': CATEGORIES.index(match['category']) - }), file=fp) - else: - print(json.dumps({ - 'text': parsed_item['text'], - 'label': none_category - }), file=fp) - - logger.info('Write') - # Save excess items - # excess_path = os.path.join( - # dataset_args.data_dir, dataset_args.excess_file) - # if not os.path.exists(excess_path) or preprocess_args.overwrite: - # with open(excess_path, 'w', encoding='utf-8') as fp: - # fp.writelines(excess) - # else: - # logger.info(f'Skipping {dataset_args.excess_file}') - - logger.info( - f'Finished splitting: {len(sponsors)} sponsors, {len(non_sponsors)} non sponsors') - - -def split(arr, ratios): - """Split array according to ratios. Sum of ratios should be <= 1""" - to_return = [] - - cumulative_sum = 0 - for r in ratios: - current = cumulative_sum - cumulative_sum += r * len(arr) - to_return.append(arr[int(current):int(cumulative_sum)]) - - return to_return - - -if __name__ == '__main__': - main() diff --git a/spaces/Xhaheen/GPTJ_PLUS_DALL_E/README.md b/spaces/Xhaheen/GPTJ_PLUS_DALL_E/README.md deleted file mode 100644 index dad0e2989d6e56e06ac8be50e6863c9070f09765..0000000000000000000000000000000000000000 --- a/spaces/Xhaheen/GPTJ_PLUS_DALL_E/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: GPTJ_PLUS_DALL_E -emoji: 📘 🎨 -colorFrom: green -colorTo: red -sdk: gradio -sdk_version: 3.0.2 -app_file: app.py -pinned: false -license: gpl ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/XzJosh/Jiaran-Bert-VITS2/text/chinese.py b/spaces/XzJosh/Jiaran-Bert-VITS2/text/chinese.py deleted file mode 100644 index 276753880b73de2e8889dcb2101cd98c09e0710b..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/Jiaran-Bert-VITS2/text/chinese.py +++ /dev/null @@ -1,193 +0,0 @@ -import os -import re - -import cn2an -from pypinyin import lazy_pinyin, Style - -from text import symbols -from text.symbols import punctuation -from text.tone_sandhi import ToneSandhi - -current_file_path = os.path.dirname(__file__) -pinyin_to_symbol_map = {line.split("\t")[0]: line.strip().split("\t")[1] for line in - open(os.path.join(current_file_path, 'opencpop-strict.txt')).readlines()} - -import jieba.posseg as psg - - -rep_map = { - ':': ',', - ';': ',', - ',': ',', - '。': '.', - '!': '!', - '?': '?', - '\n': '.', - "·": ",", - '、': ",", - '...': '…', - '$': '.', - '“': "'", - '”': "'", - '‘': "'", - '’': "'", - '(': "'", - ')': "'", - '(': "'", - ')': "'", - '《': "'", - '》': "'", - '【': "'", - '】': "'", - '[': "'", - ']': "'", - '—': "-", - '~': "-", - '~': "-", - '「': "'", - '」': "'", - -} - -tone_modifier = ToneSandhi() - -def replace_punctuation(text): - text = text.replace("嗯", "恩").replace("呣","母") - pattern = re.compile('|'.join(re.escape(p) for p in rep_map.keys())) - - replaced_text = pattern.sub(lambda x: rep_map[x.group()], text) - - replaced_text = re.sub(r'[^\u4e00-\u9fa5'+"".join(punctuation)+r']+', '', replaced_text) - - return replaced_text - -def g2p(text): - pattern = r'(?<=[{0}])\s*'.format(''.join(punctuation)) - sentences = [i for i in re.split(pattern, text) if i.strip()!=''] - phones, tones, word2ph = _g2p(sentences) - assert sum(word2ph) == len(phones) - assert len(word2ph) == len(text) #Sometimes it will crash,you can add a try-catch. - phones = ['_'] + phones + ["_"] - tones = [0] + tones + [0] - word2ph = [1] + word2ph + [1] - return phones, tones, word2ph - - -def _get_initials_finals(word): - initials = [] - finals = [] - orig_initials = lazy_pinyin( - word, neutral_tone_with_five=True, style=Style.INITIALS) - orig_finals = lazy_pinyin( - word, neutral_tone_with_five=True, style=Style.FINALS_TONE3) - for c, v in zip(orig_initials, orig_finals): - initials.append(c) - finals.append(v) - return initials, finals - - -def _g2p(segments): - phones_list = [] - tones_list = [] - word2ph = [] - for seg in segments: - pinyins = [] - # Replace all English words in the sentence - seg = re.sub('[a-zA-Z]+', '', seg) - seg_cut = psg.lcut(seg) - initials = [] - finals = [] - seg_cut = tone_modifier.pre_merge_for_modify(seg_cut) - for word, pos in seg_cut: - if pos == 'eng': - continue - sub_initials, sub_finals = _get_initials_finals(word) - sub_finals = tone_modifier.modified_tone(word, pos, - sub_finals) - initials.append(sub_initials) - finals.append(sub_finals) - - # assert len(sub_initials) == len(sub_finals) == len(word) - initials = sum(initials, []) - finals = sum(finals, []) - # - for c, v in zip(initials, finals): - raw_pinyin = c+v - # NOTE: post process for pypinyin outputs - # we discriminate i, ii and iii - if c == v: - assert c in punctuation - phone = [c] - tone = '0' - word2ph.append(1) - else: - v_without_tone = v[:-1] - tone = v[-1] - - pinyin = c+v_without_tone - assert tone in '12345' - - if c: - # 多音节 - v_rep_map = { - "uei": 'ui', - 'iou': 'iu', - 'uen': 'un', - } - if v_without_tone in v_rep_map.keys(): - pinyin = c+v_rep_map[v_without_tone] - else: - # 单音节 - pinyin_rep_map = { - 'ing': 'ying', - 'i': 'yi', - 'in': 'yin', - 'u': 'wu', - } - if pinyin in pinyin_rep_map.keys(): - pinyin = pinyin_rep_map[pinyin] - else: - single_rep_map = { - 'v': 'yu', - 'e': 'e', - 'i': 'y', - 'u': 'w', - } - if pinyin[0] in single_rep_map.keys(): - pinyin = single_rep_map[pinyin[0]]+pinyin[1:] - - assert pinyin in pinyin_to_symbol_map.keys(), (pinyin, seg, raw_pinyin) - phone = pinyin_to_symbol_map[pinyin].split(' ') - word2ph.append(len(phone)) - - phones_list += phone - tones_list += [int(tone)] * len(phone) - return phones_list, tones_list, word2ph - - - -def text_normalize(text): - numbers = re.findall(r'\d+(?:\.?\d+)?', text) - for number in numbers: - text = text.replace(number, cn2an.an2cn(number), 1) - text = replace_punctuation(text) - return text - -def get_bert_feature(text, word2ph): - from text import chinese_bert - return chinese_bert.get_bert_feature(text, word2ph) - -if __name__ == '__main__': - from text.chinese_bert import get_bert_feature - text = "啊!但是《原神》是由,米哈\游自主, [研发]的一款全.新开放世界.冒险游戏" - text = text_normalize(text) - print(text) - phones, tones, word2ph = g2p(text) - bert = get_bert_feature(text, word2ph) - - print(phones, tones, word2ph, bert.shape) - - -# # 示例用法 -# text = "这是一个示例文本:,你好!这是一个测试...." -# print(g2p_paddle(text)) # 输出: 这是一个示例文本你好这是一个测试 diff --git a/spaces/XzJosh/Lumi-Bert-VITS2/resample.py b/spaces/XzJosh/Lumi-Bert-VITS2/resample.py deleted file mode 100644 index 2ed1685654a371c5722168e9987809b05b1cb224..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/Lumi-Bert-VITS2/resample.py +++ /dev/null @@ -1,42 +0,0 @@ -import os -import argparse -import librosa -import numpy as np -from multiprocessing import Pool, cpu_count - -import soundfile -from scipy.io import wavfile -from tqdm import tqdm - - -def process(item): - spkdir, wav_name, args = item - speaker = spkdir.replace("\\", "/").split("/")[-1] - wav_path = os.path.join(args.in_dir, speaker, wav_name) - if os.path.exists(wav_path) and '.wav' in wav_path: - os.makedirs(os.path.join(args.out_dir, speaker), exist_ok=True) - wav, sr = librosa.load(wav_path, sr=args.sr) - soundfile.write( - os.path.join(args.out_dir, speaker, wav_name), - wav, - sr - ) - - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--sr", type=int, default=44100, help="sampling rate") - parser.add_argument("--in_dir", type=str, default="./raw", help="path to source dir") - parser.add_argument("--out_dir", type=str, default="./dataset", help="path to target dir") - args = parser.parse_args() - # processs = 8 - processs = cpu_count()-2 if cpu_count() >4 else 1 - pool = Pool(processes=processs) - - for speaker in os.listdir(args.in_dir): - spk_dir = os.path.join(args.in_dir, speaker) - if os.path.isdir(spk_dir): - print(spk_dir) - for _ in tqdm(pool.imap_unordered(process, [(spk_dir, i, args) for i in os.listdir(spk_dir) if i.endswith("wav")])): - pass diff --git a/spaces/YFHAki/DeepDanbooru_string/app.py b/spaces/YFHAki/DeepDanbooru_string/app.py deleted file mode 100644 index 49019837c9207cc68cb37be0342f3bc44fd0decb..0000000000000000000000000000000000000000 --- a/spaces/YFHAki/DeepDanbooru_string/app.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python - -from __future__ import annotations - -import argparse -import functools -import os -import html -import pathlib -import tarfile - -import deepdanbooru as dd -import gradio as gr -import huggingface_hub -import numpy as np -import PIL.Image -import tensorflow as tf -import piexif -import piexif.helper - -TITLE = 'DeepDanbooru String' - -TOKEN = os.environ['TOKEN'] -MODEL_REPO = 'CikeyQI/DeepDanbooru_string' -MODEL_FILENAME = 'model-resnet_custom_v3.h5' -LABEL_FILENAME = 'tags.txt' - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser() - parser.add_argument('--score-slider-step', type=float, default=0.05) - parser.add_argument('--score-threshold', type=float, default=0.5) - parser.add_argument('--theme', type=str, default='dark-grass') - parser.add_argument('--live', action='store_true') - parser.add_argument('--share', action='store_true') - parser.add_argument('--port', type=int) - parser.add_argument('--disable-queue', - dest='enable_queue', - action='store_false') - parser.add_argument('--allow-flagging', type=str, default='never') - return parser.parse_args() - - -def load_sample_image_paths() -> list[pathlib.Path]: - image_dir = pathlib.Path('images') - if not image_dir.exists(): - dataset_repo = 'hysts/sample-images-TADNE' - path = huggingface_hub.hf_hub_download(dataset_repo, - 'images.tar.gz', - repo_type='dataset', - use_auth_token=TOKEN) - with tarfile.open(path) as f: - f.extractall() - return sorted(image_dir.glob('*')) - - -def load_model() -> tf.keras.Model: - path = huggingface_hub.hf_hub_download(MODEL_REPO, - MODEL_FILENAME, - use_auth_token=TOKEN) - model = tf.keras.models.load_model(path) - return model - - -def load_labels() -> list[str]: - path = huggingface_hub.hf_hub_download(MODEL_REPO, - LABEL_FILENAME, - use_auth_token=TOKEN) - with open(path) as f: - labels = [line.strip() for line in f.readlines()] - return labels - -def plaintext_to_html(text): - text = "

      " + "
      \n".join([f"{html.escape(x)}" for x in text.split('\n')]) + "

      " - return text - -def predict(image: PIL.Image.Image, score_threshold: float, - model: tf.keras.Model, labels: list[str]) -> dict[str, float]: - rawimage = image - _, height, width, _ = model.input_shape - image = np.asarray(image) - image = tf.image.resize(image, - size=(height, width), - method=tf.image.ResizeMethod.AREA, - preserve_aspect_ratio=True) - image = image.numpy() - image = dd.image.transform_and_pad_image(image, width, height) - image = image / 255. - probs = model.predict(image[None, ...])[0] - probs = probs.astype(float) - res = dict() - for prob, label in zip(probs.tolist(), labels): - if prob < score_threshold: - continue - res[label] = prob - b = dict(sorted(res.items(),key=lambda item:item[1], reverse=True)) - a = ', '.join(list(b.keys())).replace('_',' ').replace('(','\(').replace(')','\)') - c = ', '.join(list(b.keys())) - - items = rawimage.info - geninfo = '' - - if "exif" in rawimage.info: - exif = piexif.load(rawimage.info["exif"]) - exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'') - try: - exif_comment = piexif.helper.UserComment.load(exif_comment) - except ValueError: - exif_comment = exif_comment.decode('utf8', errors="ignore") - - items['exif comment'] = exif_comment - geninfo = exif_comment - - for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif', - 'loop', 'background', 'timestamp', 'duration']: - items.pop(field, None) - - geninfo = items.get('parameters', geninfo) - - info = f""" -

      PNG Info

      -""" - for key, text in items.items(): - info += f""" -
      -

      {plaintext_to_html(str(key))}

      -

      {plaintext_to_html(str(text))}

      -
      -""".strip()+"\n" - - if len(info) == 0: - message = "Nothing found in the image." - info = f"

      {message}

      " - - return (a,c,res,info) - - -def main(): - args = parse_args() - model = load_model() - labels = load_labels() - - func = functools.partial(predict, model=model, labels=labels) - func = functools.update_wrapper(func, predict) - - gr.Interface( - func, - [ - gr.inputs.Image(type='pil', label='Input'), - gr.inputs.Slider(0, - 1, - step=args.score_slider_step, - default=args.score_threshold, - label='Score Threshold'), - ], - [ - gr.outputs.Textbox(label='Output (string)'), - gr.outputs.Textbox(label='Output (raw string)'), - gr.outputs.Label(label='Output (label)'), - gr.outputs.HTML() - ], - examples=[ - ['miku.jpg',0.5], - ['miku2.jpg',0.5] - ], - title=TITLE, - description=''' -Demo for [KichangKim/DeepDanbooru](https://github.com/KichangKim/DeepDanbooru) with "ready to copy" prompt and a prompt analyzer. - -Modified from [hysts/DeepDanbooru](https://huggingface.co/spaces/hysts/DeepDanbooru) - -PNG Info code forked from [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) - ''', - theme=args.theme, - allow_flagging=args.allow_flagging, - live=args.live, - ).launch( - enable_queue=args.enable_queue, - server_port=args.port, - share=args.share, - ) - - -if __name__ == '__main__': - main() diff --git a/spaces/Yasu55/stable-diffusion-webui/app.py b/spaces/Yasu55/stable-diffusion-webui/app.py deleted file mode 100644 index 71bad0a3aeda52448f1fbf0fab82452f88b67ada..0000000000000000000000000000000000000000 --- a/spaces/Yasu55/stable-diffusion-webui/app.py +++ /dev/null @@ -1,77 +0,0 @@ -import os -from subprocess import getoutput - -gpu_info = getoutput('nvidia-smi') -if("A10G" in gpu_info): - os.system(f"pip install -q https://github.com/camenduru/stable-diffusion-webui-colab/releases/download/0.0.15/xformers-0.0.15.dev0+4c06c79.d20221205-cp38-cp38-linux_x86_64.whl") -elif("T4" in gpu_info): - os.system(f"pip install -q https://github.com/camenduru/stable-diffusion-webui-colab/releases/download/0.0.15/xformers-0.0.15.dev0+1515f77.d20221130-cp38-cp38-linux_x86_64.whl") - -os.system(f"git clone https://github.com/camenduru/stable-diffusion-webui /home/user/app/stable-diffusion-webui") -os.chdir("/home/user/app/stable-diffusion-webui") - -os.system(f"wget -q https://github.com/camenduru/webui/raw/main/env_patch.py -O /home/user/app/env_patch.py") -os.system(f"sed -i -e '/import image_from_url_text/r /home/user/app/env_patch.py' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f"sed -i -e '/(modelmerger_interface, \"Checkpoint Merger\", \"modelmerger\"),/d' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f"sed -i -e '/(train_interface, \"Train\", \"ti\"),/d' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f"sed -i -e '/extensions_interface, \"Extensions\", \"extensions\"/d' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f"sed -i -e '/settings_interface, \"Settings\", \"settings\"/d' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f'''sed -i -e "s/document.getElementsByTagName('gradio-app')\[0\].shadowRoot/!!document.getElementsByTagName('gradio-app')[0].shadowRoot ? document.getElementsByTagName('gradio-app')[0].shadowRoot : document/g" /home/user/app/stable-diffusion-webui/script.js''') -os.system(f"sed -i -e 's/ show_progress=False,/ show_progress=True,/g' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f"sed -i -e 's/shared.demo.launch/shared.demo.queue().launch/g' /home/user/app/stable-diffusion-webui/webui.py") -os.system(f"sed -i -e 's/ outputs=\[/queue=False, &/g' /home/user/app/stable-diffusion-webui/modules/ui.py") -os.system(f"sed -i -e 's/ queue=False, / /g' /home/user/app/stable-diffusion-webui/modules/ui.py") - -# ----------------------------Please duplicate this space and delete this block if you don't want to see the extra header---------------------------- -os.system(f"wget -q https://github.com/camenduru/webui/raw/main/header_patch.py -O /home/user/app/header_patch.py") -os.system(f"sed -i -e '/demo:/r /home/user/app/header_patch.py' /home/user/app/stable-diffusion-webui/modules/ui.py") -# --------------------------------------------------------------------------------------------------------------------------------------------------- - -if "IS_SHARED_UI" in os.environ: - os.system(f"rm -rfv /home/user/app/stable-diffusion-webui/scripts/") - - os.system(f"wget -q https://github.com/camenduru/webui/raw/main/shared-config.json -O /home/user/app/shared-config.json") - os.system(f"wget -q https://github.com/camenduru/webui/raw/main/shared-ui-config.json -O /home/user/app/shared-ui-config.json") - - os.system(f"wget -q {os.getenv('MODEL_LINK')} -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/{os.getenv('MODEL_NAME')}") - os.system(f"wget -q {os.getenv('VAE_LINK')} -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/{os.getenv('VAE_NAME')}") - - os.system(f"python launch.py --force-enable-xformers --disable-console-progressbars --enable-console-prompts --ui-config-file /home/user/app/shared-ui-config.json --ui-settings-file /home/user/app/shared-config.json --cors-allow-origins huggingface.co,hf.space --no-progressbar-hiding") -else: - # Please duplicate this space and delete # character in front of the custom script you want to use or add here more custom scripts with same structure os.system(f"wget -q https://CUSTOM_SCRIPT_URL -O /home/user/app/stable-diffusion-webui/scripts/CUSTOM_SCRIPT_NAME.py") - os.system(f"wget -q https://gist.github.com/camenduru/9ec5f8141db9902e375967e93250860f/raw/d0bcf01786f20107c329c03f8968584ee67be12a/run_n_times.py -O /home/user/app/stable-diffusion-webui/scripts/run_n_times.py") - - - #os.system(f"git clone https://github.com/camenduru/stable-diffusion-webui-artists-to-study /home/user/app/stable-diffusion-webui/extensions/stable-diffusion-webui-artists-to-study") - os.system(f"git clone https://github.com/yfszzx/stable-diffusion-webui-images-browser /home/user/app/stable-diffusion-webui/extensions/stable-diffusion-webui-images-browser") - os.system(f"git clone https://github.com/deforum-art/deforum-for-automatic1111-webui /home/user/app/stable-diffusion-webui/extensions/deforum-for-automatic1111-webui") - - # Please duplicate this space and delete # character in front of the model you want to use or add here more ckpts with same structure os.system(f"wget -q https://CKPT_URL -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/CKPT_NAME.ckpt") - #os.system(f"wget -q https://huggingface.co/nitrosocke/Arcane-Diffusion/resolve/main/arcane-diffusion-v3.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/arcane-diffusion-v3.ckpt") - #os.system(f"wget -q https://huggingface.co/DGSpitzer/Cyberpunk-Anime-Diffusion/resolve/main/Cyberpunk-Anime-Diffusion.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/Cyberpunk-Anime-Diffusion.ckpt") - #os.system(f"wget -q https://huggingface.co/prompthero/midjourney-v4-diffusion/resolve/main/mdjrny-v4.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/mdjrny-v4.ckpt") - #os.system(f"wget -q https://huggingface.co/nitrosocke/mo-di-diffusion/resolve/main/moDi-v1-pruned.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/moDi-v1-pruned.ckpt") - #os.system(f"wget -q https://huggingface.co/Fictiverse/Stable_Diffusion_PaperCut_Model/resolve/main/PaperCut_v1.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/PaperCut_v1.ckpt") - #os.system(f"wget -q https://huggingface.co/lilpotat/sa/resolve/main/samdoesarts_style.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/samdoesarts_style.ckpt") - #os.system(f"wget -q https://huggingface.co/hakurei/waifu-diffusion-v1-3/resolve/main/wd-v1-3-float32.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/wd-v1-3-float32.ckpt") - #os.system(f"wget -q https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/sd-v1-4.ckpt") - #os.system(f"wget -q https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/v1-5-pruned-emaonly.ckpt") - #os.system(f"wget -q https://huggingface.co/runwayml/stable-diffusion-inpainting/resolve/main/sd-v1-5-inpainting.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/sd-v1-5-inpainting.ckpt") - - #os.system(f"wget -q https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/Anything-V3.0-pruned.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/Anything-V3.0-pruned.ckpt") - #os.system(f"wget -q https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/Anything-V3.0.vae.pt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/Anything-V3.0-pruned.vae.pt") - - #os.system(f"wget -q https://huggingface.co/stabilityai/stable-diffusion-2/resolve/main/768-v-ema.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/768-v-ema.ckpt") - #os.system(f"wget -q https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/768-v-ema.yaml") - os.system(f"wget -q https://r2.kamiya-b.me/dreambooth_lib/akakura-sn.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/akakura-sn.ckpt") - #os.system(f"wget -q https://huggingface.co/stabilityai/stable-diffusion-2-1/resolve/main/v2-1_768-ema-pruned.ckpt -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/v2-1_768-ema-pruned.ckpt") - os.system(f"wget -q https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/v2-1_768-ema-pruned.yaml") - - - os.system(f"wget -q {os.getenv('MODEL_LINK')} -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/{os.getenv('MODEL_NAME')}") - os.system(f"wget -q {os.getenv('VAE_LINK')} -O /home/user/app/stable-diffusion-webui/models/Stable-diffusion/{os.getenv('VAE_NAME')}") - - - - os.system(f"python launch.py --ui-config-file /home/user/app/ui-config.json --ui-settings-file /home/user/app/config.json --disable-console-progressbars --enable-console-prompts --cors-allow-origins huggingface.co,hf.space --no-progressbar-hiding --api --skip-torch-cuda-test") - \ No newline at end of file diff --git a/spaces/YazawaSunrise/so-vits-svc-LoveLive/train.py b/spaces/YazawaSunrise/so-vits-svc-LoveLive/train.py deleted file mode 100644 index 97557410edb18717b0330c602fbaa9984f647b13..0000000000000000000000000000000000000000 --- a/spaces/YazawaSunrise/so-vits-svc-LoveLive/train.py +++ /dev/null @@ -1,281 +0,0 @@ -import logging -logging.getLogger('matplotlib').setLevel(logging.WARNING) -import os -import json -import argparse -import itertools -import math -import torch -from torch import nn, optim -from torch.nn import functional as F -from torch.utils.data import DataLoader -from torch.utils.tensorboard import SummaryWriter -import torch.multiprocessing as mp -import torch.distributed as dist -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.cuda.amp import autocast, GradScaler - -import commons -import utils -from data_utils import TextAudioSpeakerLoader, EvalDataLoader -from models import ( - SynthesizerTrn, - MultiPeriodDiscriminator, -) -from losses import ( - kl_loss, - generator_loss, discriminator_loss, feature_loss -) - -from mel_processing import mel_spectrogram_torch, spec_to_mel_torch - -torch.backends.cudnn.benchmark = True -global_step = 0 - - -# os.environ['TORCH_DISTRIBUTED_DEBUG'] = 'INFO' - - -def main(): - """Assume Single Node Multi GPUs Training Only""" - assert torch.cuda.is_available(), "CPU training is not allowed." - hps = utils.get_hparams() - - n_gpus = torch.cuda.device_count() - os.environ['MASTER_ADDR'] = 'localhost' - os.environ['MASTER_PORT'] = hps.train.port - - mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,)) - - -def run(rank, n_gpus, hps): - global global_step - if rank == 0: - logger = utils.get_logger(hps.model_dir) - logger.info(hps) - utils.check_git_hash(hps.model_dir) - writer = SummaryWriter(log_dir=hps.model_dir) - writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) - - dist.init_process_group(backend='nccl', init_method='env://', world_size=n_gpus, rank=rank) - torch.manual_seed(hps.train.seed) - torch.cuda.set_device(rank) - - train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps) - train_loader = DataLoader(train_dataset, num_workers=8, shuffle=False, pin_memory=True, - batch_size=hps.train.batch_size) - if rank == 0: - eval_dataset = EvalDataLoader(hps.data.validation_files, hps) - eval_loader = DataLoader(eval_dataset, num_workers=1, shuffle=False, - batch_size=1, pin_memory=False, - drop_last=False) - - net_g = SynthesizerTrn( - hps.data.filter_length // 2 + 1, - hps.train.segment_size // hps.data.hop_length, - **hps.model).cuda(rank) - net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) - optim_g = torch.optim.AdamW( - net_g.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - optim_d = torch.optim.AdamW( - net_d.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - net_g = DDP(net_g, device_ids=[rank]) # , find_unused_parameters=True) - net_d = DDP(net_d, device_ids=[rank]) - - try: - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, - optim_g) - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, - optim_d) - global_step = (epoch_str - 1) * len(train_loader) - except: - epoch_str = 1 - global_step = 0 - - scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) - scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) - - scaler = GradScaler(enabled=hps.train.fp16_run) - - for epoch in range(epoch_str, hps.train.epochs + 1): - if rank == 0: - train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, - [train_loader, eval_loader], logger, [writer, writer_eval]) - else: - train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, - [train_loader, None], None, None) - scheduler_g.step() - scheduler_d.step() - - -def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): - net_g, net_d = nets - optim_g, optim_d = optims - scheduler_g, scheduler_d = schedulers - train_loader, eval_loader = loaders - if writers is not None: - writer, writer_eval = writers - - # train_loader.batch_sampler.set_epoch(epoch) - global global_step - - net_g.train() - net_d.train() - for batch_idx, items in enumerate(train_loader): - c, f0, spec, y, spk = items - g = spk.cuda(rank, non_blocking=True) - spec, y = spec.cuda(rank, non_blocking=True), y.cuda(rank, non_blocking=True) - c = c.cuda(rank, non_blocking=True) - f0 = f0.cuda(rank, non_blocking=True) - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax) - - with autocast(enabled=hps.train.fp16_run): - y_hat, ids_slice, z_mask, \ - (z, z_p, m_p, logs_p, m_q, logs_q) = net_g(c, f0, spec, g=g, mel=mel) - - y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) - y_hat_mel = mel_spectrogram_torch( - y_hat.squeeze(1), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax - ) - y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice - - # Discriminator - y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) - - with autocast(enabled=False): - loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) - loss_disc_all = loss_disc - - optim_d.zero_grad() - scaler.scale(loss_disc_all).backward() - scaler.unscale_(optim_d) - grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) - scaler.step(optim_d) - - with autocast(enabled=hps.train.fp16_run): - # Generator - y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) - with autocast(enabled=False): - loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel - loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl - loss_fm = feature_loss(fmap_r, fmap_g) - loss_gen, losses_gen = generator_loss(y_d_hat_g) - loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl - optim_g.zero_grad() - scaler.scale(loss_gen_all).backward() - scaler.unscale_(optim_g) - grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) - scaler.step(optim_g) - scaler.update() - - if rank == 0: - if global_step % hps.train.log_interval == 0: - lr = optim_g.param_groups[0]['lr'] - losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_kl] - logger.info('Train Epoch: {} [{:.0f}%]'.format( - epoch, - 100. * batch_idx / len(train_loader))) - logger.info([x.item() for x in losses] + [global_step, lr]) - - scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, - "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g} - scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/kl": loss_kl}) - - scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}) - scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}) - scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)}) - image_dict = { - "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()), - "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()), - "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()), - } - - utils.summarize( - writer=writer, - global_step=global_step, - images=image_dict, - scalars=scalar_dict - ) - - if global_step % hps.train.eval_interval == 0: - evaluate(hps, net_g, eval_loader, writer_eval) - utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, - os.path.join(hps.model_dir, "G_{}.pth".format(global_step))) - utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, - os.path.join(hps.model_dir, "D_{}.pth".format(global_step))) - global_step += 1 - - if rank == 0: - logger.info('====> Epoch: {}'.format(epoch)) - - -def evaluate(hps, generator, eval_loader, writer_eval): - generator.eval() - image_dict = {} - audio_dict = {} - with torch.no_grad(): - for batch_idx, items in enumerate(eval_loader): - c, f0, spec, y, spk = items - g = spk[:1].cuda(0) - spec, y = spec[:1].cuda(0), y[:1].cuda(0) - c = c[:1].cuda(0) - f0 = f0[:1].cuda(0) - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax) - y_hat = generator.module.infer(c, f0, g=g, mel=mel) - - y_hat_mel = mel_spectrogram_torch( - y_hat.squeeze(1).float(), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax - ) - - audio_dict.update({ - f"gen/audio_{batch_idx}": y_hat[0], - f"gt/audio_{batch_idx}": y[0] - }) - image_dict.update({ - f"gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()), - "gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy()) - }) - utils.summarize( - writer=writer_eval, - global_step=global_step, - images=image_dict, - audios=audio_dict, - audio_sampling_rate=hps.data.sampling_rate - ) - generator.train() - - -if __name__ == "__main__": - main() diff --git a/spaces/Yiqin/ChatVID/model/vision/grit_src/third_party/CenterNet2/detectron2/evaluation/pascal_voc_evaluation.py b/spaces/Yiqin/ChatVID/model/vision/grit_src/third_party/CenterNet2/detectron2/evaluation/pascal_voc_evaluation.py deleted file mode 100644 index 1d1abcde2f87bb5f103e73cb364aaabbecb6e619..0000000000000000000000000000000000000000 --- a/spaces/Yiqin/ChatVID/model/vision/grit_src/third_party/CenterNet2/detectron2/evaluation/pascal_voc_evaluation.py +++ /dev/null @@ -1,300 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. - -import logging -import numpy as np -import os -import tempfile -import xml.etree.ElementTree as ET -from collections import OrderedDict, defaultdict -from functools import lru_cache -import torch - -from detectron2.data import MetadataCatalog -from detectron2.utils import comm -from detectron2.utils.file_io import PathManager - -from .evaluator import DatasetEvaluator - - -class PascalVOCDetectionEvaluator(DatasetEvaluator): - """ - Evaluate Pascal VOC style AP for Pascal VOC dataset. - It contains a synchronization, therefore has to be called from all ranks. - - Note that the concept of AP can be implemented in different ways and may not - produce identical results. This class mimics the implementation of the official - Pascal VOC Matlab API, and should produce similar but not identical results to the - official API. - """ - - def __init__(self, dataset_name): - """ - Args: - dataset_name (str): name of the dataset, e.g., "voc_2007_test" - """ - self._dataset_name = dataset_name - meta = MetadataCatalog.get(dataset_name) - - # Too many tiny files, download all to local for speed. - annotation_dir_local = PathManager.get_local_path( - os.path.join(meta.dirname, "Annotations/") - ) - self._anno_file_template = os.path.join(annotation_dir_local, "{}.xml") - self._image_set_path = os.path.join(meta.dirname, "ImageSets", "Main", meta.split + ".txt") - self._class_names = meta.thing_classes - assert meta.year in [2007, 2012], meta.year - self._is_2007 = meta.year == 2007 - self._cpu_device = torch.device("cpu") - self._logger = logging.getLogger(__name__) - - def reset(self): - self._predictions = defaultdict(list) # class name -> list of prediction strings - - def process(self, inputs, outputs): - for input, output in zip(inputs, outputs): - image_id = input["image_id"] - instances = output["instances"].to(self._cpu_device) - boxes = instances.pred_boxes.tensor.numpy() - scores = instances.scores.tolist() - classes = instances.pred_classes.tolist() - for box, score, cls in zip(boxes, scores, classes): - xmin, ymin, xmax, ymax = box - # The inverse of data loading logic in `datasets/pascal_voc.py` - xmin += 1 - ymin += 1 - self._predictions[cls].append( - f"{image_id} {score:.3f} {xmin:.1f} {ymin:.1f} {xmax:.1f} {ymax:.1f}" - ) - - def evaluate(self): - """ - Returns: - dict: has a key "segm", whose value is a dict of "AP", "AP50", and "AP75". - """ - all_predictions = comm.gather(self._predictions, dst=0) - if not comm.is_main_process(): - return - predictions = defaultdict(list) - for predictions_per_rank in all_predictions: - for clsid, lines in predictions_per_rank.items(): - predictions[clsid].extend(lines) - del all_predictions - - self._logger.info( - "Evaluating {} using {} metric. " - "Note that results do not use the official Matlab API.".format( - self._dataset_name, 2007 if self._is_2007 else 2012 - ) - ) - - with tempfile.TemporaryDirectory(prefix="pascal_voc_eval_") as dirname: - res_file_template = os.path.join(dirname, "{}.txt") - - aps = defaultdict(list) # iou -> ap per class - for cls_id, cls_name in enumerate(self._class_names): - lines = predictions.get(cls_id, [""]) - - with open(res_file_template.format(cls_name), "w") as f: - f.write("\n".join(lines)) - - for thresh in range(50, 100, 5): - rec, prec, ap = voc_eval( - res_file_template, - self._anno_file_template, - self._image_set_path, - cls_name, - ovthresh=thresh / 100.0, - use_07_metric=self._is_2007, - ) - aps[thresh].append(ap * 100) - - ret = OrderedDict() - mAP = {iou: np.mean(x) for iou, x in aps.items()} - ret["bbox"] = {"AP": np.mean(list(mAP.values())), "AP50": mAP[50], "AP75": mAP[75]} - return ret - - -############################################################################## -# -# Below code is modified from -# https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/datasets/voc_eval.py -# -------------------------------------------------------- -# Fast/er R-CNN -# Licensed under The MIT License [see LICENSE for details] -# Written by Bharath Hariharan -# -------------------------------------------------------- - -"""Python implementation of the PASCAL VOC devkit's AP evaluation code.""" - - -@lru_cache(maxsize=None) -def parse_rec(filename): - """Parse a PASCAL VOC xml file.""" - with PathManager.open(filename) as f: - tree = ET.parse(f) - objects = [] - for obj in tree.findall("object"): - obj_struct = {} - obj_struct["name"] = obj.find("name").text - obj_struct["pose"] = obj.find("pose").text - obj_struct["truncated"] = int(obj.find("truncated").text) - obj_struct["difficult"] = int(obj.find("difficult").text) - bbox = obj.find("bndbox") - obj_struct["bbox"] = [ - int(bbox.find("xmin").text), - int(bbox.find("ymin").text), - int(bbox.find("xmax").text), - int(bbox.find("ymax").text), - ] - objects.append(obj_struct) - - return objects - - -def voc_ap(rec, prec, use_07_metric=False): - """Compute VOC AP given precision and recall. If use_07_metric is true, uses - the VOC 07 11-point method (default:False). - """ - if use_07_metric: - # 11 point metric - ap = 0.0 - for t in np.arange(0.0, 1.1, 0.1): - if np.sum(rec >= t) == 0: - p = 0 - else: - p = np.max(prec[rec >= t]) - ap = ap + p / 11.0 - else: - # correct AP calculation - # first append sentinel values at the end - mrec = np.concatenate(([0.0], rec, [1.0])) - mpre = np.concatenate(([0.0], prec, [0.0])) - - # compute the precision envelope - for i in range(mpre.size - 1, 0, -1): - mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) - - # to calculate area under PR curve, look for points - # where X axis (recall) changes value - i = np.where(mrec[1:] != mrec[:-1])[0] - - # and sum (\Delta recall) * prec - ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) - return ap - - -def voc_eval(detpath, annopath, imagesetfile, classname, ovthresh=0.5, use_07_metric=False): - """rec, prec, ap = voc_eval(detpath, - annopath, - imagesetfile, - classname, - [ovthresh], - [use_07_metric]) - - Top level function that does the PASCAL VOC evaluation. - - detpath: Path to detections - detpath.format(classname) should produce the detection results file. - annopath: Path to annotations - annopath.format(imagename) should be the xml annotations file. - imagesetfile: Text file containing the list of images, one image per line. - classname: Category name (duh) - [ovthresh]: Overlap threshold (default = 0.5) - [use_07_metric]: Whether to use VOC07's 11 point AP computation - (default False) - """ - # assumes detections are in detpath.format(classname) - # assumes annotations are in annopath.format(imagename) - # assumes imagesetfile is a text file with each line an image name - - # first load gt - # read list of images - with PathManager.open(imagesetfile, "r") as f: - lines = f.readlines() - imagenames = [x.strip() for x in lines] - - # load annots - recs = {} - for imagename in imagenames: - recs[imagename] = parse_rec(annopath.format(imagename)) - - # extract gt objects for this class - class_recs = {} - npos = 0 - for imagename in imagenames: - R = [obj for obj in recs[imagename] if obj["name"] == classname] - bbox = np.array([x["bbox"] for x in R]) - difficult = np.array([x["difficult"] for x in R]).astype(np.bool) - # difficult = np.array([False for x in R]).astype(np.bool) # treat all "difficult" as GT - det = [False] * len(R) - npos = npos + sum(~difficult) - class_recs[imagename] = {"bbox": bbox, "difficult": difficult, "det": det} - - # read dets - detfile = detpath.format(classname) - with open(detfile, "r") as f: - lines = f.readlines() - - splitlines = [x.strip().split(" ") for x in lines] - image_ids = [x[0] for x in splitlines] - confidence = np.array([float(x[1]) for x in splitlines]) - BB = np.array([[float(z) for z in x[2:]] for x in splitlines]).reshape(-1, 4) - - # sort by confidence - sorted_ind = np.argsort(-confidence) - BB = BB[sorted_ind, :] - image_ids = [image_ids[x] for x in sorted_ind] - - # go down dets and mark TPs and FPs - nd = len(image_ids) - tp = np.zeros(nd) - fp = np.zeros(nd) - for d in range(nd): - R = class_recs[image_ids[d]] - bb = BB[d, :].astype(float) - ovmax = -np.inf - BBGT = R["bbox"].astype(float) - - if BBGT.size > 0: - # compute overlaps - # intersection - ixmin = np.maximum(BBGT[:, 0], bb[0]) - iymin = np.maximum(BBGT[:, 1], bb[1]) - ixmax = np.minimum(BBGT[:, 2], bb[2]) - iymax = np.minimum(BBGT[:, 3], bb[3]) - iw = np.maximum(ixmax - ixmin + 1.0, 0.0) - ih = np.maximum(iymax - iymin + 1.0, 0.0) - inters = iw * ih - - # union - uni = ( - (bb[2] - bb[0] + 1.0) * (bb[3] - bb[1] + 1.0) - + (BBGT[:, 2] - BBGT[:, 0] + 1.0) * (BBGT[:, 3] - BBGT[:, 1] + 1.0) - - inters - ) - - overlaps = inters / uni - ovmax = np.max(overlaps) - jmax = np.argmax(overlaps) - - if ovmax > ovthresh: - if not R["difficult"][jmax]: - if not R["det"][jmax]: - tp[d] = 1.0 - R["det"][jmax] = 1 - else: - fp[d] = 1.0 - else: - fp[d] = 1.0 - - # compute precision recall - fp = np.cumsum(fp) - tp = np.cumsum(tp) - rec = tp / float(npos) - # avoid divide by zero in case the first detection matches a difficult - # ground truth - prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) - ap = voc_ap(rec, prec, use_07_metric) - - return rec, prec, ap diff --git a/spaces/YouLiXiya/Mobile-SAM/segment_anything/segment_anything/utils/amg.py b/spaces/YouLiXiya/Mobile-SAM/segment_anything/segment_anything/utils/amg.py deleted file mode 100644 index 3a137778e45c464c079658ecb87ec53270e789f7..0000000000000000000000000000000000000000 --- a/spaces/YouLiXiya/Mobile-SAM/segment_anything/segment_anything/utils/amg.py +++ /dev/null @@ -1,346 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import numpy as np -import torch - -import math -from copy import deepcopy -from itertools import product -from typing import Any, Dict, Generator, ItemsView, List, Tuple - - -class MaskData: - """ - A structure for storing masks and their related data in batched format. - Implements basic filtering and concatenation. - """ - - def __init__(self, **kwargs) -> None: - for v in kwargs.values(): - assert isinstance( - v, (list, np.ndarray, torch.Tensor) - ), "MaskData only supports list, numpy arrays, and torch tensors." - self._stats = dict(**kwargs) - - def __setitem__(self, key: str, item: Any) -> None: - assert isinstance( - item, (list, np.ndarray, torch.Tensor) - ), "MaskData only supports list, numpy arrays, and torch tensors." - self._stats[key] = item - - def __delitem__(self, key: str) -> None: - del self._stats[key] - - def __getitem__(self, key: str) -> Any: - return self._stats[key] - - def items(self) -> ItemsView[str, Any]: - return self._stats.items() - - def filter(self, keep: torch.Tensor) -> None: - for k, v in self._stats.items(): - if v is None: - self._stats[k] = None - elif isinstance(v, torch.Tensor): - self._stats[k] = v[torch.as_tensor(keep, device=v.device)] - elif isinstance(v, np.ndarray): - self._stats[k] = v[keep.detach().cpu().numpy()] - elif isinstance(v, list) and keep.dtype == torch.bool: - self._stats[k] = [a for i, a in enumerate(v) if keep[i]] - elif isinstance(v, list): - self._stats[k] = [v[i] for i in keep] - else: - raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") - - def cat(self, new_stats: "MaskData") -> None: - for k, v in new_stats.items(): - if k not in self._stats or self._stats[k] is None: - self._stats[k] = deepcopy(v) - elif isinstance(v, torch.Tensor): - self._stats[k] = torch.cat([self._stats[k], v], dim=0) - elif isinstance(v, np.ndarray): - self._stats[k] = np.concatenate([self._stats[k], v], axis=0) - elif isinstance(v, list): - self._stats[k] = self._stats[k] + deepcopy(v) - else: - raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") - - def to_numpy(self) -> None: - for k, v in self._stats.items(): - if isinstance(v, torch.Tensor): - self._stats[k] = v.detach().cpu().numpy() - - -def is_box_near_crop_edge( - boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 -) -> torch.Tensor: - """Filter masks at the edge of a crop, but not at the edge of the original image.""" - crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) - orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) - boxes = uncrop_boxes_xyxy(boxes, crop_box).float() - near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) - near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) - near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) - return torch.any(near_crop_edge, dim=1) - - -def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: - box_xywh = deepcopy(box_xyxy) - box_xywh[2] = box_xywh[2] - box_xywh[0] - box_xywh[3] = box_xywh[3] - box_xywh[1] - return box_xywh - - -def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: - assert len(args) > 0 and all( - len(a) == len(args[0]) for a in args - ), "Batched iteration must have inputs of all the same size." - n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) - for b in range(n_batches): - yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] - - -def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: - """ - Encodes masks to an uncompressed RLE, in the format expected by - pycoco tools. - """ - # Put in fortran order and flatten h,w - b, h, w = tensor.shape - tensor = tensor.permute(0, 2, 1).flatten(1) - - # Compute change indices - diff = tensor[:, 1:] ^ tensor[:, :-1] - change_indices = diff.nonzero() - - # Encode run length - out = [] - for i in range(b): - cur_idxs = change_indices[change_indices[:, 0] == i, 1] - cur_idxs = torch.cat( - [ - torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), - cur_idxs + 1, - torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), - ] - ) - btw_idxs = cur_idxs[1:] - cur_idxs[:-1] - counts = [] if tensor[i, 0] == 0 else [0] - counts.extend(btw_idxs.detach().cpu().tolist()) - out.append({"size": [h, w], "counts": counts}) - return out - - -def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: - """Compute a binary mask from an uncompressed RLE.""" - h, w = rle["size"] - mask = np.empty(h * w, dtype=bool) - idx = 0 - parity = False - for count in rle["counts"]: - mask[idx : idx + count] = parity - idx += count - parity ^= True - mask = mask.reshape(w, h) - return mask.transpose() # Put in C order - - -def area_from_rle(rle: Dict[str, Any]) -> int: - return sum(rle["counts"][1::2]) - - -def calculate_stability_score( - masks: torch.Tensor, mask_threshold: float, threshold_offset: float -) -> torch.Tensor: - """ - Computes the stability score for a batch of masks. The stability - score is the IoU between the binary masks obtained by thresholding - the predicted mask logits at high and low values. - """ - # One mask is always contained inside the other. - # Save memory by preventing unnecesary cast to torch.int64 - intersections = ( - (masks > (mask_threshold + threshold_offset)) - .sum(-1, dtype=torch.int16) - .sum(-1, dtype=torch.int32) - ) - unions = ( - (masks > (mask_threshold - threshold_offset)) - .sum(-1, dtype=torch.int16) - .sum(-1, dtype=torch.int32) - ) - return intersections / unions - - -def build_point_grid(n_per_side: int) -> np.ndarray: - """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" - offset = 1 / (2 * n_per_side) - points_one_side = np.linspace(offset, 1 - offset, n_per_side) - points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) - points_y = np.tile(points_one_side[:, None], (1, n_per_side)) - points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) - return points - - -def build_all_layer_point_grids( - n_per_side: int, n_layers: int, scale_per_layer: int -) -> List[np.ndarray]: - """Generates point grids for all crop layers.""" - points_by_layer = [] - for i in range(n_layers + 1): - n_points = int(n_per_side / (scale_per_layer**i)) - points_by_layer.append(build_point_grid(n_points)) - return points_by_layer - - -def generate_crop_boxes( - im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float -) -> Tuple[List[List[int]], List[int]]: - """ - Generates a list of crop boxes of different sizes. Each layer - has (2**i)**2 boxes for the ith layer. - """ - crop_boxes, layer_idxs = [], [] - im_h, im_w = im_size - short_side = min(im_h, im_w) - - # Original image - crop_boxes.append([0, 0, im_w, im_h]) - layer_idxs.append(0) - - def crop_len(orig_len, n_crops, overlap): - return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) - - for i_layer in range(n_layers): - n_crops_per_side = 2 ** (i_layer + 1) - overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) - - crop_w = crop_len(im_w, n_crops_per_side, overlap) - crop_h = crop_len(im_h, n_crops_per_side, overlap) - - crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] - crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] - - # Crops in XYWH format - for x0, y0 in product(crop_box_x0, crop_box_y0): - box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] - crop_boxes.append(box) - layer_idxs.append(i_layer + 1) - - return crop_boxes, layer_idxs - - -def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: - x0, y0, _, _ = crop_box - offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) - # Check if boxes has a channel dimension - if len(boxes.shape) == 3: - offset = offset.unsqueeze(1) - return boxes + offset - - -def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: - x0, y0, _, _ = crop_box - offset = torch.tensor([[x0, y0]], device=points.device) - # Check if points has a channel dimension - if len(points.shape) == 3: - offset = offset.unsqueeze(1) - return points + offset - - -def uncrop_masks( - masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int -) -> torch.Tensor: - x0, y0, x1, y1 = crop_box - if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: - return masks - # Coordinate transform masks - pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) - pad = (x0, pad_x - x0, y0, pad_y - y0) - return torch.nn.functional.pad(masks, pad, value=0) - - -def remove_small_regions( - mask: np.ndarray, area_thresh: float, mode: str -) -> Tuple[np.ndarray, bool]: - """ - Removes small disconnected regions and holes in a mask. Returns the - mask and an indicator of if the mask has been modified. - """ - import cv2 # type: ignore - - assert mode in ["holes", "islands"] - correct_holes = mode == "holes" - working_mask = (correct_holes ^ mask).astype(np.uint8) - n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) - sizes = stats[:, -1][1:] # Row 0 is background label - small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] - if len(small_regions) == 0: - return mask, False - fill_labels = [0] + small_regions - if not correct_holes: - fill_labels = [i for i in range(n_labels) if i not in fill_labels] - # If every region is below threshold, keep largest - if len(fill_labels) == 0: - fill_labels = [int(np.argmax(sizes)) + 1] - mask = np.isin(regions, fill_labels) - return mask, True - - -def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: - from pycocotools import mask as mask_utils # type: ignore - - h, w = uncompressed_rle["size"] - rle = mask_utils.frPyObjects(uncompressed_rle, h, w) - rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json - return rle - - -def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: - """ - Calculates boxes in XYXY format around masks. Return [0,0,0,0] for - an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. - """ - # torch.max below raises an error on empty inputs, just skip in this case - if torch.numel(masks) == 0: - return torch.zeros(*masks.shape[:-2], 4, device=masks.device) - - # Normalize shape to CxHxW - shape = masks.shape - h, w = shape[-2:] - if len(shape) > 2: - masks = masks.flatten(0, -3) - else: - masks = masks.unsqueeze(0) - - # Get top and bottom edges - in_height, _ = torch.max(masks, dim=-1) - in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] - bottom_edges, _ = torch.max(in_height_coords, dim=-1) - in_height_coords = in_height_coords + h * (~in_height) - top_edges, _ = torch.min(in_height_coords, dim=-1) - - # Get left and right edges - in_width, _ = torch.max(masks, dim=-2) - in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] - right_edges, _ = torch.max(in_width_coords, dim=-1) - in_width_coords = in_width_coords + w * (~in_width) - left_edges, _ = torch.min(in_width_coords, dim=-1) - - # If the mask is empty the right edge will be to the left of the left edge. - # Replace these boxes with [0, 0, 0, 0] - empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) - out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) - out = out * (~empty_filter).unsqueeze(-1) - - # Return to original shape - if len(shape) > 2: - out = out.reshape(*shape[:-2], 4) - else: - out = out[0] - - return out diff --git a/spaces/YuAnthony/Audio-Caption/data_augmentation/SpecAugment.py b/spaces/YuAnthony/Audio-Caption/data_augmentation/SpecAugment.py deleted file mode 100644 index eeea7d16d2842ba5a40bd5a108e7f3c62aba2b73..0000000000000000000000000000000000000000 --- a/spaces/YuAnthony/Audio-Caption/data_augmentation/SpecAugment.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Heavily copied from https://github.com/zcaceres/spec_augment -""" -import random -import torch - -from .nb_SparseImageWarp import sparse_image_warp - - -def time_warp(spec, W=5): - num_rows = spec.shape[1] - spec_len = spec.shape[2] - device = spec.device - - y = num_rows // 2 - horizontal_line_at_ctr = spec[0][y] - assert len(horizontal_line_at_ctr) == spec_len - - point_to_warp = horizontal_line_at_ctr[random.randrange(W, spec_len - W)] - assert isinstance(point_to_warp, torch.Tensor) - - # Uniform distribution from (0,W) with chance to be up to W negative - dist_to_warp = random.randrange(-W, W) - src_pts, dest_pts = (torch.tensor([[[y, point_to_warp]]], device=device), - torch.tensor([[[y, point_to_warp + dist_to_warp]]], device=device)) - warped_spectro, dense_flows = sparse_image_warp(spec, src_pts, dest_pts) - return warped_spectro.squeeze(3) - - -def freq_mask(spec, F=30, num_masks=1, replace_with_zero=False): - cloned = spec.clone() - num_mel_channels = cloned.shape[1] - - for i in range(0, num_masks): - f = random.randrange(0, F) - f_zero = random.randrange(0, num_mel_channels - f) - - # avoids randrange error if values are equal and range is empty - if (f_zero == f_zero + f): return cloned - - mask_end = random.randrange(f_zero, f_zero + f) - if (replace_with_zero): - cloned[0][f_zero:mask_end] = 0 - else: - cloned[0][f_zero:mask_end] = cloned.mean() - - return cloned - - -def time_mask(spec, T=40, num_masks=1, replace_with_zero=False): - cloned = spec.clone() - len_spectro = cloned.shape[2] - - for i in range(0, num_masks): - t = random.randrange(0, T) - t_zero = random.randrange(0, len_spectro - t) - - # avoids randrange error if values are equal and range is empty - if (t_zero == t_zero + t): return cloned - - mask_end = random.randrange(t_zero, t_zero + t) - if (replace_with_zero): - cloned[0][:, t_zero:mask_end] = 0 - else: - cloned[0][:, t_zero:mask_end] = cloned.mean() - return cloned - - -def spec_augment(mel, num_time_mask=2, num_freq_mask=2, apply_time_warp=False, F=15, W=40, T=30, p=0.2): - # mel:(batch_size,T,dim) - mel = mel.transpose(1, 2) - for i in range(len(mel)): - mel_single = mel[i].unsqueeze(0) # single example in the batch - if random.random() < p: - if num_time_mask and num_time_mask > 0: - mel_single = time_mask(mel_single, T=T, num_masks=num_time_mask) - if num_freq_mask and num_freq_mask > 0: - mel_single = freq_mask(mel_single, F=F, num_masks=num_freq_mask) - if apply_time_warp: - mel_single = time_warp(mel_single, W=W) - mel[i] = mel_single - mel = mel.transpose(1, 2) - return mel diff --git a/spaces/Zulqrnain/FAST_NU_PAST_PAPERS/README.md b/spaces/Zulqrnain/FAST_NU_PAST_PAPERS/README.md deleted file mode 100644 index c23655bca364a7c509e570e4d73927d9416eeb8d..0000000000000000000000000000000000000000 --- a/spaces/Zulqrnain/FAST_NU_PAST_PAPERS/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: FAST NU PAST PAPERS -emoji: 🏃 -colorFrom: yellow -colorTo: yellow -sdk: gradio -sdk_version: 3.28.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/aaditkapoorbionlp/clinical_trial_match/app.py b/spaces/aaditkapoorbionlp/clinical_trial_match/app.py deleted file mode 100644 index aa8ecbf0a3bb4479d8ba58587b132614e619d646..0000000000000000000000000000000000000000 --- a/spaces/aaditkapoorbionlp/clinical_trial_match/app.py +++ /dev/null @@ -1,64 +0,0 @@ -import streamlit as st -from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModel -import os -import pandas as pd -import numpy as np -from transformers import pipeline -from sklearn.metrics.pairwise import cosine_similarity, manhattan_distances, euclidean_distances - - - -@st.cache(allow_output_mutation=True) -def load_model(): - tokenizer = AutoTokenizer.from_pretrained("stanford-crfm/pubmedgpt") - model = AutoModel.from_pretrained("stanford-crfm/pubmedgpt") - return tokenizer, model - -tokenizer, model = load_model() -pipe = pipeline('feature-extraction', model=model, tokenizer=tokenizer) -def get_embedding(desc): - return np.squeeze(pipe(desc)).mean(axis=0) - - -st.set_page_config( - page_title="Clinical Trials Best Match [Eye Diseases]", - page_icon="🧑‍💻", - layout="wide", -) - -# Constants -embs = [] - -# Heading -st.title('Clinical Trials Search') - - -# Gene File, 128 dim embeddings -data = np.load("data.npy") - - -@st.cache(allow_output_mutation=True) -def get_sim(emb_desc, data): - ids = [] - scores = [] - for i in data: - score = cosine_similarity(emb_desc, i['data']) - ids.append(i['ids']) - scores.append(score) - df = pd.DataFrame(data={"url": ids, "scores": scores}).sort_values(by='scores') - - return df - -st.subheader("🖮 Enter your clinical trial study description") -text = st.text_area('Example') - -with st.spinner(): - emb = get_embedding(text) - - -st.subheader("💻 Hit Search") - -if st.button("Compute"): - with st.spinner('Searching...'): - df = get_sim(emb, data=data) - st.dataframe(df) \ No newline at end of file diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/core/bbox/match_costs/builder.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/core/bbox/match_costs/builder.py deleted file mode 100644 index 6894017d42eb16ee4a8ae3ed660a71cda3ad9940..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/core/bbox/match_costs/builder.py +++ /dev/null @@ -1,8 +0,0 @@ -from mmcv.utils import Registry, build_from_cfg - -MATCH_COST = Registry('Match Cost') - - -def build_match_cost(cfg, default_args=None): - """Builder of IoU calculator.""" - return build_from_cfg(cfg, MATCH_COST, default_args) diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/anchor_free_head.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/anchor_free_head.py deleted file mode 100644 index 1814a0cc4f577f470f74f025440073a0aaa1ebd0..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/anchor_free_head.py +++ /dev/null @@ -1,340 +0,0 @@ -from abc import abstractmethod - -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 multi_apply -from ..builder import HEADS, build_loss -from .base_dense_head import BaseDenseHead -from .dense_test_mixins import BBoxTestMixin - - -@HEADS.register_module() -class AnchorFreeHead(BaseDenseHead, BBoxTestMixin): - """Anchor-free head (FCOS, Fovea, RepPoints, etc.). - - Args: - num_classes (int): Number of categories excluding the background - category. - in_channels (int): Number of channels in the input feature map. - feat_channels (int): Number of hidden channels. Used in child classes. - stacked_convs (int): Number of stacking convs of the head. - strides (tuple): Downsample factor of each feature map. - dcn_on_last_conv (bool): If true, use dcn in the last layer of - towers. Default: False. - conv_bias (bool | str): If specified as `auto`, it will be decided by - the norm_cfg. Bias of conv will be set as True if `norm_cfg` is - None, otherwise False. Default: "auto". - loss_cls (dict): Config of classification loss. - loss_bbox (dict): Config of localization loss. - conv_cfg (dict): Config dict for convolution layer. Default: None. - norm_cfg (dict): Config dict for normalization layer. Default: None. - train_cfg (dict): Training config of anchor head. - test_cfg (dict): Testing config of anchor head. - """ # noqa: W605 - - _version = 1 - - def __init__(self, - num_classes, - in_channels, - feat_channels=256, - stacked_convs=4, - strides=(4, 8, 16, 32, 64), - dcn_on_last_conv=False, - conv_bias='auto', - loss_cls=dict( - type='FocalLoss', - use_sigmoid=True, - gamma=2.0, - alpha=0.25, - loss_weight=1.0), - loss_bbox=dict(type='IoULoss', loss_weight=1.0), - conv_cfg=None, - norm_cfg=None, - train_cfg=None, - test_cfg=None): - super(AnchorFreeHead, self).__init__() - self.num_classes = num_classes - self.cls_out_channels = num_classes - self.in_channels = in_channels - self.feat_channels = feat_channels - self.stacked_convs = stacked_convs - self.strides = strides - self.dcn_on_last_conv = dcn_on_last_conv - assert conv_bias == 'auto' or isinstance(conv_bias, bool) - self.conv_bias = conv_bias - self.loss_cls = build_loss(loss_cls) - self.loss_bbox = build_loss(loss_bbox) - self.train_cfg = train_cfg - self.test_cfg = test_cfg - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.fp16_enabled = False - - self._init_layers() - - def _init_layers(self): - """Initialize layers of the head.""" - self._init_cls_convs() - self._init_reg_convs() - self._init_predictor() - - def _init_cls_convs(self): - """Initialize classification conv layers of the head.""" - self.cls_convs = nn.ModuleList() - for i in range(self.stacked_convs): - chn = self.in_channels if i == 0 else self.feat_channels - if self.dcn_on_last_conv and i == self.stacked_convs - 1: - conv_cfg = dict(type='DCNv2') - else: - conv_cfg = self.conv_cfg - self.cls_convs.append( - ConvModule( - chn, - self.feat_channels, - 3, - stride=1, - padding=1, - conv_cfg=conv_cfg, - norm_cfg=self.norm_cfg, - bias=self.conv_bias)) - - def _init_reg_convs(self): - """Initialize bbox regression conv layers of the head.""" - self.reg_convs = nn.ModuleList() - for i in range(self.stacked_convs): - chn = self.in_channels if i == 0 else self.feat_channels - if self.dcn_on_last_conv and i == self.stacked_convs - 1: - conv_cfg = dict(type='DCNv2') - else: - conv_cfg = self.conv_cfg - self.reg_convs.append( - ConvModule( - chn, - self.feat_channels, - 3, - stride=1, - padding=1, - conv_cfg=conv_cfg, - norm_cfg=self.norm_cfg, - bias=self.conv_bias)) - - def _init_predictor(self): - """Initialize predictor layers of the head.""" - self.conv_cls = nn.Conv2d( - self.feat_channels, self.cls_out_channels, 3, padding=1) - self.conv_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) - - def init_weights(self): - """Initialize weights of the head.""" - for m in self.cls_convs: - if isinstance(m.conv, nn.Conv2d): - normal_init(m.conv, std=0.01) - for m in self.reg_convs: - if isinstance(m.conv, nn.Conv2d): - normal_init(m.conv, std=0.01) - bias_cls = bias_init_with_prob(0.01) - normal_init(self.conv_cls, std=0.01, bias=bias_cls) - normal_init(self.conv_reg, std=0.01) - - def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, - missing_keys, unexpected_keys, error_msgs): - """Hack some keys of the model state dict so that can load checkpoints - of previous version.""" - version = local_metadata.get('version', None) - if version is None: - # the key is different in early versions - # for example, 'fcos_cls' become 'conv_cls' now - bbox_head_keys = [ - k for k in state_dict.keys() if k.startswith(prefix) - ] - ori_predictor_keys = [] - new_predictor_keys = [] - # e.g. 'fcos_cls' or 'fcos_reg' - for key in bbox_head_keys: - ori_predictor_keys.append(key) - key = key.split('.') - conv_name = None - if key[1].endswith('cls'): - conv_name = 'conv_cls' - elif key[1].endswith('reg'): - conv_name = 'conv_reg' - elif key[1].endswith('centerness'): - conv_name = 'conv_centerness' - else: - assert NotImplementedError - if conv_name is not None: - key[1] = conv_name - new_predictor_keys.append('.'.join(key)) - else: - ori_predictor_keys.pop(-1) - for i in range(len(new_predictor_keys)): - state_dict[new_predictor_keys[i]] = state_dict.pop( - ori_predictor_keys[i]) - super()._load_from_state_dict(state_dict, prefix, local_metadata, - strict, missing_keys, unexpected_keys, - error_msgs) - - def forward(self, feats): - """Forward features from the upstream network. - - Args: - feats (tuple[Tensor]): Features from the upstream network, each is - a 4D-tensor. - - Returns: - tuple: Usually contain classification scores and bbox predictions. - cls_scores (list[Tensor]): Box scores for each scale level, - each is a 4D-tensor, the channel number is - num_points * num_classes. - bbox_preds (list[Tensor]): Box energies / deltas for each scale - level, each is a 4D-tensor, the channel number is - num_points * 4. - """ - return multi_apply(self.forward_single, feats)[:2] - - def forward_single(self, x): - """Forward features of a single scale level. - - Args: - x (Tensor): FPN feature maps of the specified stride. - - Returns: - tuple: Scores for each class, bbox predictions, features - after classification and regression conv layers, some - models needs these features like FCOS. - """ - cls_feat = x - reg_feat = x - - for cls_layer in self.cls_convs: - cls_feat = cls_layer(cls_feat) - cls_score = self.conv_cls(cls_feat) - - for reg_layer in self.reg_convs: - reg_feat = reg_layer(reg_feat) - bbox_pred = self.conv_reg(reg_feat) - return cls_score, bbox_pred, cls_feat, reg_feat - - @abstractmethod - @force_fp32(apply_to=('cls_scores', 'bbox_preds')) - def loss(self, - cls_scores, - bbox_preds, - gt_bboxes, - gt_labels, - img_metas, - gt_bboxes_ignore=None): - """Compute loss of the head. - - Args: - cls_scores (list[Tensor]): Box scores for each scale level, - each is a 4D-tensor, the channel number is - num_points * num_classes. - bbox_preds (list[Tensor]): Box energies / deltas for each scale - level, each is a 4D-tensor, the channel number is - num_points * 4. - gt_bboxes (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[Tensor]): class indices corresponding to each box - img_metas (list[dict]): Meta information of each image, e.g., - image size, scaling factor, etc. - gt_bboxes_ignore (None | list[Tensor]): specify which bounding - boxes can be ignored when computing the loss. - """ - - raise NotImplementedError - - @abstractmethod - @force_fp32(apply_to=('cls_scores', 'bbox_preds')) - def get_bboxes(self, - cls_scores, - bbox_preds, - img_metas, - cfg=None, - rescale=None): - """Transform network output for a batch into bbox predictions. - - Args: - cls_scores (list[Tensor]): Box scores for each scale level - Has shape (N, num_points * num_classes, H, W) - bbox_preds (list[Tensor]): Box energies / deltas for each scale - level with shape (N, num_points * 4, H, W) - img_metas (list[dict]): Meta information of each image, e.g., - image size, scaling factor, etc. - cfg (mmcv.Config): Test / postprocessing configuration, - if None, test_cfg would be used - rescale (bool): If True, return boxes in original image space - """ - - raise NotImplementedError - - @abstractmethod - def get_targets(self, points, gt_bboxes_list, gt_labels_list): - """Compute regression, classification and centerness targets for points - in multiple images. - - Args: - points (list[Tensor]): Points of each fpn level, each has shape - (num_points, 2). - gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image, - each has shape (num_gt, 4). - gt_labels_list (list[Tensor]): Ground truth labels of each box, - each has shape (num_gt,). - """ - raise NotImplementedError - - def _get_points_single(self, - featmap_size, - stride, - dtype, - device, - flatten=False): - """Get points of a single scale level.""" - h, w = featmap_size - x_range = torch.arange(w, dtype=dtype, device=device) - y_range = torch.arange(h, dtype=dtype, device=device) - y, x = torch.meshgrid(y_range, x_range) - if flatten: - y = y.flatten() - x = x.flatten() - return y, x - - def get_points(self, featmap_sizes, dtype, device, flatten=False): - """Get points according to feature map sizes. - - Args: - featmap_sizes (list[tuple]): Multi-level feature map sizes. - dtype (torch.dtype): Type of points. - device (torch.device): Device of points. - - Returns: - tuple: points of each image. - """ - mlvl_points = [] - for i in range(len(featmap_sizes)): - mlvl_points.append( - self._get_points_single(featmap_sizes[i], self.strides[i], - dtype, device, flatten)) - return mlvl_points - - def aug_test(self, feats, img_metas, rescale=False): - """Test function with test time augmentation. - - Args: - feats (list[Tensor]): the outer list indicates test-time - augmentations and inner Tensor should have a shape NxCxHxW, - which contains features for all images in the batch. - img_metas (list[list[dict]]): the outer list indicates test-time - augs (multiscale, flip, etc.) and the inner list indicates - images in a batch. each dict has image information. - rescale (bool, optional): Whether to rescale the results. - Defaults to False. - - Returns: - list[ndarray]: bbox results of each class - """ - return self.aug_test_bboxes(feats, img_metas, rescale=rescale) diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/detectors/fovea.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/detectors/fovea.py deleted file mode 100644 index 22a578efffbd108db644d907bae95c7c8df31f2e..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/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/akhaliq/yolov7/utils/activations.py b/spaces/akhaliq/yolov7/utils/activations.py deleted file mode 100644 index aa3ddf071d28daa3061b6d796cb60cd7a88f557c..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/yolov7/utils/activations.py +++ /dev/null @@ -1,72 +0,0 @@ -# Activation functions - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -# SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- -class SiLU(nn.Module): # export-friendly version of nn.SiLU() - @staticmethod - def forward(x): - return x * torch.sigmoid(x) - - -class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() - @staticmethod - def forward(x): - # return x * F.hardsigmoid(x) # for torchscript and CoreML - return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX - - -class MemoryEfficientSwish(nn.Module): - class F(torch.autograd.Function): - @staticmethod - def forward(ctx, x): - ctx.save_for_backward(x) - return x * torch.sigmoid(x) - - @staticmethod - def backward(ctx, grad_output): - x = ctx.saved_tensors[0] - sx = torch.sigmoid(x) - return grad_output * (sx * (1 + x * (1 - sx))) - - def forward(self, x): - return self.F.apply(x) - - -# Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- -class Mish(nn.Module): - @staticmethod - def forward(x): - return x * F.softplus(x).tanh() - - -class MemoryEfficientMish(nn.Module): - class F(torch.autograd.Function): - @staticmethod - def forward(ctx, x): - ctx.save_for_backward(x) - return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) - - @staticmethod - def backward(ctx, grad_output): - x = ctx.saved_tensors[0] - sx = torch.sigmoid(x) - fx = F.softplus(x).tanh() - return grad_output * (fx + x * sx * (1 - fx * fx)) - - def forward(self, x): - return self.F.apply(x) - - -# FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- -class FReLU(nn.Module): - def __init__(self, c1, k=3): # ch_in, kernel - super().__init__() - self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) - self.bn = nn.BatchNorm2d(c1) - - def forward(self, x): - return torch.max(x, self.bn(self.conv(x))) diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/distlib/locators.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/distlib/locators.py deleted file mode 100644 index c78bc9e23a09ca158edb178022a22d344e524fac..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/distlib/locators.py +++ /dev/null @@ -1,1300 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2012-2015 Vinay Sajip. -# Licensed to the Python Software Foundation under a contributor agreement. -# See LICENSE.txt and CONTRIBUTORS.txt. -# - -import gzip -from io import BytesIO -import json -import logging -import os -import posixpath -import re -try: - import threading -except ImportError: # pragma: no cover - import dummy_threading as threading -import zlib - -from . import DistlibException -from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url, - queue, quote, unescape, build_opener, - HTTPRedirectHandler as BaseRedirectHandler, text_type, - Request, HTTPError, URLError) -from .database import Distribution, DistributionPath, make_dist -from .metadata import Metadata, MetadataInvalidError -from .util import (cached_property, ensure_slash, split_filename, get_project_data, - parse_requirement, parse_name_and_version, ServerProxy, - normalize_name) -from .version import get_scheme, UnsupportedVersionError -from .wheel import Wheel, is_compatible - -logger = logging.getLogger(__name__) - -HASHER_HASH = re.compile(r'^(\w+)=([a-f0-9]+)') -CHARSET = re.compile(r';\s*charset\s*=\s*(.*)\s*$', re.I) -HTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml') -DEFAULT_INDEX = 'https://pypi.org/pypi' - -def get_all_distribution_names(url=None): - """ - Return all distribution names known by an index. - :param url: The URL of the index. - :return: A list of all known distribution names. - """ - if url is None: - url = DEFAULT_INDEX - client = ServerProxy(url, timeout=3.0) - try: - return client.list_packages() - finally: - client('close')() - -class RedirectHandler(BaseRedirectHandler): - """ - A class to work around a bug in some Python 3.2.x releases. - """ - # There's a bug in the base version for some 3.2.x - # (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header - # returns e.g. /abc, it bails because it says the scheme '' - # is bogus, when actually it should use the request's - # URL for the scheme. See Python issue #13696. - def http_error_302(self, req, fp, code, msg, headers): - # Some servers (incorrectly) return multiple Location headers - # (so probably same goes for URI). Use first header. - newurl = None - for key in ('location', 'uri'): - if key in headers: - newurl = headers[key] - break - if newurl is None: # pragma: no cover - return - urlparts = urlparse(newurl) - if urlparts.scheme == '': - newurl = urljoin(req.get_full_url(), newurl) - if hasattr(headers, 'replace_header'): - headers.replace_header(key, newurl) - else: - headers[key] = newurl - return BaseRedirectHandler.http_error_302(self, req, fp, code, msg, - headers) - - http_error_301 = http_error_303 = http_error_307 = http_error_302 - -class Locator(object): - """ - A base class for locators - things that locate distributions. - """ - source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz') - binary_extensions = ('.egg', '.exe', '.whl') - excluded_extensions = ('.pdf',) - - # A list of tags indicating which wheels you want to match. The default - # value of None matches against the tags compatible with the running - # Python. If you want to match other values, set wheel_tags on a locator - # instance to a list of tuples (pyver, abi, arch) which you want to match. - wheel_tags = None - - downloadable_extensions = source_extensions + ('.whl',) - - def __init__(self, scheme='default'): - """ - Initialise an instance. - :param scheme: Because locators look for most recent versions, they - need to know the version scheme to use. This specifies - the current PEP-recommended scheme - use ``'legacy'`` - if you need to support existing distributions on PyPI. - """ - self._cache = {} - self.scheme = scheme - # Because of bugs in some of the handlers on some of the platforms, - # we use our own opener rather than just using urlopen. - self.opener = build_opener(RedirectHandler()) - # If get_project() is called from locate(), the matcher instance - # is set from the requirement passed to locate(). See issue #18 for - # why this can be useful to know. - self.matcher = None - self.errors = queue.Queue() - - def get_errors(self): - """ - Return any errors which have occurred. - """ - result = [] - while not self.errors.empty(): # pragma: no cover - try: - e = self.errors.get(False) - result.append(e) - except self.errors.Empty: - continue - self.errors.task_done() - return result - - def clear_errors(self): - """ - Clear any errors which may have been logged. - """ - # Just get the errors and throw them away - self.get_errors() - - def clear_cache(self): - self._cache.clear() - - def _get_scheme(self): - return self._scheme - - def _set_scheme(self, value): - self._scheme = value - - scheme = property(_get_scheme, _set_scheme) - - def _get_project(self, name): - """ - For a given project, get a dictionary mapping available versions to Distribution - instances. - - This should be implemented in subclasses. - - If called from a locate() request, self.matcher will be set to a - matcher for the requirement to satisfy, otherwise it will be None. - """ - raise NotImplementedError('Please implement in the subclass') - - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - raise NotImplementedError('Please implement in the subclass') - - def get_project(self, name): - """ - For a given project, get a dictionary mapping available versions to Distribution - instances. - - This calls _get_project to do all the work, and just implements a caching layer on top. - """ - if self._cache is None: # pragma: no cover - result = self._get_project(name) - elif name in self._cache: - result = self._cache[name] - else: - self.clear_errors() - result = self._get_project(name) - self._cache[name] = result - return result - - def score_url(self, url): - """ - Give an url a score which can be used to choose preferred URLs - for a given project release. - """ - t = urlparse(url) - basename = posixpath.basename(t.path) - compatible = True - is_wheel = basename.endswith('.whl') - is_downloadable = basename.endswith(self.downloadable_extensions) - if is_wheel: - compatible = is_compatible(Wheel(basename), self.wheel_tags) - return (t.scheme == 'https', 'pypi.org' in t.netloc, - is_downloadable, is_wheel, compatible, basename) - - def prefer_url(self, url1, url2): - """ - Choose one of two URLs where both are candidates for distribution - archives for the same version of a distribution (for example, - .tar.gz vs. zip). - - The current implementation favours https:// URLs over http://, archives - from PyPI over those from other locations, wheel compatibility (if a - wheel) and then the archive name. - """ - result = url2 - if url1: - s1 = self.score_url(url1) - s2 = self.score_url(url2) - if s1 > s2: - result = url1 - if result != url2: - logger.debug('Not replacing %r with %r', url1, url2) - else: - logger.debug('Replacing %r with %r', url1, url2) - return result - - def split_filename(self, filename, project_name): - """ - Attempt to split a filename in project name, version and Python version. - """ - return split_filename(filename, project_name) - - def convert_url_to_download_info(self, url, project_name): - """ - See if a URL is a candidate for a download URL for a project (the URL - has typically been scraped from an HTML page). - - If it is, a dictionary is returned with keys "name", "version", - "filename" and "url"; otherwise, None is returned. - """ - def same_project(name1, name2): - return normalize_name(name1) == normalize_name(name2) - - result = None - scheme, netloc, path, params, query, frag = urlparse(url) - if frag.lower().startswith('egg='): # pragma: no cover - logger.debug('%s: version hint in fragment: %r', - project_name, frag) - m = HASHER_HASH.match(frag) - if m: - algo, digest = m.groups() - else: - algo, digest = None, None - origpath = path - if path and path[-1] == '/': # pragma: no cover - path = path[:-1] - if path.endswith('.whl'): - try: - wheel = Wheel(path) - if not is_compatible(wheel, self.wheel_tags): - logger.debug('Wheel not compatible: %s', path) - else: - if project_name is None: - include = True - else: - include = same_project(wheel.name, project_name) - if include: - result = { - 'name': wheel.name, - 'version': wheel.version, - 'filename': wheel.filename, - 'url': urlunparse((scheme, netloc, origpath, - params, query, '')), - 'python-version': ', '.join( - ['.'.join(list(v[2:])) for v in wheel.pyver]), - } - except Exception as e: # pragma: no cover - logger.warning('invalid path for wheel: %s', path) - elif not path.endswith(self.downloadable_extensions): # pragma: no cover - logger.debug('Not downloadable: %s', path) - else: # downloadable extension - path = filename = posixpath.basename(path) - for ext in self.downloadable_extensions: - if path.endswith(ext): - path = path[:-len(ext)] - t = self.split_filename(path, project_name) - if not t: # pragma: no cover - logger.debug('No match for project/version: %s', path) - else: - name, version, pyver = t - if not project_name or same_project(project_name, name): - result = { - 'name': name, - 'version': version, - 'filename': filename, - 'url': urlunparse((scheme, netloc, origpath, - params, query, '')), - #'packagetype': 'sdist', - } - if pyver: # pragma: no cover - result['python-version'] = pyver - break - if result and algo: - result['%s_digest' % algo] = digest - return result - - def _get_digest(self, info): - """ - Get a digest from a dictionary by looking at a "digests" dictionary - or keys of the form 'algo_digest'. - - Returns a 2-tuple (algo, digest) if found, else None. Currently - looks only for SHA256, then MD5. - """ - result = None - if 'digests' in info: - digests = info['digests'] - for algo in ('sha256', 'md5'): - if algo in digests: - result = (algo, digests[algo]) - break - if not result: - for algo in ('sha256', 'md5'): - key = '%s_digest' % algo - if key in info: - result = (algo, info[key]) - break - return result - - def _update_version_data(self, result, info): - """ - Update a result dictionary (the final result from _get_project) with a - dictionary for a specific version, which typically holds information - gleaned from a filename or URL for an archive for the distribution. - """ - name = info.pop('name') - version = info.pop('version') - if version in result: - dist = result[version] - md = dist.metadata - else: - dist = make_dist(name, version, scheme=self.scheme) - md = dist.metadata - dist.digest = digest = self._get_digest(info) - url = info['url'] - result['digests'][url] = digest - if md.source_url != info['url']: - md.source_url = self.prefer_url(md.source_url, url) - result['urls'].setdefault(version, set()).add(url) - dist.locator = self - result[version] = dist - - def locate(self, requirement, prereleases=False): - """ - Find the most recent distribution which matches the given - requirement. - - :param requirement: A requirement of the form 'foo (1.0)' or perhaps - 'foo (>= 1.0, < 2.0, != 1.3)' - :param prereleases: If ``True``, allow pre-release versions - to be located. Otherwise, pre-release versions - are not returned. - :return: A :class:`Distribution` instance, or ``None`` if no such - distribution could be located. - """ - result = None - r = parse_requirement(requirement) - if r is None: # pragma: no cover - raise DistlibException('Not a valid requirement: %r' % requirement) - scheme = get_scheme(self.scheme) - self.matcher = matcher = scheme.matcher(r.requirement) - logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__) - versions = self.get_project(r.name) - if len(versions) > 2: # urls and digests keys are present - # sometimes, versions are invalid - slist = [] - vcls = matcher.version_class - for k in versions: - if k in ('urls', 'digests'): - continue - try: - if not matcher.match(k): - pass # logger.debug('%s did not match %r', matcher, k) - else: - if prereleases or not vcls(k).is_prerelease: - slist.append(k) - # else: - # logger.debug('skipping pre-release ' - # 'version %s of %s', k, matcher.name) - except Exception: # pragma: no cover - logger.warning('error matching %s with %r', matcher, k) - pass # slist.append(k) - if len(slist) > 1: - slist = sorted(slist, key=scheme.key) - if slist: - logger.debug('sorted list: %s', slist) - version = slist[-1] - result = versions[version] - if result: - if r.extras: - result.extras = r.extras - result.download_urls = versions.get('urls', {}).get(version, set()) - d = {} - sd = versions.get('digests', {}) - for url in result.download_urls: - if url in sd: # pragma: no cover - d[url] = sd[url] - result.digests = d - self.matcher = None - return result - - -class PyPIRPCLocator(Locator): - """ - This locator uses XML-RPC to locate distributions. It therefore - cannot be used with simple mirrors (that only mirror file content). - """ - def __init__(self, url, **kwargs): - """ - Initialise an instance. - - :param url: The URL to use for XML-RPC. - :param kwargs: Passed to the superclass constructor. - """ - super(PyPIRPCLocator, self).__init__(**kwargs) - self.base_url = url - self.client = ServerProxy(url, timeout=3.0) - - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - return set(self.client.list_packages()) - - def _get_project(self, name): - result = {'urls': {}, 'digests': {}} - versions = self.client.package_releases(name, True) - for v in versions: - urls = self.client.release_urls(name, v) - data = self.client.release_data(name, v) - metadata = Metadata(scheme=self.scheme) - metadata.name = data['name'] - metadata.version = data['version'] - metadata.license = data.get('license') - metadata.keywords = data.get('keywords', []) - metadata.summary = data.get('summary') - dist = Distribution(metadata) - if urls: - info = urls[0] - metadata.source_url = info['url'] - dist.digest = self._get_digest(info) - dist.locator = self - result[v] = dist - for info in urls: - url = info['url'] - digest = self._get_digest(info) - result['urls'].setdefault(v, set()).add(url) - result['digests'][url] = digest - return result - -class PyPIJSONLocator(Locator): - """ - This locator uses PyPI's JSON interface. It's very limited in functionality - and probably not worth using. - """ - def __init__(self, url, **kwargs): - super(PyPIJSONLocator, self).__init__(**kwargs) - self.base_url = ensure_slash(url) - - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - raise NotImplementedError('Not available from this locator') - - def _get_project(self, name): - result = {'urls': {}, 'digests': {}} - url = urljoin(self.base_url, '%s/json' % quote(name)) - try: - resp = self.opener.open(url) - data = resp.read().decode() # for now - d = json.loads(data) - md = Metadata(scheme=self.scheme) - data = d['info'] - md.name = data['name'] - md.version = data['version'] - md.license = data.get('license') - md.keywords = data.get('keywords', []) - md.summary = data.get('summary') - dist = Distribution(md) - dist.locator = self - urls = d['urls'] - result[md.version] = dist - for info in d['urls']: - url = info['url'] - dist.download_urls.add(url) - dist.digests[url] = self._get_digest(info) - result['urls'].setdefault(md.version, set()).add(url) - result['digests'][url] = self._get_digest(info) - # Now get other releases - for version, infos in d['releases'].items(): - if version == md.version: - continue # already done - omd = Metadata(scheme=self.scheme) - omd.name = md.name - omd.version = version - odist = Distribution(omd) - odist.locator = self - result[version] = odist - for info in infos: - url = info['url'] - odist.download_urls.add(url) - odist.digests[url] = self._get_digest(info) - result['urls'].setdefault(version, set()).add(url) - result['digests'][url] = self._get_digest(info) -# for info in urls: -# md.source_url = info['url'] -# dist.digest = self._get_digest(info) -# dist.locator = self -# for info in urls: -# url = info['url'] -# result['urls'].setdefault(md.version, set()).add(url) -# result['digests'][url] = self._get_digest(info) - except Exception as e: - self.errors.put(text_type(e)) - logger.exception('JSON fetch failed: %s', e) - return result - - -class Page(object): - """ - This class represents a scraped HTML page. - """ - # The following slightly hairy-looking regex just looks for the contents of - # an anchor link, which has an attribute "href" either immediately preceded - # or immediately followed by a "rel" attribute. The attribute values can be - # declared with double quotes, single quotes or no quotes - which leads to - # the length of the expression. - _href = re.compile(""" -(rel\\s*=\\s*(?:"(?P[^"]*)"|'(?P[^']*)'|(?P[^>\\s\n]*))\\s+)? -href\\s*=\\s*(?:"(?P[^"]*)"|'(?P[^']*)'|(?P[^>\\s\n]*)) -(\\s+rel\\s*=\\s*(?:"(?P[^"]*)"|'(?P[^']*)'|(?P[^>\\s\n]*)))? -""", re.I | re.S | re.X) - _base = re.compile(r"""]+)""", re.I | re.S) - - def __init__(self, data, url): - """ - Initialise an instance with the Unicode page contents and the URL they - came from. - """ - self.data = data - self.base_url = self.url = url - m = self._base.search(self.data) - if m: - self.base_url = m.group(1) - - _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I) - - @cached_property - def links(self): - """ - Return the URLs of all the links on a page together with information - about their "rel" attribute, for determining which ones to treat as - downloads and which ones to queue for further scraping. - """ - def clean(url): - "Tidy up an URL." - scheme, netloc, path, params, query, frag = urlparse(url) - return urlunparse((scheme, netloc, quote(path), - params, query, frag)) - - result = set() - for match in self._href.finditer(self.data): - d = match.groupdict('') - rel = (d['rel1'] or d['rel2'] or d['rel3'] or - d['rel4'] or d['rel5'] or d['rel6']) - url = d['url1'] or d['url2'] or d['url3'] - url = urljoin(self.base_url, url) - url = unescape(url) - url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url) - result.add((url, rel)) - # We sort the result, hoping to bring the most recent versions - # to the front - result = sorted(result, key=lambda t: t[0], reverse=True) - return result - - -class SimpleScrapingLocator(Locator): - """ - A locator which scrapes HTML pages to locate downloads for a distribution. - This runs multiple threads to do the I/O; performance is at least as good - as pip's PackageFinder, which works in an analogous fashion. - """ - - # These are used to deal with various Content-Encoding schemes. - decoders = { - 'deflate': zlib.decompress, - 'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(b)).read(), - 'none': lambda b: b, - } - - def __init__(self, url, timeout=None, num_workers=10, **kwargs): - """ - Initialise an instance. - :param url: The root URL to use for scraping. - :param timeout: The timeout, in seconds, to be applied to requests. - This defaults to ``None`` (no timeout specified). - :param num_workers: The number of worker threads you want to do I/O, - This defaults to 10. - :param kwargs: Passed to the superclass. - """ - super(SimpleScrapingLocator, self).__init__(**kwargs) - self.base_url = ensure_slash(url) - self.timeout = timeout - self._page_cache = {} - self._seen = set() - self._to_fetch = queue.Queue() - self._bad_hosts = set() - self.skip_externals = False - self.num_workers = num_workers - self._lock = threading.RLock() - # See issue #45: we need to be resilient when the locator is used - # in a thread, e.g. with concurrent.futures. We can't use self._lock - # as it is for coordinating our internal threads - the ones created - # in _prepare_threads. - self._gplock = threading.RLock() - self.platform_check = False # See issue #112 - - def _prepare_threads(self): - """ - Threads are created only when get_project is called, and terminate - before it returns. They are there primarily to parallelise I/O (i.e. - fetching web pages). - """ - self._threads = [] - for i in range(self.num_workers): - t = threading.Thread(target=self._fetch) - t.daemon = True - t.start() - self._threads.append(t) - - def _wait_threads(self): - """ - Tell all the threads to terminate (by sending a sentinel value) and - wait for them to do so. - """ - # Note that you need two loops, since you can't say which - # thread will get each sentinel - for t in self._threads: - self._to_fetch.put(None) # sentinel - for t in self._threads: - t.join() - self._threads = [] - - def _get_project(self, name): - result = {'urls': {}, 'digests': {}} - with self._gplock: - self.result = result - self.project_name = name - url = urljoin(self.base_url, '%s/' % quote(name)) - self._seen.clear() - self._page_cache.clear() - self._prepare_threads() - try: - logger.debug('Queueing %s', url) - self._to_fetch.put(url) - self._to_fetch.join() - finally: - self._wait_threads() - del self.result - return result - - platform_dependent = re.compile(r'\b(linux_(i\d86|x86_64|arm\w+)|' - r'win(32|_amd64)|macosx_?\d+)\b', re.I) - - def _is_platform_dependent(self, url): - """ - Does an URL refer to a platform-specific download? - """ - return self.platform_dependent.search(url) - - def _process_download(self, url): - """ - See if an URL is a suitable download for a project. - - If it is, register information in the result dictionary (for - _get_project) about the specific version it's for. - - Note that the return value isn't actually used other than as a boolean - value. - """ - if self.platform_check and self._is_platform_dependent(url): - info = None - else: - info = self.convert_url_to_download_info(url, self.project_name) - logger.debug('process_download: %s -> %s', url, info) - if info: - with self._lock: # needed because self.result is shared - self._update_version_data(self.result, info) - return info - - def _should_queue(self, link, referrer, rel): - """ - Determine whether a link URL from a referring page and with a - particular "rel" attribute should be queued for scraping. - """ - scheme, netloc, path, _, _, _ = urlparse(link) - if path.endswith(self.source_extensions + self.binary_extensions + - self.excluded_extensions): - result = False - elif self.skip_externals and not link.startswith(self.base_url): - result = False - elif not referrer.startswith(self.base_url): - result = False - elif rel not in ('homepage', 'download'): - result = False - elif scheme not in ('http', 'https', 'ftp'): - result = False - elif self._is_platform_dependent(link): - result = False - else: - host = netloc.split(':', 1)[0] - if host.lower() == 'localhost': - result = False - else: - result = True - logger.debug('should_queue: %s (%s) from %s -> %s', link, rel, - referrer, result) - return result - - def _fetch(self): - """ - Get a URL to fetch from the work queue, get the HTML page, examine its - links for download candidates and candidates for further scraping. - - This is a handy method to run in a thread. - """ - while True: - url = self._to_fetch.get() - try: - if url: - page = self.get_page(url) - if page is None: # e.g. after an error - continue - for link, rel in page.links: - if link not in self._seen: - try: - self._seen.add(link) - if (not self._process_download(link) and - self._should_queue(link, url, rel)): - logger.debug('Queueing %s from %s', link, url) - self._to_fetch.put(link) - except MetadataInvalidError: # e.g. invalid versions - pass - except Exception as e: # pragma: no cover - self.errors.put(text_type(e)) - finally: - # always do this, to avoid hangs :-) - self._to_fetch.task_done() - if not url: - #logger.debug('Sentinel seen, quitting.') - break - - def get_page(self, url): - """ - Get the HTML for an URL, possibly from an in-memory cache. - - XXX TODO Note: this cache is never actually cleared. It's assumed that - the data won't get stale over the lifetime of a locator instance (not - necessarily true for the default_locator). - """ - # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api - scheme, netloc, path, _, _, _ = urlparse(url) - if scheme == 'file' and os.path.isdir(url2pathname(path)): - url = urljoin(ensure_slash(url), 'index.html') - - if url in self._page_cache: - result = self._page_cache[url] - logger.debug('Returning %s from cache: %s', url, result) - else: - host = netloc.split(':', 1)[0] - result = None - if host in self._bad_hosts: - logger.debug('Skipping %s due to bad host %s', url, host) - else: - req = Request(url, headers={'Accept-encoding': 'identity'}) - try: - logger.debug('Fetching %s', url) - resp = self.opener.open(req, timeout=self.timeout) - logger.debug('Fetched %s', url) - headers = resp.info() - content_type = headers.get('Content-Type', '') - if HTML_CONTENT_TYPE.match(content_type): - final_url = resp.geturl() - data = resp.read() - encoding = headers.get('Content-Encoding') - if encoding: - decoder = self.decoders[encoding] # fail if not found - data = decoder(data) - encoding = 'utf-8' - m = CHARSET.search(content_type) - if m: - encoding = m.group(1) - try: - data = data.decode(encoding) - except UnicodeError: # pragma: no cover - data = data.decode('latin-1') # fallback - result = Page(data, final_url) - self._page_cache[final_url] = result - except HTTPError as e: - if e.code != 404: - logger.exception('Fetch failed: %s: %s', url, e) - except URLError as e: # pragma: no cover - logger.exception('Fetch failed: %s: %s', url, e) - with self._lock: - self._bad_hosts.add(host) - except Exception as e: # pragma: no cover - logger.exception('Fetch failed: %s: %s', url, e) - finally: - self._page_cache[url] = result # even if None (failure) - return result - - _distname_re = re.compile(']*>([^<]+)<') - - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - result = set() - page = self.get_page(self.base_url) - if not page: - raise DistlibException('Unable to get %s' % self.base_url) - for match in self._distname_re.finditer(page.data): - result.add(match.group(1)) - return result - -class DirectoryLocator(Locator): - """ - This class locates distributions in a directory tree. - """ - - def __init__(self, path, **kwargs): - """ - Initialise an instance. - :param path: The root of the directory tree to search. - :param kwargs: Passed to the superclass constructor, - except for: - * recursive - if True (the default), subdirectories are - recursed into. If False, only the top-level directory - is searched, - """ - self.recursive = kwargs.pop('recursive', True) - super(DirectoryLocator, self).__init__(**kwargs) - path = os.path.abspath(path) - if not os.path.isdir(path): # pragma: no cover - raise DistlibException('Not a directory: %r' % path) - self.base_dir = path - - def should_include(self, filename, parent): - """ - Should a filename be considered as a candidate for a distribution - archive? As well as the filename, the directory which contains it - is provided, though not used by the current implementation. - """ - return filename.endswith(self.downloadable_extensions) - - def _get_project(self, name): - result = {'urls': {}, 'digests': {}} - for root, dirs, files in os.walk(self.base_dir): - for fn in files: - if self.should_include(fn, root): - fn = os.path.join(root, fn) - url = urlunparse(('file', '', - pathname2url(os.path.abspath(fn)), - '', '', '')) - info = self.convert_url_to_download_info(url, name) - if info: - self._update_version_data(result, info) - if not self.recursive: - break - return result - - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - result = set() - for root, dirs, files in os.walk(self.base_dir): - for fn in files: - if self.should_include(fn, root): - fn = os.path.join(root, fn) - url = urlunparse(('file', '', - pathname2url(os.path.abspath(fn)), - '', '', '')) - info = self.convert_url_to_download_info(url, None) - if info: - result.add(info['name']) - if not self.recursive: - break - return result - -class JSONLocator(Locator): - """ - This locator uses special extended metadata (not available on PyPI) and is - the basis of performant dependency resolution in distlib. Other locators - require archive downloads before dependencies can be determined! As you - might imagine, that can be slow. - """ - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - raise NotImplementedError('Not available from this locator') - - def _get_project(self, name): - result = {'urls': {}, 'digests': {}} - data = get_project_data(name) - if data: - for info in data.get('files', []): - if info['ptype'] != 'sdist' or info['pyversion'] != 'source': - continue - # We don't store summary in project metadata as it makes - # the data bigger for no benefit during dependency - # resolution - dist = make_dist(data['name'], info['version'], - summary=data.get('summary', - 'Placeholder for summary'), - scheme=self.scheme) - md = dist.metadata - md.source_url = info['url'] - # TODO SHA256 digest - if 'digest' in info and info['digest']: - dist.digest = ('md5', info['digest']) - md.dependencies = info.get('requirements', {}) - dist.exports = info.get('exports', {}) - result[dist.version] = dist - result['urls'].setdefault(dist.version, set()).add(info['url']) - return result - -class DistPathLocator(Locator): - """ - This locator finds installed distributions in a path. It can be useful for - adding to an :class:`AggregatingLocator`. - """ - def __init__(self, distpath, **kwargs): - """ - Initialise an instance. - - :param distpath: A :class:`DistributionPath` instance to search. - """ - super(DistPathLocator, self).__init__(**kwargs) - assert isinstance(distpath, DistributionPath) - self.distpath = distpath - - def _get_project(self, name): - dist = self.distpath.get_distribution(name) - if dist is None: - result = {'urls': {}, 'digests': {}} - else: - result = { - dist.version: dist, - 'urls': {dist.version: set([dist.source_url])}, - 'digests': {dist.version: set([None])} - } - return result - - -class AggregatingLocator(Locator): - """ - This class allows you to chain and/or merge a list of locators. - """ - def __init__(self, *locators, **kwargs): - """ - Initialise an instance. - - :param locators: The list of locators to search. - :param kwargs: Passed to the superclass constructor, - except for: - * merge - if False (the default), the first successful - search from any of the locators is returned. If True, - the results from all locators are merged (this can be - slow). - """ - self.merge = kwargs.pop('merge', False) - self.locators = locators - super(AggregatingLocator, self).__init__(**kwargs) - - def clear_cache(self): - super(AggregatingLocator, self).clear_cache() - for locator in self.locators: - locator.clear_cache() - - def _set_scheme(self, value): - self._scheme = value - for locator in self.locators: - locator.scheme = value - - scheme = property(Locator.scheme.fget, _set_scheme) - - def _get_project(self, name): - result = {} - for locator in self.locators: - d = locator.get_project(name) - if d: - if self.merge: - files = result.get('urls', {}) - digests = result.get('digests', {}) - # next line could overwrite result['urls'], result['digests'] - result.update(d) - df = result.get('urls') - if files and df: - for k, v in files.items(): - if k in df: - df[k] |= v - else: - df[k] = v - dd = result.get('digests') - if digests and dd: - dd.update(digests) - else: - # See issue #18. If any dists are found and we're looking - # for specific constraints, we only return something if - # a match is found. For example, if a DirectoryLocator - # returns just foo (1.0) while we're looking for - # foo (>= 2.0), we'll pretend there was nothing there so - # that subsequent locators can be queried. Otherwise we - # would just return foo (1.0) which would then lead to a - # failure to find foo (>= 2.0), because other locators - # weren't searched. Note that this only matters when - # merge=False. - if self.matcher is None: - found = True - else: - found = False - for k in d: - if self.matcher.match(k): - found = True - break - if found: - result = d - break - return result - - def get_distribution_names(self): - """ - Return all the distribution names known to this locator. - """ - result = set() - for locator in self.locators: - try: - result |= locator.get_distribution_names() - except NotImplementedError: - pass - return result - - -# We use a legacy scheme simply because most of the dists on PyPI use legacy -# versions which don't conform to PEP 426 / PEP 440. -default_locator = AggregatingLocator( - JSONLocator(), - SimpleScrapingLocator('https://pypi.org/simple/', - timeout=3.0), - scheme='legacy') - -locate = default_locator.locate - - -class DependencyFinder(object): - """ - Locate dependencies for distributions. - """ - - def __init__(self, locator=None): - """ - Initialise an instance, using the specified locator - to locate distributions. - """ - self.locator = locator or default_locator - self.scheme = get_scheme(self.locator.scheme) - - def add_distribution(self, dist): - """ - Add a distribution to the finder. This will update internal information - about who provides what. - :param dist: The distribution to add. - """ - logger.debug('adding distribution %s', dist) - name = dist.key - self.dists_by_name[name] = dist - self.dists[(name, dist.version)] = dist - for p in dist.provides: - name, version = parse_name_and_version(p) - logger.debug('Add to provided: %s, %s, %s', name, version, dist) - self.provided.setdefault(name, set()).add((version, dist)) - - def remove_distribution(self, dist): - """ - Remove a distribution from the finder. This will update internal - information about who provides what. - :param dist: The distribution to remove. - """ - logger.debug('removing distribution %s', dist) - name = dist.key - del self.dists_by_name[name] - del self.dists[(name, dist.version)] - for p in dist.provides: - name, version = parse_name_and_version(p) - logger.debug('Remove from provided: %s, %s, %s', name, version, dist) - s = self.provided[name] - s.remove((version, dist)) - if not s: - del self.provided[name] - - def get_matcher(self, reqt): - """ - Get a version matcher for a requirement. - :param reqt: The requirement - :type reqt: str - :return: A version matcher (an instance of - :class:`distlib.version.Matcher`). - """ - try: - matcher = self.scheme.matcher(reqt) - except UnsupportedVersionError: # pragma: no cover - # XXX compat-mode if cannot read the version - name = reqt.split()[0] - matcher = self.scheme.matcher(name) - return matcher - - def find_providers(self, reqt): - """ - Find the distributions which can fulfill a requirement. - - :param reqt: The requirement. - :type reqt: str - :return: A set of distribution which can fulfill the requirement. - """ - matcher = self.get_matcher(reqt) - name = matcher.key # case-insensitive - result = set() - provided = self.provided - if name in provided: - for version, provider in provided[name]: - try: - match = matcher.match(version) - except UnsupportedVersionError: - match = False - - if match: - result.add(provider) - break - return result - - def try_to_replace(self, provider, other, problems): - """ - Attempt to replace one provider with another. This is typically used - when resolving dependencies from multiple sources, e.g. A requires - (B >= 1.0) while C requires (B >= 1.1). - - For successful replacement, ``provider`` must meet all the requirements - which ``other`` fulfills. - - :param provider: The provider we are trying to replace with. - :param other: The provider we're trying to replace. - :param problems: If False is returned, this will contain what - problems prevented replacement. This is currently - a tuple of the literal string 'cantreplace', - ``provider``, ``other`` and the set of requirements - that ``provider`` couldn't fulfill. - :return: True if we can replace ``other`` with ``provider``, else - False. - """ - rlist = self.reqts[other] - unmatched = set() - for s in rlist: - matcher = self.get_matcher(s) - if not matcher.match(provider.version): - unmatched.add(s) - if unmatched: - # can't replace other with provider - problems.add(('cantreplace', provider, other, - frozenset(unmatched))) - result = False - else: - # can replace other with provider - self.remove_distribution(other) - del self.reqts[other] - for s in rlist: - self.reqts.setdefault(provider, set()).add(s) - self.add_distribution(provider) - result = True - return result - - def find(self, requirement, meta_extras=None, prereleases=False): - """ - Find a distribution and all distributions it depends on. - - :param requirement: The requirement specifying the distribution to - find, or a Distribution instance. - :param meta_extras: A list of meta extras such as :test:, :build: and - so on. - :param prereleases: If ``True``, allow pre-release versions to be - returned - otherwise, don't return prereleases - unless they're all that's available. - - Return a set of :class:`Distribution` instances and a set of - problems. - - The distributions returned should be such that they have the - :attr:`required` attribute set to ``True`` if they were - from the ``requirement`` passed to ``find()``, and they have the - :attr:`build_time_dependency` attribute set to ``True`` unless they - are post-installation dependencies of the ``requirement``. - - The problems should be a tuple consisting of the string - ``'unsatisfied'`` and the requirement which couldn't be satisfied - by any distribution known to the locator. - """ - - self.provided = {} - self.dists = {} - self.dists_by_name = {} - self.reqts = {} - - meta_extras = set(meta_extras or []) - if ':*:' in meta_extras: - meta_extras.remove(':*:') - # :meta: and :run: are implicitly included - meta_extras |= set([':test:', ':build:', ':dev:']) - - if isinstance(requirement, Distribution): - dist = odist = requirement - logger.debug('passed %s as requirement', odist) - else: - dist = odist = self.locator.locate(requirement, - prereleases=prereleases) - if dist is None: - raise DistlibException('Unable to locate %r' % requirement) - logger.debug('located %s', odist) - dist.requested = True - problems = set() - todo = set([dist]) - install_dists = set([odist]) - while todo: - dist = todo.pop() - name = dist.key # case-insensitive - if name not in self.dists_by_name: - self.add_distribution(dist) - else: - #import pdb; pdb.set_trace() - other = self.dists_by_name[name] - if other != dist: - self.try_to_replace(dist, other, problems) - - ireqts = dist.run_requires | dist.meta_requires - sreqts = dist.build_requires - ereqts = set() - if meta_extras and dist in install_dists: - for key in ('test', 'build', 'dev'): - e = ':%s:' % key - if e in meta_extras: - ereqts |= getattr(dist, '%s_requires' % key) - all_reqts = ireqts | sreqts | ereqts - for r in all_reqts: - providers = self.find_providers(r) - if not providers: - logger.debug('No providers found for %r', r) - provider = self.locator.locate(r, prereleases=prereleases) - # If no provider is found and we didn't consider - # prereleases, consider them now. - if provider is None and not prereleases: - provider = self.locator.locate(r, prereleases=True) - if provider is None: - logger.debug('Cannot satisfy %r', r) - problems.add(('unsatisfied', r)) - else: - n, v = provider.key, provider.version - if (n, v) not in self.dists: - todo.add(provider) - providers.add(provider) - if r in ireqts and dist in install_dists: - install_dists.add(provider) - logger.debug('Adding %s to install_dists', - provider.name_and_version) - for p in providers: - name = p.key - if name not in self.dists_by_name: - self.reqts.setdefault(p, set()).add(r) - else: - other = self.dists_by_name[name] - if other != p: - # see if other can be replaced by p - self.try_to_replace(p, other, problems) - - dists = set(self.dists.values()) - for dist in dists: - dist.build_time_dependency = dist not in install_dists - if dist.build_time_dependency: - logger.debug('%s is a build-time dependency only.', - dist.name_and_version) - logger.debug('find done for %s', odist) - return dists, problems diff --git a/spaces/aliabd/SummerTime/model/third_party/HMNet/ThirdParty/ROUGE/ROUGE-1.5.5/XML/DOM/Element.pod b/spaces/aliabd/SummerTime/model/third_party/HMNet/ThirdParty/ROUGE/ROUGE-1.5.5/XML/DOM/Element.pod deleted file mode 100644 index d4a289aa7fa4072e49506cf8558af15df56e4c1d..0000000000000000000000000000000000000000 --- a/spaces/aliabd/SummerTime/model/third_party/HMNet/ThirdParty/ROUGE/ROUGE-1.5.5/XML/DOM/Element.pod +++ /dev/null @@ -1,189 +0,0 @@ -=head1 NAME - -XML::DOM::Element - An XML element node in XML::DOM - -=head1 DESCRIPTION - -XML::DOM::Element extends L. - -By far the vast majority of objects (apart from text) that authors -encounter when traversing a document are Element nodes. Assume the -following XML document: - - - - - - -When represented using DOM, the top node is an Element node for -"elementExample", which contains two child Element nodes, one for -"subelement1" and one for "subelement2". "subelement1" contains no -child nodes. - -Elements may have attributes associated with them; since the Element -interface inherits from Node, the generic Node interface method -getAttributes may be used to retrieve the set of all attributes for an -element. There are methods on the Element interface to retrieve either -an Attr object by name or an attribute value by name. In XML, where an -attribute value may contain entity references, an Attr object should be -retrieved to examine the possibly fairly complex sub-tree representing -the attribute value. On the other hand, in HTML, where all attributes -have simple string values, methods to directly access an attribute -value can safely be used as a convenience. - -=head2 METHODS - -=over 4 - -=item getTagName - -The name of the element. For example, in: - - - ... - - -tagName has the value "elementExample". Note that this is -case-preserving in XML, as are all of the operations of the -DOM. - -=item getAttribute (name) - -Retrieves an attribute value by name. - -Return Value: The Attr value as a string, or the empty string if that -attribute does not have a specified or default value. - -=item setAttribute (name, value) - -Adds a new attribute. If an attribute with that name is -already present in the element, its value is changed to be -that of the value parameter. This value is a simple string, -it is not parsed as it is being set. So any markup (such as -syntax to be recognized as an entity reference) is treated as -literal text, and needs to be appropriately escaped by the -implementation when it is written out. In order to assign an -attribute value that contains entity references, the user -must create an Attr node plus any Text and EntityReference -nodes, build the appropriate subtree, and use -setAttributeNode to assign it as the value of an attribute. - - -DOMExceptions: - -=over 4 - -=item * INVALID_CHARACTER_ERR - -Raised if the specified name contains an invalid character. - -=item * NO_MODIFICATION_ALLOWED_ERR - -Raised if this node is readonly. - -=back - -=item removeAttribute (name) - -Removes an attribute by name. If the removed attribute has a -default value it is immediately replaced. - -DOMExceptions: - -=over 4 - -=item * NO_MODIFICATION_ALLOWED_ERR - -Raised if this node is readonly. - -=back - -=item getAttributeNode - -Retrieves an Attr node by name. - -Return Value: The Attr node with the specified attribute name or undef -if there is no such attribute. - -=item setAttributeNode (attr) - -Adds a new attribute. If an attribute with that name is -already present in the element, it is replaced by the new one. - -Return Value: If the newAttr attribute replaces an existing attribute -with the same name, the previously existing Attr node is -returned, otherwise undef is returned. - -DOMExceptions: - -=over 4 - -=item * WRONG_DOCUMENT_ERR - -Raised if newAttr was created from a different document than the one that created -the element. - -=item * NO_MODIFICATION_ALLOWED_ERR - -Raised if this node is readonly. - -=item * INUSE_ATTRIBUTE_ERR - -Raised if newAttr is already an attribute of another Element object. The DOM -user must explicitly clone Attr nodes to re-use them in other elements. - -=back - -=item removeAttributeNode (oldAttr) - -Removes the specified attribute. If the removed Attr has a default value it is -immediately replaced. If the Attr already is the default value, nothing happens -and nothing is returned. - -Parameters: - I The Attr node to remove from the attribute list. - -Return Value: The Attr node that was removed. - -DOMExceptions: - -=over 4 - -=item * NO_MODIFICATION_ALLOWED_ERR - -Raised if this node is readonly. - -=item * NOT_FOUND_ERR - -Raised if oldAttr is not an attribute of the element. - -=back - -=head2 Additional methods not in the DOM Spec - -=over 4 - -=item setTagName (newTagName) - -Sets the tag name of the Element. Note that this method is not portable -between DOM implementations. - -DOMExceptions: - -=over 4 - -=item * INVALID_CHARACTER_ERR - -Raised if the specified name contains an invalid character. - -=back - -=item check ($checker) - -Uses the specified L to validate the document. -NOTE: an XML::Checker must be supplied. The checker can be created in -different ways, e.g. when parsing a document with XML::DOM::ValParser, -or with XML::DOM::Document::createChecker(). -See L for more info. - -=back diff --git a/spaces/aliabid94/AutoGPT/autogpt/commands/web_playwright.py b/spaces/aliabid94/AutoGPT/autogpt/commands/web_playwright.py deleted file mode 100644 index 4e388ded203cefb5e24f9116f7fe5b8a94893413..0000000000000000000000000000000000000000 --- a/spaces/aliabid94/AutoGPT/autogpt/commands/web_playwright.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Web scraping commands using Playwright""" -from __future__ import annotations - -try: - from playwright.sync_api import sync_playwright -except ImportError: - print( - "Playwright not installed. Please install it with 'pip install playwright' to use." - ) -from bs4 import BeautifulSoup - -from autogpt.processing.html import extract_hyperlinks, format_hyperlinks - - -def scrape_text(url: str) -> str: - """Scrape text from a webpage - - Args: - url (str): The URL to scrape text from - - Returns: - str: The scraped text - """ - with sync_playwright() as p: - browser = p.chromium.launch() - page = browser.new_page() - - try: - page.goto(url) - html_content = page.content() - soup = BeautifulSoup(html_content, "html.parser") - - for script in soup(["script", "style"]): - script.extract() - - text = soup.get_text() - lines = (line.strip() for line in text.splitlines()) - chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) - text = "\n".join(chunk for chunk in chunks if chunk) - - except Exception as e: - text = f"Error: {str(e)}" - - finally: - browser.close() - - return text - - -def scrape_links(url: str) -> str | list[str]: - """Scrape links from a webpage - - Args: - url (str): The URL to scrape links from - - Returns: - Union[str, List[str]]: The scraped links - """ - with sync_playwright() as p: - browser = p.chromium.launch() - page = browser.new_page() - - try: - page.goto(url) - html_content = page.content() - soup = BeautifulSoup(html_content, "html.parser") - - for script in soup(["script", "style"]): - script.extract() - - hyperlinks = extract_hyperlinks(soup, url) - formatted_links = format_hyperlinks(hyperlinks) - - except Exception as e: - formatted_links = f"Error: {str(e)}" - - finally: - browser.close() - - return formatted_links diff --git a/spaces/alihalabyah/falcon-180b-demo/README.md b/spaces/alihalabyah/falcon-180b-demo/README.md deleted file mode 100644 index 04189396d29fcc4721c66850250efc7c85a18276..0000000000000000000000000000000000000000 --- a/spaces/alihalabyah/falcon-180b-demo/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Falcon-180B Demo -emoji: 💬 -colorFrom: indigo -colorTo: purple -sdk: gradio -sdk_version: 3.42.0 -app_file: app.py -duplicated_from: tiiuae/falcon-180b-demo ---- diff --git a/spaces/allknowingroger/Image-Models-Test170/app.py b/spaces/allknowingroger/Image-Models-Test170/app.py deleted file mode 100644 index 9d63351c8017d9ab699e83bcdf09f8a0e08ba471..0000000000000000000000000000000000000000 --- a/spaces/allknowingroger/Image-Models-Test170/app.py +++ /dev/null @@ -1,144 +0,0 @@ -import gradio as gr -# import os -# import sys -# from pathlib import Path -import time - -models =[ - "anupamtripathi/model_2", - "digiplay/majicMIX_realistic_v4", - "mokshu3242/my-pet-mouse", - "jsram/pboobs", - "madhuuuuuu/my-thar", - "Meghana779905/my-pet-dog", - "Devops-hestabit/Stable_dreamshape", - "venumadhav04/my-thar", - "gbellamy/lora-trained-xl-colab", -] - - -model_functions = {} -model_idx = 1 -for model_path in models: - try: - model_functions[model_idx] = gr.Interface.load(f"models/{model_path}", live=False, preprocess=True, postprocess=False) - except Exception as error: - def the_fn(txt): - return None - model_functions[model_idx] = gr.Interface(fn=the_fn, inputs=["text"], outputs=["image"]) - model_idx+=1 - - -def send_it_idx(idx): - def send_it_fn(prompt): - output = (model_functions.get(str(idx)) or model_functions.get(str(1)))(prompt) - return output - return send_it_fn - -def get_prompts(prompt_text): - return prompt_text - -def clear_it(val): - if int(val) != 0: - val = 0 - else: - val = 0 - pass - return val - -def all_task_end(cnt,t_stamp): - to = t_stamp + 60 - et = time.time() - if et > to and t_stamp != 0: - d = gr.update(value=0) - tog = gr.update(value=1) - #print(f'to: {to} et: {et}') - else: - if cnt != 0: - d = gr.update(value=et) - else: - d = gr.update(value=0) - tog = gr.update(value=0) - #print (f'passing: to: {to} et: {et}') - pass - return d, tog - -def all_task_start(): - print("\n\n\n\n\n\n\n") - t = time.gmtime() - t_stamp = time.time() - current_time = time.strftime("%H:%M:%S", t) - return gr.update(value=t_stamp), gr.update(value=t_stamp), gr.update(value=0) - -def clear_fn(): - nn = len(models) - return tuple([None, *[None for _ in range(nn)]]) - - - -with gr.Blocks(title="SD Models") as my_interface: - with gr.Column(scale=12): - # with gr.Row(): - # gr.Markdown("""- Primary prompt: 你想画的内容(英文单词,如 a cat, 加英文逗号效果更好;点 Improve 按钮进行完善)\n- Real prompt: 完善后的提示词,出现后再点右边的 Run 按钮开始运行""") - with gr.Row(): - with gr.Row(scale=6): - primary_prompt=gr.Textbox(label="Prompt", value="") - # real_prompt=gr.Textbox(label="Real prompt") - with gr.Row(scale=6): - # improve_prompts_btn=gr.Button("Improve") - with gr.Row(): - run=gr.Button("Run",variant="primary") - clear_btn=gr.Button("Clear") - with gr.Row(): - sd_outputs = {} - model_idx = 1 - for model_path in models: - with gr.Column(scale=3, min_width=320): - with gr.Box(): - sd_outputs[model_idx] = gr.Image(label=model_path) - pass - model_idx += 1 - pass - pass - - with gr.Row(visible=False): - start_box=gr.Number(interactive=False) - end_box=gr.Number(interactive=False) - tog_box=gr.Textbox(value=0,interactive=False) - - start_box.change( - all_task_end, - [start_box, end_box], - [start_box, tog_box], - every=1, - show_progress=False) - - primary_prompt.submit(all_task_start, None, [start_box, end_box, tog_box]) - run.click(all_task_start, None, [start_box, end_box, tog_box]) - runs_dict = {} - model_idx = 1 - for model_path in models: - runs_dict[model_idx] = run.click(model_functions[model_idx], inputs=[primary_prompt], outputs=[sd_outputs[model_idx]]) - model_idx += 1 - pass - pass - - # improve_prompts_btn_clicked=improve_prompts_btn.click( - # get_prompts, - # inputs=[primary_prompt], - # outputs=[primary_prompt], - # cancels=list(runs_dict.values())) - clear_btn.click( - clear_fn, - None, - [primary_prompt, *list(sd_outputs.values())], - cancels=[*list(runs_dict.values())]) - tog_box.change( - clear_it, - tog_box, - tog_box, - cancels=[*list(runs_dict.values())]) - -my_interface.queue(concurrency_count=600, status_update_rate=1) -my_interface.launch(inline=True, show_api=False) - \ No newline at end of file diff --git a/spaces/amankishore/sjc/run_nerf.py b/spaces/amankishore/sjc/run_nerf.py deleted file mode 100644 index a66ed3c600ff43614c8dab4127e28f928a580dc8..0000000000000000000000000000000000000000 --- a/spaces/amankishore/sjc/run_nerf.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List -from pydantic import validator - -from my.config import BaseConf, SingleOrList, dispatch -from my.utils.seed import seed_everything - -import numpy as np -from voxnerf.vox import VOXRF_REGISTRY -from voxnerf.pipelines import train - - -class VoxConfig(BaseConf): - model_type: str = "VoxRF" - bbox_len: float = 1.5 - grid_size: SingleOrList(int) = [128, 128, 128] - step_ratio: float = 0.5 - density_shift: float = -10. - ray_march_weight_thres: float = 0.0001 - c: int = 3 - blend_bg_texture: bool = False - bg_texture_hw: int = 64 - - @validator("grid_size") - def check_gsize(cls, grid_size): - if isinstance(grid_size, int): - return [grid_size, ] * 3 - else: - assert len(grid_size) == 3 - return grid_size - - def make(self): - params = self.dict() - m_type = params.pop("model_type") - model_fn = VOXRF_REGISTRY.get(m_type) - - radius = params.pop('bbox_len') - aabb = radius * np.array([ - [-1, -1, -1], - [1, 1, 1] - ]) - model = model_fn(aabb=aabb, **params) - return model - - -class TrainerConfig(BaseConf): - model: VoxConfig = VoxConfig() - scene: str = "lego" - n_epoch: int = 2 - bs: int = 4096 - lr: float = 0.02 - - def run(self): - args = self.dict() - args.pop("model") - - model = self.model.make() - train(model, **args) - - -if __name__ == "__main__": - seed_everything(0) - dispatch(TrainerConfig) diff --git a/spaces/amsterdamNLP/value-zeroing/description.md b/spaces/amsterdamNLP/value-zeroing/description.md deleted file mode 100644 index 87616058992d91a61bceb41597017c9b416dfe68..0000000000000000000000000000000000000000 --- a/spaces/amsterdamNLP/value-zeroing/description.md +++ /dev/null @@ -1,4 +0,0 @@ -# Value Zeroing - -Demo of the effect of value-zeroing ([Mohebbi et al., 2023](https://arxiv.org/abs/2301.12971)) both with Attention Rollout ([Abnar & Zuidema, 2020](https://aclanthology.org/2020.acl-main.385/)) -and without. diff --git a/spaces/anisharitakula/sentiment_classifier/app.py b/spaces/anisharitakula/sentiment_classifier/app.py deleted file mode 100644 index fd2c4a61e8421e4fd9f0bfd085742cf6647cf462..0000000000000000000000000000000000000000 --- a/spaces/anisharitakula/sentiment_classifier/app.py +++ /dev/null @@ -1,1005 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# In[1]: - - -import pickle -import copy -import numpy as np -import pickle - -#pip install torch -import torch -import torch.nn as nn -#pip install transformers -from transformers import BertModel, BertTokenizer -#import utils - - -# In[2]: - - -#!pip install nltk -#!pip install tensorflow --upgrade -import os - -import torch -import torch.nn as nn -import transformers -from transformers import BertModel, BertTokenizer - -# from torch_shallow_neural_classifier import TorchShallowNeuralClassifier -# from torch_rnn_classifier import TorchRNNModel -# from torch_rnn_classifier import TorchRNNClassifier -# from torch_rnn_classifier import TorchRNNClassifierModel -# from torch_rnn_classifier import TorchRNNClassifier -# import sst -# import utils - -#!pip install numpy --upgrade -import numpy as np - -import pandas as pd - -#pip install nltk -from nltk.tokenize.treebank import TreebankWordDetokenizer -from nltk.tokenize.treebank import TreebankWordTokenizer - - - -import tensorflow as tf - - -# In[79]: - - -class TorchModelBase: - def __init__(self, - batch_size=1028, - max_iter=1000, - eta=0.001, - optimizer_class=torch.optim.Adam, - l2_strength=0, - gradient_accumulation_steps=1, - max_grad_norm=None, - warm_start=False, - early_stopping=False, - validation_fraction=0.1, - shuffle_train=True, - n_iter_no_change=10, - tol=1e-5, - device=None, - display_progress=True, - **optimizer_kwargs): - """ - Base class for all the PyTorch-based models. - - Parameters - ---------- - batch_size: int - Number of examples per batch. Batching is handled by a - `torch.utils.data.DataLoader`. Final batches can have fewer - examples, depending on the total number of examples in the - dataset. - - max_iter: int - Maximum number of training iterations. This will interact - with `early_stopping`, `n_iter_no_change`, and `tol` in the - sense that this limit will be reached if and only if and - conditions triggered by those other parameters are not met. - - eta : float - Learning rate for the optimizer. - - optimizer_class: `torch.optimizer.Optimizer` - Any PyTorch optimizer should work. Additional arguments - can be passed to this object via `**optimizer_kwargs`. The - optimizer itself is built by `self.build_optimizer` when - `fit` is called. - - l2_strength: float - L2 regularization parameters for the optimizer. The default - of 0 means no regularization, and larger values correspond - to stronger regularization. - - gradient_accumulation_steps: int - Controls how often the model parameters are updated during - learning. For example, with `gradient_accumulation_steps=2`, - the parameters are updated after every other batch. The primary - use case for `gradient_accumulation_steps > 1` is where the - model is very large, so only small batches of examples can be - fit into memory. The updates based on these small batches can - have high variance, so accumulating a few batches before - updating can smooth the process out. - - max_grad_norm: None or float - If not `None`, then `torch.nn.utils.clip_grad_norm_` is used - to clip all the model parameters to within the range set - by this value. This is a kind of brute-force way of keeping - the parameter values from growing absurdly large or small. - - warm_start: bool - If `False`, then repeated calls to `fit` will reset all the - optimization settings: the model parameters, the optimizer, - and the metadata we collect during optimization. If `True`, - then calling `fit` twice with `max_iter=N` should be the same - as calling fit once with `max_iter=N*2`. - - early_stopping: bool - If `True`, then `validation_fraction` of the data given to - `fit` are held out and used to assess the model after every - epoch. The best scoring model is stored in an attribute - `best_parameters`. If an improvement of at least `self.tol` - isn't seen after `n_iter_no_change` iterations, then training - stops and `self.model` is set to use `best_parameters`. - - validation_fraction: float - Percentage of the data given to `fit` to hold out for use in - early stopping. Ignored if `early_stopping=False` - - shuffle_train: bool - Whether to shuffle the training data. - - n_iter_no_change: int - Number of epochs used to control convergence and early - stopping. Where `early_stopping=True`, training stops if an - improvement of more than `self.tol` isn't seen after this - many epochs. If `early_stopping=False`, then training stops - if the epoch error doesn't drop by at least `self.tol` after - this many epochs. - - tol: float - Value used to control `early_stopping` and convergence. - - device: str or None - Used to set the device on which the PyTorch computations will - be done. If `device=None`, this will choose a CUDA device if - one is available, else the CPU is used. - - display_progress: bool - Whether to print optimization information incrementally to - `sys.stderr` during training. - - **optimizer_kwargs: kwargs - Any additional keywords given to the model will be passed to - the optimizer -- see `self.build_optimizer`. The intent is to - make it easy to tune these as hyperparameters will still - allowing the user to specify just `optimizer_class` rather - than setting up a full optimizer. - - Attributes - ---------- - params: list - All the keyword arguments are parameters and, with the - exception of `display_progress`, their names are added to - this list to support working with them using tools from - `sklearn.model_selection`. - - """ - self.batch_size = batch_size - self.max_iter = max_iter - self.eta = eta - self.optimizer_class = optimizer_class - self.l2_strength = l2_strength - self.gradient_accumulation_steps = max([gradient_accumulation_steps, 1]) - self.max_grad_norm = max_grad_norm - self.warm_start = warm_start - self.early_stopping = early_stopping - self.validation_fraction = validation_fraction - self.shuffle_train = shuffle_train - self.n_iter_no_change = n_iter_no_change - self.tol = tol - if device is None: - device = "cuda" if torch.cuda.is_available() else "cpu" - self.device = torch.device(device) - self.display_progress = display_progress - self.optimizer_kwargs = optimizer_kwargs - for k, v in self.optimizer_kwargs.items(): - setattr(self, k, v) - self.params = [ - 'batch_size', - 'max_iter', - 'eta', - 'optimizer_class', - 'l2_strength', - 'gradient_accumulation_steps', - 'max_grad_norm', - 'validation_fraction', - 'early_stopping', - 'n_iter_no_change', - 'warm_start', - 'tol'] - self.params += list(optimizer_kwargs.keys()) - - def build_dataset(self, *args, **kwargs): - """ - Subclasses are required to define this method. Perhaps the most - important design note is that the function should be prepared to - return datasets that are appropriate for both training and - prediction. For training, we expect `*args` to have labels in - final position. For prediction, we expect all of `*args` to be - model inputs. For example, in a simple classifier, we expect - `*args` to be a pair `(X, y)` for training and so this method - should return something like: - - `torch.utils.data.TensorDataset(X, y)` - - For prediction, we get only `X`, so we should return - - `torch.utils.data.TensorDataset(X)` - - Parameters - ---------- - *args: any arguments to be used to create the dataset - - **kwargs: any desired keyword arguments - - Returns - ------- - `torch.utils.data.Dataset` or a custom subclass thereof - - """ - raise NotImplementedError - - def build_graph(self, *args, **kwargs): - """ - Build the core computational graph. This is called only after - `fit` is called. The return value of this function becomes the - the `self.model` attribute. - - Parameters - ---------- - *args: any arguments to be used to create the dataset - - **kwargs: any desired keyword arguments - - Returns - ------- - nn.Module or subclass thereof - - """ - raise NotImplementedError - - def score(self, *args): - """ - Required by the `sklearn.model_selection` tools. This function - needs to take the same arguments as `fit`. For `*args` is usually - an `(X, y)` pair of features and labels, and `self.predict(X)` - is called and then some kind of scoring function is used to - compare those predictions with `y`. The return value should be - some kind of appropriate score for the model in question. - - Notes - ----- - For early stopping, we use this function to get scores and - assume that larger scores are better. This would conflict with - using, say, a mean-squared-error scoring function. - - """ - raise NotImplementedError - - def build_optimizer(self): - """ - Builds the optimizer. This function is called only when `fit` - is called. - - Returns - ------- - torch.optimizer.Optimizer - - """ - return self.optimizer_class( - self.model.parameters(), - lr=self.eta, - weight_decay=self.l2_strength, - **self.optimizer_kwargs) - - def fit(self, *args): - """ - Generic optimization method. - - Parameters - ---------- - *args: list of objects - We assume that the final element of args give the labels - and all the preceding elements give the system inputs. - For regular supervised learning, this is like (X, y), but - we allow for models that might use multiple data structures - for their inputs. - - Attributes - ---------- - model: nn.Module or subclass thereof - Set by `build_graph`. If `warm_start=True`, then this is - initialized only by the first call to `fit`. - - optimizer: torch.optimizer.Optimizer - Set by `build_optimizer`. If `warm_start=True`, then this is - initialized only by the first call to `fit`. - - errors: list of float - List of errors. If `warm_start=True`, then this is - initialized only by the first call to `fit`. Thus, where - `max_iter=5`, if we call `fit` twice with `warm_start=True`, - then `errors` will end up with 10 floats in it. - - validation_scores: list - List of scores. This is filled only if `early_stopping=True`. - If `warm_start=True`, then this is initialized only by the - first call to `fit`. Thus, where `max_iter=5`, if we call - `fit` twice with `warm_start=True`, then `validation_scores` - will end up with 10 floats in it. - - no_improvement_count: int - Used to control early stopping and convergence. These values - are controlled by `_update_no_improvement_count_early_stopping` - or `_update_no_improvement_count_errors`. If `warm_start=True`, - then this is initialized only by the first call to `fit`. Thus, - in that situation, the values could accumulate across calls to - `fit`. - - best_error: float - Used to control convergence. Smaller is assumed to be better. - If `warm_start=True`, then this is initialized only by the first - call to `fit`. It will be reset by - `_update_no_improvement_count_errors` depending on how the - optimization is proceeding. - - best_score: float - Used to control early stopping. If `warm_start=True`, then this - is initialized only by the first call to `fit`. It will be reset - by `_update_no_improvement_count_early_stopping` depending on how - the optimization is proceeding. Important: we currently assume - that larger scores are better. As a result, we will not get the - correct results for, e.g., a scoring function based in - `mean_squared_error`. See `self.score` for additional details. - - best_parameters: dict - This is a PyTorch state dict. It is used if and only if - `early_stopping=True`. In that case, it is updated whenever - `best_score` is improved numerically. If the early stopping - criteria are met, then `self.model` is reset to contain these - parameters before `fit` exits. - - Returns - ------- - self - - """ - if self.early_stopping: - args, dev = self._build_validation_split( - *args, validation_fraction=self.validation_fraction) - - # Dataset: - dataset = self.build_dataset(*args) - dataloader = self._build_dataloader(dataset, shuffle=self.shuffle_train) - - # Set up parameters needed to use the model. This is a separate - # function to support using pretrained models for prediction, - # where it might not be desirable to call `fit`. - self.initialize() - - # Make sure the model is where we want it: - self.model.to(self.device) - - self.model.train() - self.optimizer.zero_grad() - - for iteration in range(1, self.max_iter+1): - - epoch_error = 0.0 - - for batch_num, batch in enumerate(dataloader, start=1): - - batch = [x.to(self.device, non_blocking=True) for x in batch] - - X_batch = batch[: -1] - y_batch = batch[-1] - - batch_preds = self.model(*X_batch) - - err = self.loss(batch_preds, y_batch) - - if self.gradient_accumulation_steps > 1 and \ - self.loss.reduction == "mean": - err /= self.gradient_accumulation_steps - - err.backward() - - epoch_error += err.item() - - if batch_num % self.gradient_accumulation_steps == 0 or \ - batch_num == len(dataloader): - if self.max_grad_norm is not None: - torch.nn.utils.clip_grad_norm_( - self.model.parameters(), self.max_grad_norm) - self.optimizer.step() - self.optimizer.zero_grad() - - # Stopping criteria: - - if self.early_stopping: - self._update_no_improvement_count_early_stopping(*dev) - if self.no_improvement_count > self.n_iter_no_change: - utils.progress_bar( - "Stopping after epoch {}. Validation score did " - "not improve by tol={} for more than {} epochs. " - "Final error is {}".format(iteration, self.tol, - self.n_iter_no_change, epoch_error), - verbose=self.display_progress) - break - - else: - self._update_no_improvement_count_errors(epoch_error) - if self.no_improvement_count > self.n_iter_no_change: - utils.progress_bar( - "Stopping after epoch {}. Training loss did " - "not improve more than tol={}. Final error " - "is {}.".format(iteration, self.tol, epoch_error), - verbose=self.display_progress) - break - - utils.progress_bar( - "Finished epoch {} of {}; error is {}".format( - iteration, self.max_iter, epoch_error), - verbose=self.display_progress) - - if self.early_stopping: - self.model.load_state_dict(self.best_parameters) - - return self - - def initialize(self): - """ - Method called by `fit` to establish core attributes. To use a - pretrained model without calling `fit`, one can use this - method. - - """ - if not self.warm_start or not hasattr(self, "model"): - self.model = self.build_graph() - # This device move has to happen before the optimizer is built: - # https://pytorch.org/docs/master/optim.html#constructing-it - self.model.to(self.device) - self.optimizer = self.build_optimizer() - self.errors = [] - self.validation_scores = [] - self.no_improvement_count = 0 - self.best_error = np.inf - self.best_score = -np.inf - self.best_parameters = None - - @staticmethod - def _build_validation_split(*args, validation_fraction=0.2): - """ - Split `*args` into train and dev portions for early stopping. - We use `train_test_split`. For args of length N, then delivers - N*2 objects, arranged as - - X1_train, X1_test, X2_train, X2_test, ..., y_train, y_test - - Parameters - ---------- - *args: List of objects to split. - - validation_fraction: float - Percentage of the examples to use for the dev portion. In - `fit`, this is determined by `self.validation_fraction`. - We give it as an argument here to facilitate unit testing. - - Returns - ------- - Pair of tuples `train` and `dev` - - """ - if validation_fraction == 1.0: - return args, args - results = train_test_split(*args, test_size=validation_fraction) - train = results[::2] - dev = results[1::2] - return train, dev - - def _build_dataloader(self, dataset, shuffle=True): - """ - Internal method used to create a dataloader from a dataset. - This is used by `fit` and `_predict`. - - Parameters - ---------- - dataset: torch.utils.data.Dataset - - shuffle: bool - When training, this is `True`. For prediction, this is - crucially set to `False` so that the examples are not - shuffled out of order with respect to labels that might - be used for assessment. - - Returns - ------- - torch.utils.data.DataLoader - - """ - if hasattr(dataset, "collate_fn"): - collate_fn = dataset.collate_fn - else: - collate_fn = None - dataloader = torch.utils.data.DataLoader( - dataset, - batch_size=self.batch_size, - shuffle=shuffle, - pin_memory=True, - collate_fn=collate_fn) - return dataloader - - def _update_no_improvement_count_early_stopping(self, *dev): - """ - Internal method used by `fit` to control early stopping. - The method uses `self.score(*dev)` for scoring and updates - `self.validation_scores`, `self.no_improvement_count`, - `self.best_score`, `self.best_parameters` as appropriate. - - """ - score = self.score(*dev) - self.validation_scores.append(score) - # If the score isn't at least `self.tol` better, increment: - if score < (self.best_score + self.tol): - self.no_improvement_count += 1 - else: - self.no_improvement_count = 0 - # If the current score is numerically better than all previous - # scores, update the best parameters: - if score > self.best_score: - self.best_parameters = copy.deepcopy(self.model.state_dict()) - self.best_score = score - self.model.train() - - def _update_no_improvement_count_errors(self, epoch_error): - """ - Internal method used by `fit` to control convergence. - The method uses `epoch_error`, `self.best_error`, and - `self.tol` to make decisions, and it updates `self.errors`, - `self.no_improvement_count`, and `self.best_error` as - appropriate. - - """ - if epoch_error > (self.best_error - self.tol): - self.no_improvement_count += 1 - else: - self.no_improvement_count = 0 - if epoch_error < self.best_error: - self.best_error = epoch_error - self.errors.append(epoch_error) - - def _predict(self, *args, device=None): - """ - Internal method that subclasses are expected to use to define - their own `predict` functions. The hope is that this method - can do all the data organization and other details, allowing - subclasses to have compact predict methods that just encode - the core logic specific to them. - - Parameters - ---------- - *args: system inputs - - device: str or None - Allows the user to temporarily change the device used - during prediction. This is useful if predictions require a - lot of memory and so are better done on the CPU. After - prediction is done, the model is returned to `self.device`. - - Returns - ------- - The precise return value depends on the nature of the predictions. - If the predictions have the same shape across all batches, then - we return a single tensor concatenation of them. If the shape - can vary across batches, as is common for sequence prediction, - then we return a list of tensors of varying length. - - """ - device = self.device if device is None else torch.device(device) - - # Dataset: - dataset = self.build_dataset(*args) - dataloader = self._build_dataloader(dataset, shuffle=False) - - # Model: - self.model.to(device) - self.model.eval() - - preds = [] - with torch.no_grad(): - for batch in dataloader: - X = [x.to(device, non_blocking=True) for x in batch] - preds.append(self.model(*X)) - - # Make sure the model is back on the instance device: - #self.model.to(self.device) - - # If the batch outputs differ only in their batch size, sharing - # all other dimensions, then we can concatenate them and maintain - # a tensor. For simple classification problems, this should hold. - if all(x.shape[1: ] == preds[0].shape[1: ] for x in preds[1: ]): - return torch.cat(preds, axis=0) - # The batch outputs might differ along other dimensions. This is - # common for sequence prediction, where different batches might - # have different max lengths, since we pad on a per-batch basis. - # In this case, we can't concatenate them, so we return a list - # of the predictions, where each prediction is a tensor. Note: - # the predictions might still be padded and so need trimming on a - # per example basis. - else: - return [p for batch in preds for p in batch] - - def get_params(self, deep=True): - params = self.params.copy() - # Obligatorily add `vocab` so that sklearn passes it in when - # creating new model instances during cross-validation: - if hasattr(self, 'vocab'): - params += ['vocab'] - return {p: getattr(self, p) for p in params} - - def set_params(self, **params): - for key, val in params.items(): - if key not in self.params: - raise ValueError( - "{} is not a parameter for {}. For the list of " - "available parameters, use `self.params`.".format( - key, self.__class__.__name__)) - else: - setattr(self, key, val) - return self - - def to_pickle(self, output_filename): - """ - Serialize the entire class instance. Importantly, this is - different from using the standard `torch.save` method: - - torch.save(self.model.state_dict(), output_filename) - - The above stores only the underlying model parameters. In - contrast, the current method ensures that all of the model - parameters are on the CPU and then stores the full instance. - This is necessary to ensure that we retain all the information - needed to read new examples, do additional training, make - predictions, and so forth. - - Parameters - ---------- - output_filename : str - Full path for the output file. - - """ - self.model = self.model.cpu() - with open(output_filename, 'wb') as f: - pickle.dump(self, f) - - @staticmethod - def from_pickle(src_filename): - """ - Load an entire class instance onto the CPU. This also sets - `self.warm_start=True` so that the loaded parameters are used - if `fit` is called. - - Importantly, this is different from recommended PyTorch method: - - self.model.load_state_dict(torch.load(src_filename)) - - We cannot reliably do this with new instances, because we need - to see new examples in order to set some of the model - dimensionalities and obtain information about what the class - labels are. Thus, the current method loads an entire serialized - class as created by `to_pickle`. - - The training and prediction code move the model parameters to - `self.device`. - - Parameters - ---------- - src_filename : str - Full path to the serialized model file. - - """ - with open(src_filename, 'rb') as f: - return pickle.load(f) - - def __repr__(self): - param_str = ["{}={}".format(a, getattr(self, a)) for a in self.params] - param_str = ",\n\t".join(param_str) - return "{}(\n\t{})".format(self.__class__.__name__, param_str) - - -# In[80]: - - -class TorchShallowNeuralClassifier(TorchModelBase): - def __init__(self, - hidden_dim=50, - hidden_activation=nn.Tanh(), - **base_kwargs): - """ - A model - - h = f(xW_xh + b_h) - y = softmax(hW_hy + b_y) - - with a cross-entropy loss and f determined by `hidden_activation`. - - Parameters - ---------- - hidden_dim : int - Dimensionality of the hidden layer. - - hidden_activation : nn.Module - The non-activation function used by the network for the - hidden layer. - - **base_kwargs - For details, see `torch_model_base.py`. - - Attributes - ---------- - loss: nn.CrossEntropyLoss(reduction="mean") - - self.params: list - Extends TorchModelBase.params with names for all of the - arguments for this class to support tuning of these values - using `sklearn.model_selection` tools. - - """ - self.hidden_dim = hidden_dim - self.hidden_activation = hidden_activation - super().__init__(**base_kwargs) - self.loss = nn.CrossEntropyLoss(reduction="mean") - self.params += ['hidden_dim', 'hidden_activation'] - - def build_graph(self): - """ - Define the model's computation graph. - - Returns - ------- - nn.Module - - """ - return nn.Sequential( - nn.Linear(self.input_dim, self.hidden_dim), - self.hidden_activation, - nn.Linear(self.hidden_dim, self.n_classes_)) - - def build_dataset(self, X, y=None): - """ - Define datasets for the model. - - Parameters - ---------- - X : iterable of length `n_examples` - Each element must have the same length. - - y: None or iterable of length `n_examples` - - Attributes - ---------- - input_dim : int - Set based on `X.shape[1]` after `X` has been converted to - `np.array`. - - Returns - ------- - torch.utils.data.TensorDataset` Where `y=None`, the dataset will - yield single tensors `X`. Where `y` is specified, it will yield - `(X, y)` pairs. - - """ - X = np.array(X) - self.input_dim = X.shape[1] - X = torch.FloatTensor(X) - if y is None: - dataset = torch.utils.data.TensorDataset(X) - else: - self.classes_ = sorted(set(y)) - self.n_classes_ = len(self.classes_) - class2index = dict(zip(self.classes_, range(self.n_classes_))) - y = [class2index[label] for label in y] - y = torch.tensor(y) - dataset = torch.utils.data.TensorDataset(X, y) - return dataset - - def score(self, X, y, device=None): - """ - Uses macro-F1 as the score function. Note: this departs from - `sklearn`, where classifiers use accuracy as their scoring - function. Using macro-F1 is more consistent with our course. - - This function can be used to evaluate models, but its primary - use is in cross-validation and hyperparameter tuning. - - Parameters - ---------- - X: np.array, shape `(n_examples, n_features)` - - y: iterable, shape `len(n_examples)` - These can be the raw labels. They will converted internally - as needed. See `build_dataset`. - - device: str or None - Allows the user to temporarily change the device used - during prediction. This is useful if predictions require a - lot of memory and so are better done on the CPU. After - prediction is done, the model is returned to `self.device`. - - Returns - ------- - float - - """ - preds = self.predict(X, device=device) - return utils.safe_macro_f1(y, preds) - - def predict_proba(self, X, device=None): - """ - Predicted probabilities for the examples in `X`. - - Parameters - ---------- - X : np.array, shape `(n_examples, n_features)` - - device: str or None - Allows the user to temporarily change the device used - during prediction. This is useful if predictions require a - lot of memory and so are better done on the CPU. After - prediction is done, the model is returned to `self.device`. - - Returns - ------- - np.array, shape `(len(X), self.n_classes_)` - Each row of this matrix will sum to 1.0. - - """ - #print(device) - preds = self._predict(X, device=device) - probs = torch.softmax(preds, dim=1).cpu().numpy() - return probs - - def predict(self, X, device="cpu"): - """ - Predicted labels for the examples in `X`. These are converted - from the integers that PyTorch needs back to their original - values in `self.classes_`. - - Parameters - ---------- - X : np.array, shape `(n_examples, n_features)` - - device: str or None - Allows the user to temporarily change the device used - during prediction. This is useful if predictions require a - lot of memory and so are better done on the CPU. After - prediction is done, the model is returned to `self.device`. - - Returns - ------- - list, length len(X) - - """ - #print(device) - probs = self.predict_proba(X, device=device) - #return [{self.classes_[i.argmax(axis=1):] for i in probs] - return [{self.classes_[i]:j} for i,j in zip(probs.argmax(axis=1),probs.max(axis=1))] - - -# In[81]: - - -class HfBertClassifierModel1(nn.Module): - def __init__(self, n_classes, weights_name='bert-base-cased',hidden_dim=64): - super().__init__() - self.n_classes = n_classes - self.weights_name = weights_name - self.hidden_dim = hidden_dim - self.bert = BertModel.from_pretrained(self.weights_name) - self.bert.train() - self.input_dim = self.bert.embeddings.word_embeddings.embedding_dim - # The only new parameters -- the classifier: - self.classifier_layer = nn.Sequential( - nn.Linear(self.input_dim, self.hidden_dim), - nn.ReLU(), - nn.Dropout(0.1), - nn.Linear(self.hidden_dim, self.n_classes)) - - def forward(self, indices, mask): - reps = self.bert( - indices, attention_mask=mask) - return self.classifier_layer(reps.pooler_output) - - -# In[82]: - - -class HfBertClassifier_all(TorchShallowNeuralClassifier): - def __init__(self, weights_name, *args, **kwargs): - self.weights_name = weights_name - self.tokenizer = BertTokenizer.from_pretrained(self.weights_name) - #self.hidden_dim=kwargs['hidden_dim'] - super().__init__(*args, **kwargs) - self.params += ['weights_name'] - - - def build_graph(self): - return HfBertClassifierModel1(self.n_classes_, self.weights_name) - - def build_dataset(self, X, y=None): - data = self.tokenizer.batch_encode_plus( - X, - max_length=512, - add_special_tokens=True, - padding='longest', - truncation=True, - return_attention_mask=True) - indices = torch.tensor(data['input_ids']) - mask = torch.tensor(data['attention_mask']) - if y is None: - dataset = torch.utils.data.TensorDataset(indices, mask) - else: - self.classes_ = sorted(set(y)) - self.n_classes_ = len(self.classes_) - class2index = dict(zip(self.classes_, range(self.n_classes_))) - y = [class2index[label] for label in y] - y = torch.tensor(y) - dataset = torch.utils.data.TensorDataset(indices, mask, y) - return dataset - - -# In[83]: - - -def bert_fine_tune_phi(text): - return text - - -# In[85]: - - -model_try=HfBertClassifier_all.from_pickle("bert_model_deploy_1.pt") - - -# In[112]: - - -#model_try.predict(["The 1st half was bad and the 2nd half was good","Wow what an amazing movie"]) - - -# In[93]: - - -tokenizer = TreebankWordTokenizer() -def treebank_tokenize_detokenize(s): - return ' '.join(tokenizer.tokenize(s)) - - -# In[110]: - - -def predict_1(text): - text_tokenized=treebank_tokenize_detokenize(text) - return model_try.predict([text_tokenized])[0] - -import gradio as gr - - -iface = gr.Interface(fn=predict_1, inputs="text", outputs="text") -iface.launch() - - -# In[114]: - - -#predict_1("The 1st half was good but the 2nd half was bad") - - -# In[ ]: - - - - diff --git a/spaces/antonovmaxim/text-generation-webui-space/docs/Extensions.md b/spaces/antonovmaxim/text-generation-webui-space/docs/Extensions.md deleted file mode 100644 index 0e396ce2c350242abf45056f869e27c3e3381de7..0000000000000000000000000000000000000000 --- a/spaces/antonovmaxim/text-generation-webui-space/docs/Extensions.md +++ /dev/null @@ -1,220 +0,0 @@ -Extensions are defined by files named `script.py` inside subfolders of `text-generation-webui/extensions`. They are loaded at startup if specified with the `--extensions` flag. - -For instance, `extensions/silero_tts/script.py` gets loaded with `python server.py --extensions silero_tts`. - -## [text-generation-webui-extensions](https://github.com/oobabooga/text-generation-webui-extensions) - -The link above contains a directory of user extensions for text-generation-webui. - -If you create an extension, you are welcome to host it in a GitHub repository and submit it to the list above. - -## Built-in extensions - -Most of these have been created by the extremely talented contributors that you can find here: [contributors](https://github.com/oobabooga/text-generation-webui/graphs/contributors?from=2022-12-18&to=&type=a). - -|Extension|Description| -|---------|-----------| -|[api](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/api)| Creates an API with two endpoints, one for streaming at `/api/v1/stream` port 5005 and another for blocking at `/api/v1/generate` port 5000. This is the main API for this web UI. | -|[google_translate](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/google_translate)| Automatically translates inputs and outputs using Google Translate.| -|[character_bias](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/character_bias)| Just a very simple example that biases the bot's responses in chat mode.| -|[gallery](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/gallery/)| Creates a gallery with the chat characters and their pictures. | -|[silero_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/silero_tts)| Text-to-speech extension using [Silero](https://github.com/snakers4/silero-models). When used in chat mode, it replaces the responses with an audio widget. | -|[elevenlabs_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/elevenlabs_tts)| Text-to-speech extension using the [ElevenLabs](https://beta.elevenlabs.io/) API. You need an API key to use it. | -|[send_pictures](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/send_pictures/)| Creates an image upload field that can be used to send images to the bot in chat mode. Captions are automatically generated using BLIP. | -|[whisper_stt](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/whisper_stt)| Allows you to enter your inputs in chat mode using your microphone. | -|[sd_api_pictures](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/sd_api_pictures)| Allows you to request pictures from the bot in chat mode, which will be generated using the AUTOMATIC1111 Stable Diffusion API. See examples [here](https://github.com/oobabooga/text-generation-webui/pull/309). | -|[multimodal](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal) | Adds multimodality support (text+images). For a detailed description see [README.md](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal/README.md) in the extension directory. | -|[openai](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai)| Creates an API that mimics the OpenAI API and can be used as a drop-in replacement. | -|[superbooga](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/superbooga)| An extension that uses ChromaDB to create an arbitrarily large pseudocontext, taking as input text files, URLs, or pasted text. Based on https://github.com/kaiokendev/superbig. | - -## How to write an extension - -script.py may define the special functions and variables below. - -#### Predefined functions - -| Function | Description | -|-------------|-------------| -| `def ui()` | Creates custom gradio elements when the UI is launched. | -| `def custom_css()` | Returns custom CSS as a string. It is applied whenever the web UI is loaded. | -| `def custom_js()` | Same as above but for javascript. | -| `def input_modifier(string)` | Modifies the input string before it enters the model. In chat mode, it is applied to the user message. Otherwise, it is applied to the entire prompt. | -| `def output_modifier(string)` | Modifies the output string before it is presented in the UI. In chat mode, it is applied to the bot's reply. Otherwise, it is applied to the entire output. | -| `def state_modifier(state)` | Modifies the dictionary containing the UI input parameters before it is used by the text generation functions. | -| `def bot_prefix_modifier(string)` | Applied in chat mode to the prefix for the bot's reply. | -| `def custom_generate_reply(...)` | Overrides the main text generation function. | -| `def custom_generate_chat_prompt(...)` | Overrides the prompt generator in chat mode. | -| `def tokenizer_modifier(state, prompt, input_ids, input_embeds)` | Modifies the `input_ids`/`input_embeds` fed to the model. Should return `prompt`, `input_ids`, `input_embeds`. See the `multimodal` extension for an example. | -| `def custom_tokenized_length(prompt)` | Used in conjunction with `tokenizer_modifier`, returns the length in tokens of `prompt`. See the `multimodal` extension for an example. | - -#### `params` dictionary - -In this dictionary, `display_name` is used to define the displayed name of the extension in the UI, and `is_tab` is used to define whether the extension should appear in a new tab. By default, extensions appear at the bottom of the "Text generation" tab. - -Example: - -```python -params = { - "display_name": "Google Translate", - "is_tab": True, -} -``` - -Additionally, `params` may contain variables that you want to be customizable through a `settings.json` file. For instance, assuming the extension is in `extensions/google_translate`, the variable `language string` in - -```python -params = { - "display_name": "Google Translate", - "is_tab": True, - "language string": "jp" -} -``` - -can be customized by adding a key called `google_translate-language string` to `settings.json`: - -```python -"google_translate-language string": "fr", -``` - -That is, the syntax is `extension_name-variable_name`. - -#### `input_hijack` dictionary - -```python -input_hijack = { - 'state': False, - 'value': ["", ""] -} -``` -This is only used in chat mode. If your extension sets `input_hijack['state'] = True` at any moment, the next call to `modules.chat.chatbot_wrapper` will use the values inside `input_hijack['value']` as the user input for text generation. See the `send_pictures` extension above for an example. - -Additionally, your extension can set the value to be a callback in the form of `def cb(text: str, visible_text: str) -> [str, str]`. See the `multimodal` extension above for an example. - -## Using multiple extensions at the same time - -In order to use your extension, you must start the web UI with the `--extensions` flag followed by the name of your extension (the folder under `text-generation-webui/extension` where `script.py` resides). - -You can activate more than one extension at a time by providing their names separated by spaces. The input, output, and bot prefix modifiers will be applied in the specified order. - - -``` -python server.py --extensions enthusiasm translate # First apply enthusiasm, then translate -python server.py --extensions translate enthusiasm # First apply translate, then enthusiasm -``` - -Do note, that for: -- `custom_generate_chat_prompt` -- `custom_generate_reply` -- `tokenizer_modifier` -- `custom_tokenized_length` - -only the first declaration encountered will be used and the rest will be ignored. - -## The `bot_prefix_modifier` - -In chat mode, this function modifies the prefix for a new bot message. For instance, if your bot is named `Marie Antoinette`, the default prefix for a new message will be - -``` -Marie Antoinette: -``` - -Using `bot_prefix_modifier`, you can change it to: - -``` -Marie Antoinette: *I am very enthusiastic* -``` - -Marie Antoinette will become very enthusiastic in all her messages. - -## `custom_generate_reply` example - -Once defined in a `script.py`, this function is executed in place of the main generation functions. You can use it to connect the web UI to an external API, or to load a custom model that is not supported yet. - -Note that in chat mode, this function must only return the new text, whereas in other modes it must return the original prompt + the new text. - -```python -import datetime - -def custom_generate_reply(question, original_question, seed, state, eos_token, stopping_strings): - cumulative = '' - for i in range(10): - cumulative += f"Counting: {i}...\n" - yield cumulative - - cumulative += f"Done! {str(datetime.datetime.now())}" - yield cumulative -``` - -## `custom_generate_chat_prompt` example - -Below is an extension that just reproduces the default prompt generator in `modules/chat.py`. You can modify it freely to come up with your own prompts in chat mode. - -```python -def custom_generate_chat_prompt(user_input, state, **kwargs): - impersonate = kwargs['impersonate'] if 'impersonate' in kwargs else False - _continue = kwargs['_continue'] if '_continue' in kwargs else False - also_return_rows = kwargs['also_return_rows'] if 'also_return_rows' in kwargs else False - is_instruct = state['mode'] == 'instruct' - rows = [state['context'] if is_instruct else f"{state['context'].strip()}\n"] - min_rows = 3 - - # Finding the maximum prompt size - chat_prompt_size = state['chat_prompt_size'] - if shared.soft_prompt: - chat_prompt_size -= shared.soft_prompt_tensor.shape[1] - - max_length = min(get_max_prompt_length(state), chat_prompt_size) - - # Building the turn templates - if 'turn_template' not in state or state['turn_template'] == '': - if is_instruct: - template = '<|user|>\n<|user-message|>\n<|bot|>\n<|bot-message|>\n' - else: - template = '<|user|>: <|user-message|>\n<|bot|>: <|bot-message|>\n' - else: - template = state['turn_template'].replace(r'\n', '\n') - - replacements = { - '<|user|>': state['name1'].strip(), - '<|bot|>': state['name2'].strip(), - } - - user_turn = replace_all(template.split('<|bot|>')[0], replacements) - bot_turn = replace_all('<|bot|>' + template.split('<|bot|>')[1], replacements) - user_turn_stripped = replace_all(user_turn.split('<|user-message|>')[0], replacements) - bot_turn_stripped = replace_all(bot_turn.split('<|bot-message|>')[0], replacements) - - # Building the prompt - i = len(shared.history['internal']) - 1 - while i >= 0 and get_encoded_length(''.join(rows)) < max_length: - if _continue and i == len(shared.history['internal']) - 1: - rows.insert(1, bot_turn_stripped + shared.history['internal'][i][1].strip()) - else: - rows.insert(1, bot_turn.replace('<|bot-message|>', shared.history['internal'][i][1].strip())) - - string = shared.history['internal'][i][0] - if string not in ['', '<|BEGIN-VISIBLE-CHAT|>']: - rows.insert(1, replace_all(user_turn, {'<|user-message|>': string.strip(), '<|round|>': str(i)})) - - i -= 1 - - if impersonate: - min_rows = 2 - rows.append(user_turn_stripped.rstrip(' ')) - elif not _continue: - # Adding the user message - if len(user_input) > 0: - rows.append(replace_all(user_turn, {'<|user-message|>': user_input.strip(), '<|round|>': str(len(shared.history["internal"]))})) - - # Adding the Character prefix - rows.append(apply_extensions("bot_prefix", bot_turn_stripped.rstrip(' '))) - - while len(rows) > min_rows and get_encoded_length(''.join(rows)) >= max_length: - rows.pop(1) - - prompt = ''.join(rows) - if also_return_rows: - return prompt, rows - else: - return prompt -``` diff --git a/spaces/apokalis/Apokalis/Dockerfile b/spaces/apokalis/Apokalis/Dockerfile deleted file mode 100644 index 3a4dc66fdb50519fca2a6eaf64cbe0ea05b09a3f..0000000000000000000000000000000000000000 --- a/spaces/apokalis/Apokalis/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/artificialguybr/video-dubbing/TTS/docs/source/index.md b/spaces/artificialguybr/video-dubbing/TTS/docs/source/index.md deleted file mode 100644 index 79993eec76dd72d743e2236a0df4601fd37d9809..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/video-dubbing/TTS/docs/source/index.md +++ /dev/null @@ -1,62 +0,0 @@ - -```{include} ../../README.md -:relative-images: -``` ----- - -# Documentation Content -```{eval-rst} -.. toctree:: - :maxdepth: 2 - :caption: Get started - - tutorial_for_nervous_beginners - installation - faq - contributing - -.. toctree:: - :maxdepth: 2 - :caption: Using 🐸TTS - - inference - docker_images - implementing_a_new_model - implementing_a_new_language_frontend - training_a_model - finetuning - configuration - formatting_your_dataset - what_makes_a_good_dataset - tts_datasets - marytts - -.. toctree:: - :maxdepth: 2 - :caption: Main Classes - - main_classes/trainer_api - main_classes/audio_processor - main_classes/model_api - main_classes/dataset - main_classes/gan - main_classes/speaker_manager - -.. toctree:: - :maxdepth: 2 - :caption: `tts` Models - - models/glow_tts.md - models/vits.md - models/forward_tts.md - models/tacotron1-2.md - models/overflow.md - models/tortoise.md - models/bark.md - models/xtts.md - -.. toctree:: - :maxdepth: 2 - :caption: `vocoder` Models - -``` diff --git a/spaces/artificialguybr/video-dubbing/TTS/tests/tts_tests2/test_forward_tts.py b/spaces/artificialguybr/video-dubbing/TTS/tests/tts_tests2/test_forward_tts.py deleted file mode 100644 index cec0f211c85c70b17f289e37368638911b911742..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/video-dubbing/TTS/tests/tts_tests2/test_forward_tts.py +++ /dev/null @@ -1,147 +0,0 @@ -import torch as T - -from TTS.tts.models.forward_tts import ForwardTTS, ForwardTTSArgs -from TTS.tts.utils.helpers import sequence_mask - -# pylint: disable=unused-variable - - -def expand_encoder_outputs_test(): - model = ForwardTTS(ForwardTTSArgs(num_chars=10)) - - inputs = T.rand(2, 5, 57) - durations = T.randint(1, 4, (2, 57)) - - x_mask = T.ones(2, 1, 57) - y_mask = T.ones(2, 1, durations.sum(1).max()) - - expanded, _ = model.expand_encoder_outputs(inputs, durations, x_mask, y_mask) - - for b in range(durations.shape[0]): - index = 0 - for idx, dur in enumerate(durations[b]): - diff = ( - expanded[b, :, index : index + dur.item()] - - inputs[b, :, idx].repeat(dur.item()).view(expanded[b, :, index : index + dur.item()].shape) - ).sum() - assert abs(diff) < 1e-6, diff - index += dur - - -def model_input_output_test(): - """Assert the output shapes of the model in different modes""" - - # VANILLA MODEL - model = ForwardTTS(ForwardTTSArgs(num_chars=10, use_pitch=False, use_aligner=False)) - - x = T.randint(0, 10, (2, 21)) - x_lengths = T.randint(10, 22, (2,)) - x_lengths[-1] = 21 - x_mask = sequence_mask(x_lengths).unsqueeze(1).long() - durations = T.randint(1, 4, (2, 21)) - durations = durations * x_mask.squeeze(1) - y_lengths = durations.sum(1) - y_mask = sequence_mask(y_lengths).unsqueeze(1).long() - - outputs = model.forward(x, x_lengths, y_lengths, dr=durations) - - assert outputs["model_outputs"].shape == (2, durations.sum(1).max(), 80) - assert outputs["durations_log"].shape == (2, 21) - assert outputs["durations"].shape == (2, 21) - assert outputs["alignments"].shape == (2, durations.sum(1).max(), 21) - assert (outputs["x_mask"] - x_mask).sum() == 0.0 - assert (outputs["y_mask"] - y_mask).sum() == 0.0 - - assert outputs["alignment_soft"] is None - assert outputs["alignment_mas"] is None - assert outputs["alignment_logprob"] is None - assert outputs["o_alignment_dur"] is None - assert outputs["pitch_avg"] is None - assert outputs["pitch_avg_gt"] is None - - # USE PITCH - model = ForwardTTS(ForwardTTSArgs(num_chars=10, use_pitch=True, use_aligner=False)) - - x = T.randint(0, 10, (2, 21)) - x_lengths = T.randint(10, 22, (2,)) - x_lengths[-1] = 21 - x_mask = sequence_mask(x_lengths).unsqueeze(1).long() - durations = T.randint(1, 4, (2, 21)) - durations = durations * x_mask.squeeze(1) - y_lengths = durations.sum(1) - y_mask = sequence_mask(y_lengths).unsqueeze(1).long() - pitch = T.rand(2, 1, y_lengths.max()) - - outputs = model.forward(x, x_lengths, y_lengths, dr=durations, pitch=pitch) - - assert outputs["model_outputs"].shape == (2, durations.sum(1).max(), 80) - assert outputs["durations_log"].shape == (2, 21) - assert outputs["durations"].shape == (2, 21) - assert outputs["alignments"].shape == (2, durations.sum(1).max(), 21) - assert (outputs["x_mask"] - x_mask).sum() == 0.0 - assert (outputs["y_mask"] - y_mask).sum() == 0.0 - assert outputs["pitch_avg"].shape == (2, 1, 21) - assert outputs["pitch_avg_gt"].shape == (2, 1, 21) - - assert outputs["alignment_soft"] is None - assert outputs["alignment_mas"] is None - assert outputs["alignment_logprob"] is None - assert outputs["o_alignment_dur"] is None - - # USE ALIGNER NETWORK - model = ForwardTTS(ForwardTTSArgs(num_chars=10, use_pitch=False, use_aligner=True)) - - x = T.randint(0, 10, (2, 21)) - x_lengths = T.randint(10, 22, (2,)) - x_lengths[-1] = 21 - x_mask = sequence_mask(x_lengths).unsqueeze(1).long() - durations = T.randint(1, 4, (2, 21)) - durations = durations * x_mask.squeeze(1) - y_lengths = durations.sum(1) - y_mask = sequence_mask(y_lengths).unsqueeze(1).long() - y = T.rand(2, y_lengths.max(), 80) - - outputs = model.forward(x, x_lengths, y_lengths, dr=durations, y=y) - - assert outputs["model_outputs"].shape == (2, durations.sum(1).max(), 80) - assert outputs["durations_log"].shape == (2, 21) - assert outputs["durations"].shape == (2, 21) - assert outputs["alignments"].shape == (2, durations.sum(1).max(), 21) - assert (outputs["x_mask"] - x_mask).sum() == 0.0 - assert (outputs["y_mask"] - y_mask).sum() == 0.0 - assert outputs["alignment_soft"].shape == (2, durations.sum(1).max(), 21) - assert outputs["alignment_mas"].shape == (2, durations.sum(1).max(), 21) - assert outputs["alignment_logprob"].shape == (2, 1, durations.sum(1).max(), 21) - assert outputs["o_alignment_dur"].shape == (2, 21) - - assert outputs["pitch_avg"] is None - assert outputs["pitch_avg_gt"] is None - - # USE ALIGNER NETWORK AND PITCH - model = ForwardTTS(ForwardTTSArgs(num_chars=10, use_pitch=True, use_aligner=True)) - - x = T.randint(0, 10, (2, 21)) - x_lengths = T.randint(10, 22, (2,)) - x_lengths[-1] = 21 - x_mask = sequence_mask(x_lengths).unsqueeze(1).long() - durations = T.randint(1, 4, (2, 21)) - durations = durations * x_mask.squeeze(1) - y_lengths = durations.sum(1) - y_mask = sequence_mask(y_lengths).unsqueeze(1).long() - y = T.rand(2, y_lengths.max(), 80) - pitch = T.rand(2, 1, y_lengths.max()) - - outputs = model.forward(x, x_lengths, y_lengths, dr=durations, pitch=pitch, y=y) - - assert outputs["model_outputs"].shape == (2, durations.sum(1).max(), 80) - assert outputs["durations_log"].shape == (2, 21) - assert outputs["durations"].shape == (2, 21) - assert outputs["alignments"].shape == (2, durations.sum(1).max(), 21) - assert (outputs["x_mask"] - x_mask).sum() == 0.0 - assert (outputs["y_mask"] - y_mask).sum() == 0.0 - assert outputs["alignment_soft"].shape == (2, durations.sum(1).max(), 21) - assert outputs["alignment_mas"].shape == (2, durations.sum(1).max(), 21) - assert outputs["alignment_logprob"].shape == (2, 1, durations.sum(1).max(), 21) - assert outputs["o_alignment_dur"].shape == (2, 21) - assert outputs["pitch_avg"].shape == (2, 1, 21) - assert outputs["pitch_avg_gt"].shape == (2, 1, 21) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/__init__.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/__init__.py deleted file mode 100644 index 7af91cb76b78db8cedeb7967ba49c8244deb1290..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -__all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util', 'Signature', - 'IO', 'Math'] - -version_info = (3, 16, '0') - -__version__ = ".".join([str(x) for x in version_info]) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/absl/logging/__init__.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/absl/logging/__init__.py deleted file mode 100644 index f4e79675bca86e0444f13459d7c0ddcc4b232c06..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/absl/logging/__init__.py +++ /dev/null @@ -1,1245 +0,0 @@ -# Copyright 2017 The Abseil Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Abseil Python logging module implemented on top of standard logging. - -Simple usage:: - - from absl import logging - - logging.info('Interesting Stuff') - logging.info('Interesting Stuff with Arguments: %d', 42) - - logging.set_verbosity(logging.INFO) - logging.log(logging.DEBUG, 'This will *not* be printed') - logging.set_verbosity(logging.DEBUG) - logging.log(logging.DEBUG, 'This will be printed') - - logging.warning('Worrying Stuff') - logging.error('Alarming Stuff') - logging.fatal('AAAAHHHHH!!!!') # Process exits. - -Usage note: Do not pre-format the strings in your program code. -Instead, let the logging module perform argument interpolation. -This saves cycles because strings that don't need to be printed -are never formatted. Note that this module does not attempt to -interpolate arguments when no arguments are given. In other words:: - - logging.info('Interesting Stuff: %s') - -does not raise an exception because logging.info() has only one -argument, the message string. - -"Lazy" evaluation for debugging -------------------------------- - -If you do something like this:: - - logging.debug('Thing: %s', thing.ExpensiveOp()) - -then the ExpensiveOp will be evaluated even if nothing -is printed to the log. To avoid this, use the level_debug() function:: - - if logging.level_debug(): - logging.debug('Thing: %s', thing.ExpensiveOp()) - -Per file level logging is supported by logging.vlog() and -logging.vlog_is_on(). For example:: - - if logging.vlog_is_on(2): - logging.vlog(2, very_expensive_debug_message()) - -Notes on Unicode ----------------- - -The log output is encoded as UTF-8. Don't pass data in other encodings in -bytes() instances -- instead pass unicode string instances when you need to -(for both the format string and arguments). - -Note on critical and fatal: -Standard logging module defines fatal as an alias to critical, but it's not -documented, and it does NOT actually terminate the program. -This module only defines fatal but not critical, and it DOES terminate the -program. - -The differences in behavior are historical and unfortunate. -""" - -import collections -from collections import abc -import getpass -import io -import itertools -import logging -import os -import socket -import struct -import sys -import tempfile -import threading -import tempfile -import time -import timeit -import traceback -import types -import warnings - -from absl import flags -from absl.logging import converter - -try: - from typing import NoReturn -except ImportError: - pass - - -FLAGS = flags.FLAGS - - -# Logging levels. -FATAL = converter.ABSL_FATAL -ERROR = converter.ABSL_ERROR -WARNING = converter.ABSL_WARNING -WARN = converter.ABSL_WARNING # Deprecated name. -INFO = converter.ABSL_INFO -DEBUG = converter.ABSL_DEBUG - -# Regex to match/parse log line prefixes. -ABSL_LOGGING_PREFIX_REGEX = ( - r'^(?P[IWEF])' - r'(?P\d\d)(?P\d\d) ' - r'(?P\d\d):(?P\d\d):(?P\d\d)' - r'\.(?P\d\d\d\d\d\d) +' - r'(?P-?\d+) ' - r'(?P[a-zA-Z<][\w._<>-]+):(?P\d+)') - - -# Mask to convert integer thread ids to unsigned quantities for logging purposes -_THREAD_ID_MASK = 2 ** (struct.calcsize('L') * 8) - 1 - -# Extra property set on the LogRecord created by ABSLLogger when its level is -# CRITICAL/FATAL. -_ABSL_LOG_FATAL = '_absl_log_fatal' -# Extra prefix added to the log message when a non-absl logger logs a -# CRITICAL/FATAL message. -_CRITICAL_PREFIX = 'CRITICAL - ' - -# Used by findCaller to skip callers from */logging/__init__.py. -_LOGGING_FILE_PREFIX = os.path.join('logging', '__init__.') - -# The ABSL logger instance, initialized in _initialize(). -_absl_logger = None -# The ABSL handler instance, initialized in _initialize(). -_absl_handler = None - - -_CPP_NAME_TO_LEVELS = { - 'debug': '0', # Abseil C++ has no DEBUG level, mapping it to INFO here. - 'info': '0', - 'warning': '1', - 'warn': '1', - 'error': '2', - 'fatal': '3' -} - -_CPP_LEVEL_TO_NAMES = { - '0': 'info', - '1': 'warning', - '2': 'error', - '3': 'fatal', -} - - -class _VerbosityFlag(flags.Flag): - """Flag class for -v/--verbosity.""" - - def __init__(self, *args, **kwargs): - super(_VerbosityFlag, self).__init__( - flags.IntegerParser(), - flags.ArgumentSerializer(), - *args, **kwargs) - - @property - def value(self): - return self._value - - @value.setter - def value(self, v): - self._value = v - self._update_logging_levels() - - def _update_logging_levels(self): - """Updates absl logging levels to the current verbosity. - - Visibility: module-private - """ - if not _absl_logger: - return - - if self._value <= converter.ABSL_DEBUG: - standard_verbosity = converter.absl_to_standard(self._value) - else: - # --verbosity is set to higher than 1 for vlog. - standard_verbosity = logging.DEBUG - (self._value - 1) - - # Also update root level when absl_handler is used. - if _absl_handler in logging.root.handlers: - # Make absl logger inherit from the root logger. absl logger might have - # a non-NOTSET value if logging.set_verbosity() is called at import time. - _absl_logger.setLevel(logging.NOTSET) - logging.root.setLevel(standard_verbosity) - else: - _absl_logger.setLevel(standard_verbosity) - - -class _LoggerLevelsFlag(flags.Flag): - """Flag class for --logger_levels.""" - - def __init__(self, *args, **kwargs): - super(_LoggerLevelsFlag, self).__init__( - _LoggerLevelsParser(), - _LoggerLevelsSerializer(), - *args, **kwargs) - - @property - def value(self): - # For lack of an immutable type, be defensive and return a copy. - # Modifications to the dict aren't supported and won't have any affect. - # While Py3 could use MappingProxyType, that isn't deepcopy friendly, so - # just return a copy. - return self._value.copy() - - @value.setter - def value(self, v): - self._value = {} if v is None else v - self._update_logger_levels() - - def _update_logger_levels(self): - # Visibility: module-private. - # This is called by absl.app.run() during initialization. - for name, level in self._value.items(): - logging.getLogger(name).setLevel(level) - - -class _LoggerLevelsParser(flags.ArgumentParser): - """Parser for --logger_levels flag.""" - - def parse(self, value): - if isinstance(value, abc.Mapping): - return value - - pairs = [pair.strip() for pair in value.split(',') if pair.strip()] - - # Preserve the order so that serialization is deterministic. - levels = collections.OrderedDict() - for name_level in pairs: - name, level = name_level.split(':', 1) - name = name.strip() - level = level.strip() - levels[name] = level - return levels - - -class _LoggerLevelsSerializer(object): - """Serializer for --logger_levels flag.""" - - def serialize(self, value): - if isinstance(value, str): - return value - return ','.join( - '{}:{}'.format(name, level) for name, level in value.items()) - - -class _StderrthresholdFlag(flags.Flag): - """Flag class for --stderrthreshold.""" - - def __init__(self, *args, **kwargs): - super(_StderrthresholdFlag, self).__init__( - flags.ArgumentParser(), - flags.ArgumentSerializer(), - *args, **kwargs) - - @property - def value(self): - return self._value - - @value.setter - def value(self, v): - if v in _CPP_LEVEL_TO_NAMES: - # --stderrthreshold also accepts numeric strings whose values are - # Abseil C++ log levels. - cpp_value = int(v) - v = _CPP_LEVEL_TO_NAMES[v] # Normalize to strings. - elif v.lower() in _CPP_NAME_TO_LEVELS: - v = v.lower() - if v == 'warn': - v = 'warning' # Use 'warning' as the canonical name. - cpp_value = int(_CPP_NAME_TO_LEVELS[v]) - else: - raise ValueError( - '--stderrthreshold must be one of (case-insensitive) ' - "'debug', 'info', 'warning', 'error', 'fatal', " - "or '0', '1', '2', '3', not '%s'" % v) - - self._value = v - - -flags.DEFINE_boolean('logtostderr', - False, - 'Should only log to stderr?', allow_override_cpp=True) -flags.DEFINE_boolean('alsologtostderr', - False, - 'also log to stderr?', allow_override_cpp=True) -flags.DEFINE_string('log_dir', - os.getenv('TEST_TMPDIR', ''), - 'directory to write logfiles into', - allow_override_cpp=True) -flags.DEFINE_flag(_VerbosityFlag( - 'verbosity', -1, - 'Logging verbosity level. Messages logged at this level or lower will ' - 'be included. Set to 1 for debug logging. If the flag was not set or ' - 'supplied, the value will be changed from the default of -1 (warning) to ' - '0 (info) after flags are parsed.', - short_name='v', allow_hide_cpp=True)) -flags.DEFINE_flag( - _LoggerLevelsFlag( - 'logger_levels', {}, - 'Specify log level of loggers. The format is a CSV list of ' - '`name:level`. Where `name` is the logger name used with ' - '`logging.getLogger()`, and `level` is a level name (INFO, DEBUG, ' - 'etc). e.g. `myapp.foo:INFO,other.logger:DEBUG`')) -flags.DEFINE_flag(_StderrthresholdFlag( - 'stderrthreshold', 'fatal', - 'log messages at this level, or more severe, to stderr in ' - 'addition to the logfile. Possible values are ' - "'debug', 'info', 'warning', 'error', and 'fatal'. " - 'Obsoletes --alsologtostderr. Using --alsologtostderr ' - 'cancels the effect of this flag. Please also note that ' - 'this flag is subject to --verbosity and requires logfile ' - 'not be stderr.', allow_hide_cpp=True)) -flags.DEFINE_boolean('showprefixforinfo', True, - 'If False, do not prepend prefix to info messages ' - 'when it\'s logged to stderr, ' - '--verbosity is set to INFO level, ' - 'and python logging is used.') - - -def get_verbosity(): - """Returns the logging verbosity.""" - return FLAGS['verbosity'].value - - -def set_verbosity(v): - """Sets the logging verbosity. - - Causes all messages of level <= v to be logged, - and all messages of level > v to be silently discarded. - - Args: - v: int|str, the verbosity level as an integer or string. Legal string values - are those that can be coerced to an integer as well as case-insensitive - 'debug', 'info', 'warning', 'error', and 'fatal'. - """ - try: - new_level = int(v) - except ValueError: - new_level = converter.ABSL_NAMES[v.upper()] - FLAGS.verbosity = new_level - - -def set_stderrthreshold(s): - """Sets the stderr threshold to the value passed in. - - Args: - s: str|int, valid strings values are case-insensitive 'debug', - 'info', 'warning', 'error', and 'fatal'; valid integer values are - logging.DEBUG|INFO|WARNING|ERROR|FATAL. - - Raises: - ValueError: Raised when s is an invalid value. - """ - if s in converter.ABSL_LEVELS: - FLAGS.stderrthreshold = converter.ABSL_LEVELS[s] - elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES: - FLAGS.stderrthreshold = s - else: - raise ValueError( - 'set_stderrthreshold only accepts integer absl logging level ' - 'from -3 to 1, or case-insensitive string values ' - "'debug', 'info', 'warning', 'error', and 'fatal'. " - 'But found "{}" ({}).'.format(s, type(s))) - - -def fatal(msg, *args, **kwargs): - # type: (Any, Any, Any) -> NoReturn - """Logs a fatal message.""" - log(FATAL, msg, *args, **kwargs) - - -def error(msg, *args, **kwargs): - """Logs an error message.""" - log(ERROR, msg, *args, **kwargs) - - -def warning(msg, *args, **kwargs): - """Logs a warning message.""" - log(WARNING, msg, *args, **kwargs) - - -def warn(msg, *args, **kwargs): - """Deprecated, use 'warning' instead.""" - warnings.warn("The 'warn' function is deprecated, use 'warning' instead", - DeprecationWarning, 2) - log(WARNING, msg, *args, **kwargs) - - -def info(msg, *args, **kwargs): - """Logs an info message.""" - log(INFO, msg, *args, **kwargs) - - -def debug(msg, *args, **kwargs): - """Logs a debug message.""" - log(DEBUG, msg, *args, **kwargs) - - -def exception(msg, *args, **kwargs): - """Logs an exception, with traceback and message.""" - error(msg, *args, **kwargs, exc_info=True) - - -# Counter to keep track of number of log entries per token. -_log_counter_per_token = {} - - -def _get_next_log_count_per_token(token): - """Wrapper for _log_counter_per_token. Thread-safe. - - Args: - token: The token for which to look up the count. - - Returns: - The number of times this function has been called with - *token* as an argument (starting at 0). - """ - # Can't use a defaultdict because defaultdict isn't atomic, whereas - # setdefault is. - return next(_log_counter_per_token.setdefault(token, itertools.count())) - - -def log_every_n(level, msg, n, *args): - """Logs ``msg % args`` at level 'level' once per 'n' times. - - Logs the 1st call, (N+1)st call, (2N+1)st call, etc. - Not threadsafe. - - Args: - level: int, the absl logging level at which to log. - msg: str, the message to be logged. - n: int, the number of times this should be called before it is logged. - *args: The args to be substituted into the msg. - """ - count = _get_next_log_count_per_token(get_absl_logger().findCaller()) - log_if(level, msg, not (count % n), *args) - - -# Keeps track of the last log time of the given token. -# Note: must be a dict since set/get is atomic in CPython. -# Note: entries are never released as their number is expected to be low. -_log_timer_per_token = {} - - -def _seconds_have_elapsed(token, num_seconds): - """Tests if 'num_seconds' have passed since 'token' was requested. - - Not strictly thread-safe - may log with the wrong frequency if called - concurrently from multiple threads. Accuracy depends on resolution of - 'timeit.default_timer()'. - - Always returns True on the first call for a given 'token'. - - Args: - token: The token for which to look up the count. - num_seconds: The number of seconds to test for. - - Returns: - Whether it has been >= 'num_seconds' since 'token' was last requested. - """ - now = timeit.default_timer() - then = _log_timer_per_token.get(token, None) - if then is None or (now - then) >= num_seconds: - _log_timer_per_token[token] = now - return True - else: - return False - - -def log_every_n_seconds(level, msg, n_seconds, *args): - """Logs ``msg % args`` at level ``level`` iff ``n_seconds`` elapsed since last call. - - Logs the first call, logs subsequent calls if 'n' seconds have elapsed since - the last logging call from the same call site (file + line). Not thread-safe. - - Args: - level: int, the absl logging level at which to log. - msg: str, the message to be logged. - n_seconds: float or int, seconds which should elapse before logging again. - *args: The args to be substituted into the msg. - """ - should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds) - log_if(level, msg, should_log, *args) - - -def log_first_n(level, msg, n, *args): - """Logs ``msg % args`` at level ``level`` only first ``n`` times. - - Not threadsafe. - - Args: - level: int, the absl logging level at which to log. - msg: str, the message to be logged. - n: int, the maximal number of times the message is logged. - *args: The args to be substituted into the msg. - """ - count = _get_next_log_count_per_token(get_absl_logger().findCaller()) - log_if(level, msg, count < n, *args) - - -def log_if(level, msg, condition, *args): - """Logs ``msg % args`` at level ``level`` only if condition is fulfilled.""" - if condition: - log(level, msg, *args) - - -def log(level, msg, *args, **kwargs): - """Logs ``msg % args`` at absl logging level ``level``. - - If no args are given just print msg, ignoring any interpolation specifiers. - - Args: - level: int, the absl logging level at which to log the message - (logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging - level constants are also supported, callers should prefer explicit - logging.vlog() calls for such purpose. - - msg: str, the message to be logged. - *args: The args to be substituted into the msg. - **kwargs: May contain exc_info to add exception traceback to message. - """ - if level > converter.ABSL_DEBUG: - # Even though this function supports level that is greater than 1, users - # should use logging.vlog instead for such cases. - # Treat this as vlog, 1 is equivalent to DEBUG. - standard_level = converter.STANDARD_DEBUG - (level - 1) - else: - if level < converter.ABSL_FATAL: - level = converter.ABSL_FATAL - standard_level = converter.absl_to_standard(level) - - # Match standard logging's behavior. Before use_absl_handler() and - # logging is configured, there is no handler attached on _absl_logger nor - # logging.root. So logs go no where. - if not logging.root.handlers: - logging.basicConfig() - - _absl_logger.log(standard_level, msg, *args, **kwargs) - - -def vlog(level, msg, *args, **kwargs): - """Log ``msg % args`` at C++ vlog level ``level``. - - Args: - level: int, the C++ verbose logging level at which to log the message, - e.g. 1, 2, 3, 4... While absl level constants are also supported, - callers should prefer logging.log|debug|info|... calls for such purpose. - msg: str, the message to be logged. - *args: The args to be substituted into the msg. - **kwargs: May contain exc_info to add exception traceback to message. - """ - log(level, msg, *args, **kwargs) - - -def vlog_is_on(level): - """Checks if vlog is enabled for the given level in caller's source file. - - Args: - level: int, the C++ verbose logging level at which to log the message, - e.g. 1, 2, 3, 4... While absl level constants are also supported, - callers should prefer level_debug|level_info|... calls for - checking those. - - Returns: - True if logging is turned on for that level. - """ - - if level > converter.ABSL_DEBUG: - # Even though this function supports level that is greater than 1, users - # should use logging.vlog instead for such cases. - # Treat this as vlog, 1 is equivalent to DEBUG. - standard_level = converter.STANDARD_DEBUG - (level - 1) - else: - if level < converter.ABSL_FATAL: - level = converter.ABSL_FATAL - standard_level = converter.absl_to_standard(level) - return _absl_logger.isEnabledFor(standard_level) - - -def flush(): - """Flushes all log files.""" - get_absl_handler().flush() - - -def level_debug(): - """Returns True if debug logging is turned on.""" - return get_verbosity() >= DEBUG - - -def level_info(): - """Returns True if info logging is turned on.""" - return get_verbosity() >= INFO - - -def level_warning(): - """Returns True if warning logging is turned on.""" - return get_verbosity() >= WARNING - - -level_warn = level_warning # Deprecated function. - - -def level_error(): - """Returns True if error logging is turned on.""" - return get_verbosity() >= ERROR - - -def get_log_file_name(level=INFO): - """Returns the name of the log file. - - For Python logging, only one file is used and level is ignored. And it returns - empty string if it logs to stderr/stdout or the log stream has no `name` - attribute. - - Args: - level: int, the absl.logging level. - - Raises: - ValueError: Raised when `level` has an invalid value. - """ - if level not in converter.ABSL_LEVELS: - raise ValueError('Invalid absl.logging level {}'.format(level)) - stream = get_absl_handler().python_handler.stream - if (stream == sys.stderr or stream == sys.stdout or - not hasattr(stream, 'name')): - return '' - else: - return stream.name - - -def find_log_dir_and_names(program_name=None, log_dir=None): - """Computes the directory and filename prefix for log file. - - Args: - program_name: str|None, the filename part of the path to the program that - is running without its extension. e.g: if your program is called - ``usr/bin/foobar.py`` this method should probably be called with - ``program_name='foobar`` However, this is just a convention, you can - pass in any string you want, and it will be used as part of the - log filename. If you don't pass in anything, the default behavior - is as described in the example. In python standard logging mode, - the program_name will be prepended with ``py_`` if it is the - ``program_name`` argument is omitted. - log_dir: str|None, the desired log directory. - - Returns: - (log_dir, file_prefix, symlink_prefix) - - Raises: - FileNotFoundError: raised in Python 3 when it cannot find a log directory. - OSError: raised in Python 2 when it cannot find a log directory. - """ - if not program_name: - # Strip the extension (foobar.par becomes foobar, and - # fubar.py becomes fubar). We do this so that the log - # file names are similar to C++ log file names. - program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] - - # Prepend py_ to files so that python code gets a unique file, and - # so that C++ libraries do not try to write to the same log files as us. - program_name = 'py_%s' % program_name - - actual_log_dir = find_log_dir(log_dir=log_dir) - - try: - username = getpass.getuser() - except KeyError: - # This can happen, e.g. when running under docker w/o passwd file. - if hasattr(os, 'getuid'): - # Windows doesn't have os.getuid - username = str(os.getuid()) - else: - username = 'unknown' - hostname = socket.gethostname() - file_prefix = '%s.%s.%s.log' % (program_name, hostname, username) - - return actual_log_dir, file_prefix, program_name - - -def find_log_dir(log_dir=None): - """Returns the most suitable directory to put log files into. - - Args: - log_dir: str|None, if specified, the logfile(s) will be created in that - directory. Otherwise if the --log_dir command-line flag is provided, - the logfile will be created in that directory. Otherwise the logfile - will be created in a standard location. - - Raises: - FileNotFoundError: raised in Python 3 when it cannot find a log directory. - OSError: raised in Python 2 when it cannot find a log directory. - """ - # Get a list of possible log dirs (will try to use them in order). - # NOTE: Google's internal implementation has a special handling for Google - # machines, which uses a list of directories. Hence the following uses `dirs` - # instead of a single directory. - if log_dir: - # log_dir was explicitly specified as an arg, so use it and it alone. - dirs = [log_dir] - elif FLAGS['log_dir'].value: - # log_dir flag was provided, so use it and it alone (this mimics the - # behavior of the same flag in logging.cc). - dirs = [FLAGS['log_dir'].value] - else: - dirs = [tempfile.gettempdir()] - - # Find the first usable log dir. - for d in dirs: - if os.path.isdir(d) and os.access(d, os.W_OK): - return d - raise FileNotFoundError( - "Can't find a writable directory for logs, tried %s" % dirs) - - -def get_absl_log_prefix(record): - """Returns the absl log prefix for the log record. - - Args: - record: logging.LogRecord, the record to get prefix for. - """ - created_tuple = time.localtime(record.created) - created_microsecond = int(record.created % 1.0 * 1e6) - - critical_prefix = '' - level = record.levelno - if _is_non_absl_fatal_record(record): - # When the level is FATAL, but not logged from absl, lower the level so - # it's treated as ERROR. - level = logging.ERROR - critical_prefix = _CRITICAL_PREFIX - severity = converter.get_initial_for_level(level) - - return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % ( - severity, - created_tuple.tm_mon, - created_tuple.tm_mday, - created_tuple.tm_hour, - created_tuple.tm_min, - created_tuple.tm_sec, - created_microsecond, - _get_thread_id(), - record.filename, - record.lineno, - critical_prefix) - - -def skip_log_prefix(func): - """Skips reporting the prefix of a given function or name by :class:`~absl.logging.ABSLLogger`. - - This is a convenience wrapper function / decorator for - :meth:`~absl.logging.ABSLLogger.register_frame_to_skip`. - - If a callable function is provided, only that function will be skipped. - If a function name is provided, all functions with the same name in the - file that this is called in will be skipped. - - This can be used as a decorator of the intended function to be skipped. - - Args: - func: Callable function or its name as a string. - - Returns: - func (the input, unchanged). - - Raises: - ValueError: The input is callable but does not have a function code object. - TypeError: The input is neither callable nor a string. - """ - if callable(func): - func_code = getattr(func, '__code__', None) - if func_code is None: - raise ValueError('Input callable does not have a function code object.') - file_name = func_code.co_filename - func_name = func_code.co_name - func_lineno = func_code.co_firstlineno - elif isinstance(func, str): - file_name = get_absl_logger().findCaller()[0] - func_name = func - func_lineno = None - else: - raise TypeError('Input is neither callable nor a string.') - ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno) - return func - - -def _is_non_absl_fatal_record(log_record): - return (log_record.levelno >= logging.FATAL and - not log_record.__dict__.get(_ABSL_LOG_FATAL, False)) - - -def _is_absl_fatal_record(log_record): - return (log_record.levelno >= logging.FATAL and - log_record.__dict__.get(_ABSL_LOG_FATAL, False)) - - -# Indicates if we still need to warn about pre-init logs going to stderr. -_warn_preinit_stderr = True - - -class PythonHandler(logging.StreamHandler): - """The handler class used by Abseil Python logging implementation.""" - - def __init__(self, stream=None, formatter=None): - super(PythonHandler, self).__init__(stream) - self.setFormatter(formatter or PythonFormatter()) - - def start_logging_to_file(self, program_name=None, log_dir=None): - """Starts logging messages to files instead of standard error.""" - FLAGS.logtostderr = False - - actual_log_dir, file_prefix, symlink_prefix = find_log_dir_and_names( - program_name=program_name, log_dir=log_dir) - - basename = '%s.INFO.%s.%d' % ( - file_prefix, - time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time())), - os.getpid()) - filename = os.path.join(actual_log_dir, basename) - - self.stream = open(filename, 'a', encoding='utf-8') - - # os.symlink is not available on Windows Python 2. - if getattr(os, 'symlink', None): - # Create a symlink to the log file with a canonical name. - symlink = os.path.join(actual_log_dir, symlink_prefix + '.INFO') - try: - if os.path.islink(symlink): - os.unlink(symlink) - os.symlink(os.path.basename(filename), symlink) - except EnvironmentError: - # If it fails, we're sad but it's no error. Commonly, this - # fails because the symlink was created by another user and so - # we can't modify it - pass - - def use_absl_log_file(self, program_name=None, log_dir=None): - """Conditionally logs to files, based on --logtostderr.""" - if FLAGS['logtostderr'].value: - self.stream = sys.stderr - else: - self.start_logging_to_file(program_name=program_name, log_dir=log_dir) - - def flush(self): - """Flushes all log files.""" - self.acquire() - try: - self.stream.flush() - except (EnvironmentError, ValueError): - # A ValueError is thrown if we try to flush a closed file. - pass - finally: - self.release() - - def _log_to_stderr(self, record): - """Emits the record to stderr. - - This temporarily sets the handler stream to stderr, calls - StreamHandler.emit, then reverts the stream back. - - Args: - record: logging.LogRecord, the record to log. - """ - # emit() is protected by a lock in logging.Handler, so we don't need to - # protect here again. - old_stream = self.stream - self.stream = sys.stderr - try: - super(PythonHandler, self).emit(record) - finally: - self.stream = old_stream - - def emit(self, record): - """Prints a record out to some streams. - - 1. If ``FLAGS.logtostderr`` is set, it will print to ``sys.stderr`` ONLY. - 2. If ``FLAGS.alsologtostderr`` is set, it will print to ``sys.stderr``. - 3. If ``FLAGS.logtostderr`` is not set, it will log to the stream - associated with the current thread. - - Args: - record: :class:`logging.LogRecord`, the record to emit. - """ - # People occasionally call logging functions at import time before - # our flags may have even been defined yet, let alone even parsed, as we - # rely on the C++ side to define some flags for us and app init to - # deal with parsing. Match the C++ library behavior of notify and emit - # such messages to stderr. It encourages people to clean-up and does - # not hide the message. - level = record.levelno - if not FLAGS.is_parsed(): # Also implies "before flag has been defined". - global _warn_preinit_stderr - if _warn_preinit_stderr: - sys.stderr.write( - 'WARNING: Logging before flag parsing goes to stderr.\n') - _warn_preinit_stderr = False - self._log_to_stderr(record) - elif FLAGS['logtostderr'].value: - self._log_to_stderr(record) - else: - super(PythonHandler, self).emit(record) - stderr_threshold = converter.string_to_standard( - FLAGS['stderrthreshold'].value) - if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and - self.stream != sys.stderr): - self._log_to_stderr(record) - # Die when the record is created from ABSLLogger and level is FATAL. - if _is_absl_fatal_record(record): - self.flush() # Flush the log before dying. - - # In threaded python, sys.exit() from a non-main thread only - # exits the thread in question. - os.abort() - - def close(self): - """Closes the stream to which we are writing.""" - self.acquire() - try: - self.flush() - try: - # Do not close the stream if it's sys.stderr|stdout. They may be - # redirected or overridden to files, which should be managed by users - # explicitly. - user_managed = sys.stderr, sys.stdout, sys.__stderr__, sys.__stdout__ - if self.stream not in user_managed and ( - not hasattr(self.stream, 'isatty') or not self.stream.isatty()): - self.stream.close() - except ValueError: - # A ValueError is thrown if we try to run isatty() on a closed file. - pass - super(PythonHandler, self).close() - finally: - self.release() - - -class ABSLHandler(logging.Handler): - """Abseil Python logging module's log handler.""" - - def __init__(self, python_logging_formatter): - super(ABSLHandler, self).__init__() - - self._python_handler = PythonHandler(formatter=python_logging_formatter) - self.activate_python_handler() - - def format(self, record): - return self._current_handler.format(record) - - def setFormatter(self, fmt): - self._current_handler.setFormatter(fmt) - - def emit(self, record): - self._current_handler.emit(record) - - def flush(self): - self._current_handler.flush() - - def close(self): - super(ABSLHandler, self).close() - self._current_handler.close() - - def handle(self, record): - rv = self.filter(record) - if rv: - return self._current_handler.handle(record) - return rv - - @property - def python_handler(self): - return self._python_handler - - def activate_python_handler(self): - """Uses the Python logging handler as the current logging handler.""" - self._current_handler = self._python_handler - - def use_absl_log_file(self, program_name=None, log_dir=None): - self._current_handler.use_absl_log_file(program_name, log_dir) - - def start_logging_to_file(self, program_name=None, log_dir=None): - self._current_handler.start_logging_to_file(program_name, log_dir) - - -class PythonFormatter(logging.Formatter): - """Formatter class used by :class:`~absl.logging.PythonHandler`.""" - - def format(self, record): - """Appends the message from the record to the results of the prefix. - - Args: - record: logging.LogRecord, the record to be formatted. - - Returns: - The formatted string representing the record. - """ - if (not FLAGS['showprefixforinfo'].value and - FLAGS['verbosity'].value == converter.ABSL_INFO and - record.levelno == logging.INFO and - _absl_handler.python_handler.stream == sys.stderr): - prefix = '' - else: - prefix = get_absl_log_prefix(record) - return prefix + super(PythonFormatter, self).format(record) - - -class ABSLLogger(logging.getLoggerClass()): - """A logger that will create LogRecords while skipping some stack frames. - - This class maintains an internal list of filenames and method names - for use when determining who called the currently executing stack - frame. Any method names from specific source files are skipped when - walking backwards through the stack. - - Client code should use the register_frame_to_skip method to let the - ABSLLogger know which method from which file should be - excluded from the walk backwards through the stack. - """ - _frames_to_skip = set() - - def findCaller(self, stack_info=False, stacklevel=1): - """Finds the frame of the calling method on the stack. - - This method skips any frames registered with the - ABSLLogger and any methods from this file, and whatever - method is currently being used to generate the prefix for the log - line. Then it returns the file name, line number, and method name - of the calling method. An optional fourth item may be returned, - callers who only need things from the first three are advised to - always slice or index the result rather than using direct unpacking - assignment. - - Args: - stack_info: bool, when True, include the stack trace as a fourth item - returned. On Python 3 there are always four items returned - the - fourth will be None when this is False. On Python 2 the stdlib - base class API only returns three items. We do the same when this - new parameter is unspecified or False for compatibility. - - Returns: - (filename, lineno, methodname[, sinfo]) of the calling method. - """ - f_to_skip = ABSLLogger._frames_to_skip - # Use sys._getframe(2) instead of logging.currentframe(), it's slightly - # faster because there is one less frame to traverse. - frame = sys._getframe(2) # pylint: disable=protected-access - - while frame: - code = frame.f_code - if (_LOGGING_FILE_PREFIX not in code.co_filename and - (code.co_filename, code.co_name, - code.co_firstlineno) not in f_to_skip and - (code.co_filename, code.co_name) not in f_to_skip): - sinfo = None - if stack_info: - out = io.StringIO() - out.write(u'Stack (most recent call last):\n') - traceback.print_stack(frame, file=out) - sinfo = out.getvalue().rstrip(u'\n') - return (code.co_filename, frame.f_lineno, code.co_name, sinfo) - frame = frame.f_back - - def critical(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``CRITICAL``.""" - self.log(logging.CRITICAL, msg, *args, **kwargs) - - def fatal(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``FATAL``.""" - self.log(logging.FATAL, msg, *args, **kwargs) - - def error(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``ERROR``.""" - self.log(logging.ERROR, msg, *args, **kwargs) - - def warn(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``WARN``.""" - warnings.warn("The 'warn' method is deprecated, use 'warning' instead", - DeprecationWarning, 2) - self.log(logging.WARN, msg, *args, **kwargs) - - def warning(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``WARNING``.""" - self.log(logging.WARNING, msg, *args, **kwargs) - - def info(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``INFO``.""" - self.log(logging.INFO, msg, *args, **kwargs) - - def debug(self, msg, *args, **kwargs): - """Logs ``msg % args`` with severity ``DEBUG``.""" - self.log(logging.DEBUG, msg, *args, **kwargs) - - def log(self, level, msg, *args, **kwargs): - """Logs a message at a cetain level substituting in the supplied arguments. - - This method behaves differently in python and c++ modes. - - Args: - level: int, the standard logging level at which to log the message. - msg: str, the text of the message to log. - *args: The arguments to substitute in the message. - **kwargs: The keyword arguments to substitute in the message. - """ - if level >= logging.FATAL: - # Add property to the LogRecord created by this logger. - # This will be used by the ABSLHandler to determine whether it should - # treat CRITICAL/FATAL logs as really FATAL. - extra = kwargs.setdefault('extra', {}) - extra[_ABSL_LOG_FATAL] = True - super(ABSLLogger, self).log(level, msg, *args, **kwargs) - - def handle(self, record): - """Calls handlers without checking ``Logger.disabled``. - - Non-root loggers are set to disabled after setup with :func:`logging.config` - if it's not explicitly specified. Historically, absl logging will not be - disabled by that. To maintaining this behavior, this function skips - checking the ``Logger.disabled`` bit. - - This logger can still be disabled by adding a filter that filters out - everything. - - Args: - record: logging.LogRecord, the record to handle. - """ - if self.filter(record): - self.callHandlers(record) - - @classmethod - def register_frame_to_skip(cls, file_name, function_name, line_number=None): - """Registers a function name to skip when walking the stack. - - The :class:`~absl.logging.ABSLLogger` sometimes skips method calls on the - stack to make the log messages meaningful in their appropriate context. - This method registers a function from a particular file as one - which should be skipped. - - Args: - file_name: str, the name of the file that contains the function. - function_name: str, the name of the function to skip. - line_number: int, if provided, only the function with this starting line - number will be skipped. Otherwise, all functions with the same name - in the file will be skipped. - """ - if line_number is not None: - cls._frames_to_skip.add((file_name, function_name, line_number)) - else: - cls._frames_to_skip.add((file_name, function_name)) - - -def _get_thread_id(): - """Gets id of current thread, suitable for logging as an unsigned quantity. - - If pywrapbase is linked, returns GetTID() for the thread ID to be - consistent with C++ logging. Otherwise, returns the numeric thread id. - The quantities are made unsigned by masking with 2*sys.maxint + 1. - - Returns: - Thread ID unique to this process (unsigned) - """ - thread_id = threading.get_ident() - return thread_id & _THREAD_ID_MASK - - -def get_absl_logger(): - """Returns the absl logger instance.""" - return _absl_logger - - -def get_absl_handler(): - """Returns the absl handler instance.""" - return _absl_handler - - -def use_python_logging(quiet=False): - """Uses the python implementation of the logging code. - - Args: - quiet: No logging message about switching logging type. - """ - get_absl_handler().activate_python_handler() - if not quiet: - info('Restoring pure python logging') - - -_attempted_to_remove_stderr_stream_handlers = False - - -def use_absl_handler(): - """Uses the ABSL logging handler for logging. - - This method is called in :func:`app.run()` so the absl handler - is used in absl apps. - """ - global _attempted_to_remove_stderr_stream_handlers - if not _attempted_to_remove_stderr_stream_handlers: - # The absl handler logs to stderr by default. To prevent double logging to - # stderr, the following code tries its best to remove other handlers that - # emit to stderr. Those handlers are most commonly added when - # logging.info/debug is called before calling use_absl_handler(). - handlers = [ - h for h in logging.root.handlers - if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr] - for h in handlers: - logging.root.removeHandler(h) - _attempted_to_remove_stderr_stream_handlers = True - - absl_handler = get_absl_handler() - if absl_handler not in logging.root.handlers: - logging.root.addHandler(absl_handler) - FLAGS['verbosity']._update_logging_levels() # pylint: disable=protected-access - FLAGS['logger_levels']._update_logger_levels() # pylint: disable=protected-access - - -def _initialize(): - """Initializes loggers and handlers.""" - global _absl_logger, _absl_handler - - if _absl_logger: - return - - original_logger_class = logging.getLoggerClass() - logging.setLoggerClass(ABSLLogger) - _absl_logger = logging.getLogger('absl') - logging.setLoggerClass(original_logger_class) - - python_logging_formatter = PythonFormatter() - _absl_handler = ABSLHandler(python_logging_formatter) - - -_initialize() diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/boxplot.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/boxplot.py deleted file mode 100644 index 31cd62f42db8cab10ebde58a46bccb24f6fa1754..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/boxplot.py +++ /dev/null @@ -1,18 +0,0 @@ -""" -Boxplot with Min/Max Whiskers ------------------------------- -This example shows how to make a boxplot using US Population data from 2000. -Note that the default value of the `extent` property is 1.5, -which represents the convention of extending the whiskers -to the furthest points within 1.5 * IQR from the first and third quartile. -""" -# category: other charts -import altair as alt -from vega_datasets import data - -source = data.population.url - -alt.Chart(source).mark_boxplot(extent='min-max').encode( - x='age:O', - y='people:Q' -) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/data/audio/raw_audio_dataset.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/data/audio/raw_audio_dataset.py deleted file mode 100644 index 181e2bbc9a7764e38e96e6ced3307f50afc98879..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/data/audio/raw_audio_dataset.py +++ /dev/null @@ -1,393 +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/augmentedimaginationhackathon/paperstocode/fronty/src/app/gym-setup/upload.component.spec.ts b/spaces/augmentedimaginationhackathon/paperstocode/fronty/src/app/gym-setup/upload.component.spec.ts deleted file mode 100644 index 3529e88a586a15bb0701ef2f73fb9a232f6002da..0000000000000000000000000000000000000000 --- a/spaces/augmentedimaginationhackathon/paperstocode/fronty/src/app/gym-setup/upload.component.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { ComponentFixture, TestBed } from '@angular/core/testing'; - -import { UploadComponent } from './upload.component'; - -describe('GymSetupComponent', () => { - let component: UploadComponent; - let fixture: ComponentFixture; - - beforeEach(async () => { - await TestBed.configureTestingModule({ - declarations: [ UploadComponent ] - }) - .compileComponents(); - }); - - beforeEach(() => { - fixture = TestBed.createComponent(UploadComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - }); - - it('should create', () => { - expect(component).toBeTruthy(); - }); -}); diff --git a/spaces/awacke1/Memory-Chat-Story-Generator-Bloom/app.py b/spaces/awacke1/Memory-Chat-Story-Generator-Bloom/app.py deleted file mode 100644 index d9cf899fcf0eab8534d5612d2c53e2d662603502..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Memory-Chat-Story-Generator-Bloom/app.py +++ /dev/null @@ -1,331 +0,0 @@ -import gradio as gr -import requests -import os - -##Bloom Inference API - -API_URL = "https://api-inference.huggingface.co/models/bigscience/bloom" # Models on HF feature inference API which allows direct call and easy interface - -HF_TOKEN = os.environ["HF_TOKEN"] # Add a token called HF_TOKEN under profile in settings access tokens. Then copy it to the repository secret in this spaces settings panel. os.environ reads from there. - -# For headers the bearer token needs to incclude your HF_TOKEN value. -headers = {"Authorization": f"Bearer {HF_TOKEN}"} - -# Improved text generation function -def text_generate(prompt, generated_txt): - # Initialize Thoughts variable to aggregate text - Thoughts = "" - - # Debug: display the prompt - Thoughts += f"Prompt: {prompt}\n" - - json_ = { - "inputs": prompt, - "parameters": { - "top_p": 0.9, - "temperature": 1.1, - "return_full_text": True, - "do_sample": True, - }, - "options": { - "use_cache": True, - "wait_for_model": True, - }, - } - response = requests.post(API_URL, headers=headers, json=json_) - output = response.json() - - # Debug: display the output - Thoughts += f"Output: {output}\n" - output_tmp = output[0]['generated_text'] - - # Debug: display the output_tmp - Thoughts += f"output_tmp is: {output_tmp}\n" - solution = output_tmp.split("\nQ:")[0] - - # Debug: display the solution after splitting - Thoughts += f"Final response after splits is: {solution}\n" - - if '\nOutput:' in solution: - final_solution = solution.split("\nOutput:")[0] - Thoughts += f"Response after removing output is: {final_solution}\n" - elif '\n\n' in solution: - final_solution = solution.split("\n\n")[0] - Thoughts += f"Response after removing new line entries is: {final_solution}\n" - else: - final_solution = solution - - if len(generated_txt) == 0: - display_output = final_solution - else: - display_output = generated_txt[:-len(prompt)] + final_solution - - new_prompt = final_solution[len(prompt):] - - # Debug: display the new prompt for the next cycle - Thoughts += f"new prompt for next cycle is: {new_prompt}\n" - Thoughts += f"display_output for printing on screen is: {display_output}\n" - - if len(new_prompt) == 0: - temp_text = display_output[::-1] - Thoughts += f"What is the last character of the sentence?: {temp_text[0]}\n" - - if temp_text[1] == '.': - first_period_loc = temp_text[2:].find('.') + 1 - Thoughts += f"Location of last Period is: {first_period_loc}\n" - new_prompt = display_output[-first_period_loc:-1] - Thoughts += f"Not sending blank as prompt so new prompt for next cycle is: {new_prompt}\n" - else: - first_period_loc = temp_text.find('.') - Thoughts += f"Location of last Period is: {first_period_loc}\n" - new_prompt = display_output[-first_period_loc:-1] - Thoughts += f"Not sending blank as prompt so new prompt for next cycle is: {new_prompt}\n" - - display_output = display_output[:-1] - - return display_output, new_prompt, Thoughts - - - - -# Text generation -def text_generate_old(prompt, generated_txt): - #Prints to debug the code - print(f"*****Inside text_generate - Prompt is :{prompt}") - json_ = {"inputs": prompt, - "parameters": - { - "top_p": 0.9, - "temperature": 1.1, - #"max_new_tokens": 64, - "return_full_text": True, - "do_sample":True, - }, - "options": - {"use_cache": True, - "wait_for_model": True, - },} - - - response = requests.post(API_URL, headers=headers, json=json_) - print(f"Response is : {response}") - output = response.json() - print(f"output is : {output}") - output_tmp = output[0]['generated_text'] - print(f"output_tmp is: {output_tmp}") - solution = output_tmp.split("\nQ:")[0] - print(f"Final response after splits is: {solution}") - - - if '\nOutput:' in solution: - final_solution = solution.split("\nOutput:")[0] - print(f"Response after removing output is: {final_solution}") - elif '\n\n' in solution: - final_solution = solution.split("\n\n")[0] - print(f"Response after removing new line entries is: {final_solution}") - else: - final_solution = solution - if len(generated_txt) == 0 : - display_output = final_solution - else: - display_output = generated_txt[:-len(prompt)] + final_solution - - - new_prompt = final_solution[len(prompt):] - print(f"New prompt for next cycle: {new_prompt}") - print(f"Output final is : {display_output}") - if len(new_prompt) == 0: - temp_text = display_output[::-1] - print(f"Last character of sentence: {temp_text[0]}") - if temp_text[1] == '.': - first_period_loc = temp_text[2:].find('.') + 1 - print(f"Location of last Period is: {first_period_loc}") - new_prompt = display_output[-first_period_loc:-1] - print(f"Not sending blank as prompt so new prompt for next cycle is : {new_prompt}") - else: - print("HERE") - first_period_loc = temp_text.find('.') - print(f"Last Period is : {first_period_loc}") - new_prompt = display_output[-first_period_loc:-1] - print(f"New prompt for next cycle is : {new_prompt}") - display_output = display_output[:-1] - return display_output, new_prompt - - -Markdown = """ - - -# 2023 Bloom Spaces - -1. Model: https://huggingface.co/bigscience/bloom -2. Bloom Theme Generator: https://huggingface.co/spaces/awacke1/Write-Stories-Using-Bloom -3. Bloom Ghotwriter : https://huggingface.co/spaces/awacke1/Bloom.Generative.Writer -4. https://huggingface.co/spaces/awacke1/Bloom.Human.Feedback.File.Ops -5. https://huggingface.co/spaces/awacke1/04-AW-StorywriterwMem - -🌸 🔎 Bloom Searcher 🔍 🌸 - -Tool design for Roots: [URL](https://huggingface.co/spaces/bigscience-data/scisearch/blob/main/roots_search_tool_specs.pdf). - -Bloom on Wikipedia: [URL](https://en.wikipedia.org/wiki/BLOOM_(language_model)). - -Bloom Video Playlist: [URL](https://www.youtube.com/playlist?list=PLHgX2IExbFouqnsIqziThlPCX_miiDq14). - -Access full corpus check [URL](https://forms.gle/qyYswbEL5kA23Wu99). - -Big Science - How to get started - -Big Science is a 176B parameter new ML model that was trained on a set of datasets for Natural Language processing, and many other tasks that are not yet explored.. Below is the set of the papers, models, links, and datasets around big science which promises to be the best, most recent large model of its kind benefitting all science pursuits. - -Model: https://huggingface.co/bigscience/bloom - -Papers: -BLOOM: A 176B-Parameter Open-Access Multilingual Language Model https://arxiv.org/abs/2211.05100 -Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism https://arxiv.org/abs/1909.08053 -8-bit Optimizers via Block-wise Quantization https://arxiv.org/abs/2110.02861 -Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation https://arxiv.org/abs/2108.12409 -https://huggingface.co/models?other=doi:10.57967/hf/0003 -217 Other Models optimizing use of bloom via specialization: https://huggingface.co/models?other=bloom - -Datasets: -Universal Dependencies: https://paperswithcode.com/dataset/universal-dependencies -WMT 2014: https://paperswithcode.com/dataset/wmt-2014 -The Pile: https://paperswithcode.com/dataset/the-pile -HumanEval: https://paperswithcode.com/dataset/humaneval -FLORES-101: https://paperswithcode.com/dataset/flores-101 -CrowS-Pairs: https://paperswithcode.com/dataset/crows-pairs -WikiLingua: https://paperswithcode.com/dataset/wikilingua -MTEB: https://paperswithcode.com/dataset/mteb -xP3: https://paperswithcode.com/dataset/xp3 -DiaBLa: https://paperswithcode.com/dataset/diabla - -Evals: -https://github.com/AaronCWacker/evals - -## Language Models 🗣️ -🏆 Bloom sets new record for most performant and efficient AI model in science! 🌸 -### Comparison of Large Language Models -| Model Name | Model Size (in Parameters) | -| ----------------- | -------------------------- | -| BigScience-tr11-176B | 176 billion | -| GPT-3 | 175 billion | -| OpenAI's DALL-E 2.0 | 500 million | -| NVIDIA's Megatron | 8.3 billion | -| Transformer-XL | 250 million | -| XLNet | 210 million | - -## ChatGPT Datasets 📚 -- WebText -- Common Crawl -- BooksCorpus -- English Wikipedia -- Toronto Books Corpus -- OpenWebText - -## ChatGPT Datasets - Details 📚 -- **WebText:** A dataset of web pages crawled from domains on the Alexa top 5,000 list. This dataset was used to pretrain GPT-2. - - [WebText: A Large-Scale Unsupervised Text Corpus by Radford et al.](https://paperswithcode.com/dataset/webtext) -- **Common Crawl:** A dataset of web pages from a variety of domains, which is updated regularly. This dataset was used to pretrain GPT-3. - - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/common-crawl) by Brown et al. -- **BooksCorpus:** A dataset of over 11,000 books from a variety of genres. - - [Scalable Methods for 8 Billion Token Language Modeling](https://paperswithcode.com/dataset/bookcorpus) by Zhu et al. -- **English Wikipedia:** A dump of the English-language Wikipedia as of 2018, with articles from 2001-2017. - - [Improving Language Understanding by Generative Pre-Training](https://huggingface.co/spaces/awacke1/WikipediaUltimateAISearch?logs=build) Space for Wikipedia Search -- **Toronto Books Corpus:** A dataset of over 7,000 books from a variety of genres, collected by the University of Toronto. - - [Massively Multilingual Sentence Embeddings for Zero-Shot Cross-Lingual Transfer and Beyond](https://paperswithcode.com/dataset/bookcorpus) by Schwenk and Douze. -- **OpenWebText:** A dataset of web pages that were filtered to remove content that was likely to be low-quality or spammy. This dataset was used to pretrain GPT-3. - - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/openwebtext) by Brown et al. - -## Big Science Model 🚀 -- 📜 Papers: - 1. BLOOM: A 176B-Parameter Open-Access Multilingual Language Model [Paper](https://arxiv.org/abs/2211.05100) - 2. Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism [Paper](https://arxiv.org/abs/1909.08053) - 3. 8-bit Optimizers via Block-wise Quantization [Paper](https://arxiv.org/abs/2110.02861) - 4. Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation [Paper](https://arxiv.org/abs/2108.12409) - 5. [Other papers related to Big Science](https://huggingface.co/models?other=doi:10.57967/hf/0003) - 6. [217 other models optimized for use with Bloom](https://huggingface.co/models?other=bloom) - -- 📚 Datasets: -**Datasets:** -1. - **Universal Dependencies:** A collection of annotated corpora for natural language processing in a range of languages, with a focus on dependency parsing. - - [Universal Dependencies official website.](https://universaldependencies.org/) -2. - **WMT 2014:** The fourth edition of the Workshop on Statistical Machine Translation, featuring shared tasks on translating between English and various other languages. - - [WMT14 website.](http://www.statmt.org/wmt14/) -3. - **The Pile:** An English language corpus of diverse text, sourced from various places on the internet. - - [The Pile official website.](https://pile.eleuther.ai/) -4. - **HumanEval:** A dataset of English sentences, annotated with human judgments on a range of linguistic qualities. - - [HumanEval: An Evaluation Benchmark for Language Understanding](https://github.com/google-research-datasets/humaneval) by Gabriel Ilharco, Daniel Loureiro, Pedro Rodriguez, and Afonso Mendes. -5. - **FLORES-101:** A dataset of parallel sentences in 101 languages, designed for multilingual machine translation. - - [FLORES-101: A Massively Multilingual Parallel Corpus for Language Understanding](https://flores101.opennmt.net/) by Aman Madaan, Shruti Rijhwani, Raghav Gupta, and Mitesh M. Khapra. -6. - **CrowS-Pairs:** A dataset of sentence pairs, designed for evaluating the plausibility of generated text. - - [CrowS-Pairs: A Challenge Dataset for Plausible Plausibility Judgments](https://github.com/stanford-cogsci/crows-pairs) by Andrea Madotto, Zhaojiang Lin, Chien-Sheng Wu, Pascale Fung, and Caiming Xiong. -7. - **WikiLingua:** A dataset of parallel sentences in 75 languages, sourced from Wikipedia. - - [WikiLingua: A New Benchmark Dataset for Cross-Lingual Wikification](https://arxiv.org/abs/2105.08031) by Jiarui Yao, Yanqiao Zhu, Ruihan Bao, Guosheng Lin, Lidong Bing, and Bei Shi. -8. - **MTEB:** A dataset of English sentences, annotated with their entailment relationships with respect to other sentences. - - [Multi-Task Evaluation Benchmark for Natural Language Inference](https://github.com/google-research-datasets/mteb) by Michał Lukasik, Marcin Junczys-Dowmunt, and Houda Bouamor. -9. - **xP3:** A dataset of English sentences, annotated with their paraphrase relationships with respect to other sentences. - - [xP3: A Large-Scale Evaluation Benchmark for Paraphrase Identification in Context](https://github.com/nyu-dl/xp3) by Aniket Didolkar, James Mayfield, Markus Saers, and Jason Baldridge. -10. - **DiaBLa:** A dataset of English dialogue, annotated with dialogue acts. - - [A Large-Scale Corpus for Conversation Disentanglement](https://github.com/HLTCHKUST/DiaBLA) by Samuel Broscheit, António Branco, and André F. T. Martins. - -- 📚 Dataset Papers with Code - 1. [Universal Dependencies](https://paperswithcode.com/dataset/universal-dependencies) - 2. [WMT 2014](https://paperswithcode.com/dataset/wmt-2014) - 3. [The Pile](https://paperswithcode.com/dataset/the-pile) - 4. [HumanEval](https://paperswithcode.com/dataset/humaneval) - 5. [FLORES-101](https://paperswithcode.com/dataset/flores-101) - 6. [CrowS-Pairs](https://paperswithcode.com/dataset/crows-pairs) - 7. [WikiLingua](https://paperswithcode.com/dataset/wikilingua) - 8. [MTEB](https://paperswithcode.com/dataset/mteb) - 9. [xP3](https://paperswithcode.com/dataset/xp3) - 10. [DiaBLa](https://paperswithcode.com/dataset/diabla) - -# Deep RL ML Strategy 🧠 -The AI strategies are: -- Language Model Preparation using Human Augmented with Supervised Fine Tuning 🤖 -- Reward Model Training with Prompts Dataset Multi-Model Generate Data to Rank 🎁 -- Fine Tuning with Reinforcement Reward and Distance Distribution Regret Score 🎯 -- Proximal Policy Optimization Fine Tuning 🤝 -- Variations - Preference Model Pretraining 🤔 -- Use Ranking Datasets Sentiment - Thumbs Up/Down, Distribution 📊 -- Online Version Getting Feedback 💬 -- OpenAI - InstructGPT - Humans generate LM Training Text 🔍 -- DeepMind - Advantage Actor Critic Sparrow, GopherCite 🦜 -- Reward Model Human Prefence Feedback 🏆 -For more information on specific techniques and implementations, check out the following resources: -- OpenAI's paper on [GPT-3](https://arxiv.org/abs/2005.14165) which details their Language Model Preparation approach -- DeepMind's paper on [SAC](https://arxiv.org/abs/1801.01290) which describes the Advantage Actor Critic algorithm -- OpenAI's paper on [Reward Learning](https://arxiv.org/abs/1810.06580) which explains their approach to training Reward Models -- OpenAI's blog post on [GPT-3's fine-tuning process](https://openai.com/blog/fine-tuning-gpt-3/) -""" - -# An insightful and engaging self-care health care demo -demo = gr.Blocks() - -with demo: - with gr.Row(): - input_prompt = gr.Textbox( - label="Write a self-care or health care related question to get started...", - lines=3, - value="Dear AI, please tell me about the importance of self-care and how it contributes to overall health and well-being.", - ) - - with gr.Row(): - generated_txt = gr.Textbox(lines=2, visible=True) - - with gr.Row(): - Thoughts = gr.Textbox(lines=4, visible=True) - - gen = gr.Button("Discover Health Insights") - - with gr.Row(): - gr.Markdown(Markdown) - - - gen.click( - text_generate, - inputs=[input_prompt, generated_txt], - outputs=[generated_txt, input_prompt, Thoughts], - ) - -demo.launch(enable_queue=True, debug=True) diff --git a/spaces/awacke1/Streamlit-Google-Maps-Texas/README.md b/spaces/awacke1/Streamlit-Google-Maps-Texas/README.md deleted file mode 100644 index a1901a96bc4bcd0ffa4f490eca9723a729bf2f8e..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Streamlit-Google-Maps-Texas/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 🏥 Texas Medical Centers 🤠 -emoji: 🏥🤠 -colorFrom: green -colorTo: indigo -sdk: streamlit -sdk_version: 1.28.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/awen666/web-ui/_next/static/chunks/pages/_app-4e72088c2da7d84b.js b/spaces/awen666/web-ui/_next/static/chunks/pages/_app-4e72088c2da7d84b.js deleted file mode 100644 index ee6fa99f89f7c8a6dc745be7f7e517f99f5b1e0e..0000000000000000000000000000000000000000 --- a/spaces/awen666/web-ui/_next/static/chunks/pages/_app-4e72088c2da7d84b.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[888],{41597:function(n,_,u){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_app",function(){return u(11767)}])}},function(n){var _=function(_){return n(n.s=_)};n.O(0,[774,179],function(){return _(41597),_(38645)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/spaces/banana-projects/web3d/node_modules/three/examples/js/nodes/materials/StandardNodeMaterial.js b/spaces/banana-projects/web3d/node_modules/three/examples/js/nodes/materials/StandardNodeMaterial.js deleted file mode 100644 index bcc220473bc904bf5919e178831ef636b2e858a8..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/examples/js/nodes/materials/StandardNodeMaterial.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @author sunag / http://www.sunag.com.br/ - */ - -import { StandardNode } from './nodes/StandardNode.js'; -import { NodeMaterial } from './NodeMaterial.js'; -import { NodeUtils } from '../core/NodeUtils.js'; - -function StandardNodeMaterial() { - - var node = new StandardNode(); - - NodeMaterial.call( this, node, node ); - - this.type = "StandardNodeMaterial"; - -} - -StandardNodeMaterial.prototype = Object.create( NodeMaterial.prototype ); -StandardNodeMaterial.prototype.constructor = StandardNodeMaterial; - -NodeUtils.addShortcuts( StandardNodeMaterial.prototype, 'fragment', [ - 'color', - 'alpha', - 'roughness', - 'metalness', - 'reflectivity', - 'clearCoat', - 'clearCoatRoughness', - 'normal', - 'emissive', - 'ambient', - 'light', - 'shadow', - 'ao', - 'environment', - 'mask', - 'position' -] ); - -export { StandardNodeMaterial }; diff --git a/spaces/bguberfain/Detic/README.md b/spaces/bguberfain/Detic/README.md deleted file mode 100644 index ae9d69f46a9dc2759191f5bc591add2789f69c95..0000000000000000000000000000000000000000 --- a/spaces/bguberfain/Detic/README.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Detic -emoji: 🐨 -colorFrom: purple -colorTo: gray -sdk: gradio -app_file: app.py -pinned: false -license: mit ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio`, `streamlit`, or `static` - -`sdk_version` : _string_ -Only applicable for `streamlit` SDK. -See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions. - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code). -Path is relative to the root of the repository. - -`models`: _List[string]_ -HF model IDs (like "gpt2" or "deepset/roberta-base-squad2") used in the Space. -Will be parsed automatically from your code if not specified here. - -`datasets`: _List[string]_ -HF dataset IDs (like "common_voice" or "oscar-corpus/OSCAR-2109") used in the Space. -Will be parsed automatically from your code if not specified here. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/bigjoker/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/prompt.py b/spaces/bigjoker/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/prompt.py deleted file mode 100644 index f81aa7c281376933c95c854ed2ecc8ae99ad92a7..0000000000000000000000000000000000000000 --- a/spaces/bigjoker/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/prompt.py +++ /dev/null @@ -1,113 +0,0 @@ -import re - -def check_is_number(value): - float_pattern = r'^(?=.)([+-]?([0-9]*)(\.([0-9]+))?)$' - return re.match(float_pattern, value) - -def parse_weight(match, frame = 0)->float: - import numexpr - w_raw = match.group("weight") - if w_raw == None: - return 1 - if check_is_number(w_raw): - return float(w_raw) - else: - t = frame - if len(w_raw) < 3: - print('the value inside `-characters cannot represent a math function') - return 1 - return float(numexpr.evaluate(w_raw[1:-1])) - -def split_weighted_subprompts(text, frame = 0): - """ - splits the prompt based on deforum webui implementation, moved from generate.py - """ - math_parser = re.compile(""" - (?P( - `[\S\s]*?`# a math function wrapped in `-characters - )) - """, re.VERBOSE) - - parsed_prompt = re.sub(math_parser, lambda m: str(parse_weight(m, frame)), text) - - negative_prompts = [] - positive_prompts = [] - - prompt_split = parsed_prompt.split("--neg") - if len(prompt_split) > 1: - positive_prompts, negative_prompts = parsed_prompt.split("--neg") #TODO: add --neg to vanilla Deforum for compat - else: - positive_prompts = prompt_split[0] - negative_prompts = "" - - return positive_prompts, negative_prompts - -def interpolate_prompts(animation_prompts, max_frames): - import numpy as np - import pandas as pd - # Get prompts sorted by keyframe - sorted_prompts = sorted(animation_prompts.items(), key=lambda item: int(item[0])) - - # Setup container for interpolated prompts - prompt_series = pd.Series([np.nan for a in range(max_frames)]) - - # For every keyframe prompt except the last - for i in range(0,len(sorted_prompts)-1): - - # Get current and next keyframe - current_frame = int(sorted_prompts[i][0]) - next_frame = int(sorted_prompts[i+1][0]) - - # Ensure there's no weird ordering issues or duplication in the animation prompts - # (unlikely because we sort above, and the json parser will strip dupes) - if current_frame>=next_frame: - print(f"WARNING: Sequential prompt keyframes {i}:{current_frame} and {i+1}:{next_frame} are not monotonously increasing; skipping interpolation.") - continue - - # Get current and next keyframes' positive and negative prompts (if any) - current_prompt = sorted_prompts[i][1] - next_prompt = sorted_prompts[i+1][1] - current_positive, current_negative, *_ = current_prompt.split("--neg") + [None] - next_positive, next_negative, *_ = next_prompt.split("--neg") + [None] - - # Calculate how much to shift the weight from current to next prompt at each frame - weight_step = 1/(next_frame-current_frame) - - # Apply weighted prompt interpolation for each frame between current and next keyframe - # using the syntax: prompt1 :weight1 AND prompt1 :weight2 --neg nprompt1 :weight1 AND nprompt1 :weight2 - # (See: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#composable-diffusion ) - for f in range(current_frame,next_frame): - next_weight = weight_step * (f-current_frame) - current_weight = 1 - next_weight - - # We will build the prompt incrementally depending on which prompts are present - prompt_series[f] = '' - - # Cater for the case where neither, either or both current & next have positive prompts: - if current_positive: - prompt_series[f] += f"{current_positive} :{current_weight}" - if current_positive and next_positive: - prompt_series[f] += f" AND " - if next_positive: - prompt_series[f] += f"{next_positive} :{next_weight}" - - # Cater for the case where neither, either or both current & next have negative prompts: - if current_negative or next_negative: - prompt_series[f] += " --neg " - if current_negative: - prompt_series[f] += f" {current_negative} :{current_weight}" - if current_negative and next_negative: - prompt_series[f] += f" AND " - if next_negative: - prompt_series[f] += f" {next_negative} :{next_weight}" - - # Set explicitly declared keyframe prompts (overwriting interpolated values at the keyframe idx). This ensures: - # - That final prompt is set, and - # - Gives us a chance to emit warnings if any keyframe prompts are already using composable diffusion - for i, prompt in animation_prompts.items(): - prompt_series[int(i)] = prompt - if ' AND ' in prompt: - print(f"WARNING: keyframe {i}'s prompt is using composable diffusion (aka the 'AND' keyword). This will cause unexpected behaviour with interpolation.") - - # Return the filled series, in case max_frames is greater than the last keyframe or any ranges were skipped. - return prompt_series.ffill().bfill() diff --git a/spaces/bioriAsaeru/text-to-voice/Dart Pro 24 Keygen Torrent.md b/spaces/bioriAsaeru/text-to-voice/Dart Pro 24 Keygen Torrent.md deleted file mode 100644 index 859c7c7841dd3da00bf3c5ebb2fac721d8030c31..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Dart Pro 24 Keygen Torrent.md +++ /dev/null @@ -1,63 +0,0 @@ -
      -

      Dart Pro 24 Keygen Torrent: How to Get and Use It

      -

      Dart Pro 24 is a powerful software that allows you to edit, restore and master audio files with professional quality. It has many features and tools that can help you improve the sound of your recordings, such as noise reduction, click removal, equalization, compression, reverb and more. However, Dart Pro 24 is not a free software. You need to purchase a license to use it fully and legally. But what if you don't have the money or the willingness to pay for it? Is there a way to get Dart Pro 24 for free? The answer is yes, but it comes with some risks and challenges. In this article, we will show you how to get and use Dart Pro 24 keygen torrent, a file that can generate a valid serial number for the software.

      -

      dart pro 24 keygen torrent


      Download Filehttps://urloso.com/2uyPUi



      -

      What is Dart Pro 24 Keygen Torrent?

      -

      Dart Pro 24 keygen torrent is a file that contains a program called keygen and a list of peers that share the file. A keygen is a program that can create a unique serial number for a software, which can be used to activate it without paying for it. A torrent is a file that can be downloaded using a peer-to-peer network, which is a system that connects users who have the same file and allows them to share it with each other.

      -

      By downloading and running Dart Pro 24 keygen torrent, you can get a serial number for Dart Pro 24 that can unlock all its features and functions. However, this method is illegal and unethical, as it violates the copyright and license agreement of the software. It can also expose you to various dangers, such as viruses, malware, spyware, adware and more. Therefore, we do not recommend or endorse using Dart Pro 24 keygen torrent.

      -

      How to Get Dart Pro 24 Keygen Torrent?

      -

      If you still want to get Dart Pro 24 keygen torrent, despite the risks and consequences, you need to follow these steps:

      -

      -
        -
      1. Find a reliable website that offers Dart Pro 24 keygen torrent. You can use search engines or online forums to look for one. However, be careful and cautious, as many websites may contain fake or harmful files.
      2. -
      3. Download Dart Pro 24 keygen torrent from the website. You will need a torrent client, which is a software that can download torrent files. Some of the popular torrent clients are uTorrent, BitTorrent, qBittorrent and more.
      4. -
      5. Open Dart Pro 24 keygen torrent with your torrent client. The client will connect you with other users who have the same file and start downloading it from them.
      6. -
      7. Wait until the download is complete. The time may vary depending on the size of the file and the speed of your internet connection.
      8. -
      9. Extract Dart Pro 24 keygen torrent from the downloaded folder. You will need a software that can extract compressed files, such as WinRAR, WinZip or 7-Zip.
      10. -
      11. Run Dart Pro 24 keygen from the extracted folder. The program will generate a random serial number for Dart Pro 24.
      12. -
      13. Copy the serial number and paste it into the activation window of Dart Pro 24. The software will verify the serial number and activate itself.
      14. -
      -

      How to Use Dart Pro 24 Keygen Torrent?

      -

      After activating Dart Pro 24 with the keygen torrent, you can use it as normal. You can edit, restore and master your audio files with its features and tools. However, you should be aware of some limitations and drawbacks of using Dart Pro 24 keygen torrent:

      -
        -
      • You may not be able to update or upgrade Dart Pro 24 to the latest version.
      • -
      • You may not be able to access online support or customer service from the developer.
      • -
      • You may experience errors or glitches in the software performance.
      • -
      • You may face legal actions or penalties from the developer or authorities if they detect your illegal use of the software.
      • -
      -

      Conclusion

      -

      Dart Pro 24 keygen torrent is a file that can generate a serial number for Dart Pro 24, a powerful audio editing software. By downloading and running Dart Pro 24 keygen torrent, you can activate Dart Pro 24 without paying for it. However, this method is illegal and unethical, as it violates the copyright and license agreement of the software. It can also expose you to various dangers, such as viruses, malware, spyware, adware and more. Therefore, we do not recommend or endorse using Dart Pro 24 keygen torrent.

      -

      We hope this article has helped you learn more about Dart Pro 24 keygen torrent, how to get and use it. If you have any questions or feedback, please feel free to contact us. Thank you for reading and happy editing!

      -

      Alternatives to Dart Pro 24

      -

      Dart Pro 24 is not the only software that can edit, restore and master audio files. There are many other alternatives that can offer similar or better features and performance. Some of the best alternatives to Dart Pro 24 are:

      -
        -
      • Audacity: This is a free and open-source software that can record, edit and mix audio files. It has a wide range of effects and filters, such as noise reduction, compression, equalization, reverb and more. It also supports various formats and plugins.
      • -
      • Adobe Audition: This is a professional software that can create, edit and enhance audio files. It has a powerful multitrack editor, a waveform editor, a spectral display and a mixer. It also has advanced tools and features, such as noise reduction, restoration, mastering, analysis and more.
      • -
      • WavePad: This is an easy-to-use software that can edit and record audio files. It has a simple interface and basic tools, such as cut, copy, paste, trim, fade and more. It also has some effects and filters, such as noise reduction, equalization, reverb and more.
      • -
      • Sound Forge Pro: This is a professional software that can edit and master audio files. It has a high-quality sound engine, a multichannel editor, a spectral analysis and a batch processing. It also has advanced tools and features, such as noise reduction, restoration, mastering, analysis and more.
      • -
      • Ocenaudio: This is a free and cross-platform software that can edit and analyze audio files. It has a simple interface and basic tools, such as cut, copy, paste, trim, fade and more. It also has some effects and filters, such as noise reduction, equalization, reverb and more.
      • -
      -

      Conclusion

      -

      Dart Pro 24 keygen torrent is a file that can generate a serial number for Dart Pro 24, a powerful audio editing software. By downloading and running Dart Pro 24 keygen torrent, you can activate Dart Pro 24 without paying for it. However, this method is illegal and unethical, as it violates the copyright and license agreement of the software. It can also expose you to various dangers, such as viruses, malware, spyware, adware and more. Therefore, we do not recommend or endorse using Dart Pro 24 keygen torrent.

      -

      We hope this article has helped you learn more about Dart Pro 24 keygen torrent, how to get and use it. If you have any questions or feedback, please feel free to contact us. Thank you for reading and happy editing!

      -

      If you are looking for alternatives to Dart Pro 24 that can offer similar or better features and performance, you can check out some of the best alternatives that we have listed above. They are all reputable and reliable software that can edit, restore and master audio files with professional quality.

      -

      Tips and Tricks for Using Dart Pro 24

      -

      Dart Pro 24 is a powerful software that can edit, restore and master audio files with professional quality. However, to make the most of its features and tools, you need to know some tips and tricks that can help you improve your audio editing skills. Here are some of the best tips and tricks for using Dart Pro 24:

      -
        -
      • Use the presets and templates to save time and effort. Dart Pro 24 comes with a variety of presets and templates that can help you apply common effects and settings to your audio files. You can access them from the File menu or the toolbar. You can also create your own presets and templates and save them for future use.
      • -
      • Use the batch processing feature to edit multiple files at once. Dart Pro 24 allows you to apply the same effects and settings to multiple audio files at once. You can access this feature from the Tools menu or the toolbar. You can select the files you want to edit, choose the effects and settings you want to apply, and start the batch processing.
      • -
      • Use the spectral view to analyze and edit your audio files visually. Dart Pro 24 has a spectral view that shows you the frequency spectrum of your audio files. You can access this view from the View menu or the toolbar. You can use the spectral view to identify and remove noise, clicks, pops, hums, and other unwanted sounds from your audio files.
      • -
      • Use the noise reduction feature to remove background noise from your audio files. Dart Pro 24 has a noise reduction feature that can help you reduce or eliminate background noise from your audio files. You can access this feature from the Effects menu or the toolbar. You can select a portion of your audio file that contains only noise, capture its profile, and apply it to the rest of your audio file.
      • -
      • Use the click removal feature to remove clicks and pops from your audio files. Dart Pro 24 has a click removal feature that can help you remove clicks and pops from your audio files. You can access this feature from the Effects menu or the toolbar. You can adjust the sensitivity and duration of the click detection, and preview the results before applying them.
      • -
      -

      Conclusion

      -

      Dart Pro 24 keygen torrent is a file that can generate a serial number for Dart Pro 24, a powerful audio editing software. By downloading and running Dart Pro 24 keygen torrent, you can activate Dart Pro 24 without paying for it. However, this method is illegal and unethical, as it violates the copyright and license agreement of the software. It can also expose you to various dangers, such as viruses, malware, spyware, adware and more. Therefore, we do not recommend or endorse using Dart Pro 24 keygen torrent.

      -

      We hope this article has helped you learn more about Dart Pro 24 keygen torrent, how to get and use it. If you have any questions or feedback, please feel free to contact us. Thank you for reading and happy editing!

      -

      If you are looking for tips and tricks for using Dart Pro 24 that can help you improve your audio editing skills, you can check out some of the best tips and tricks that we have listed above. They are all practical and useful tips that can help you make the most of Dart Pro 24's features and tools.

      -

      Conclusion

      -

      Dart Pro 24 is a powerful software that allows you to edit, restore and master audio files with professional quality. It has many features and tools that can help you improve the sound of your recordings, such as noise reduction, click removal, equalization, compression, reverb and more. However, Dart Pro 24 is not a free software. You need to purchase a license to use it fully and legally. But what if you don't have the money or the willingness to pay for it? Is there a way to get Dart Pro 24 for free? The answer is yes, but it comes with some risks and challenges. In this article, we have shown you how to get and use Dart Pro 24 keygen torrent, a file that can generate a valid serial number for the software.

      -

      However, we have also warned you about the dangers and consequences of using Dart Pro 24 keygen torrent. This method is illegal and unethical, as it violates the copyright and license agreement of the software. It can also expose you to various threats, such as viruses, malware, spyware, adware and more. Therefore, we do not recommend or endorse using Dart Pro 24 keygen torrent.

      -

      We hope this article has helped you learn more about Dart Pro 24 keygen torrent, how to get and use it. If you have any questions or feedback, please feel free to contact us. Thank you for reading and happy editing!

      -

      If you are looking for alternatives to Dart Pro 24 that can offer similar or better features and performance, or tips and tricks for using Dart Pro 24 that can help you improve your audio editing skills, you can check out some of the best alternatives and tips that we have listed in this article. They are all reputable and reliable software or practical and useful tips that can help you edit, restore and master your audio files with professional quality.

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/bioriAsaeru/text-to-voice/Download Starrcade Full Movie In Italian Dubbed In Mp4 The Ultimate Guide To The Greatest Wrestling Spectacle Ever.md b/spaces/bioriAsaeru/text-to-voice/Download Starrcade Full Movie In Italian Dubbed In Mp4 The Ultimate Guide To The Greatest Wrestling Spectacle Ever.md deleted file mode 100644 index 52822ff1702dbcb72b2e78a37a02ea2b1c10b074..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Download Starrcade Full Movie In Italian Dubbed In Mp4 The Ultimate Guide To The Greatest Wrestling Spectacle Ever.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Download Starrcade Full Movie In Italian Dubbed In Mp4


      DOWNLOAD ✦✦✦ https://urloso.com/2uyPql



      -
      - aaccfb2cb3
      -
      -
      -

      diff --git a/spaces/bioriAsaeru/text-to-voice/James Bond Skyfall Movie Tamil Dubbed Download Enjoy the Action-Packed Adventure of 007.md b/spaces/bioriAsaeru/text-to-voice/James Bond Skyfall Movie Tamil Dubbed Download Enjoy the Action-Packed Adventure of 007.md deleted file mode 100644 index f91321e2878df07c891a0ba5af9cf9fed0cffd87..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/James Bond Skyfall Movie Tamil Dubbed Download Enjoy the Action-Packed Adventure of 007.md +++ /dev/null @@ -1,14 +0,0 @@ - -

      daniolys 19191a764c
      -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42
      [ -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42 ]
      [ -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42 ]
      [ -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42 ]
      link= -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42
      link= -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42
      link= -bond-007-skyfall-full-movie-free-download-in-tamil-dubbed-hd42

      -

      James Bond Skyfall Movie Tamil Dubbed Download


      DOWNLOAD --->>> https://urloso.com/2uyRpK



      -

      ivanocta 19191a764c
      -tamil-movie-download-dvdrip-torrent
      [ -tamil-movie-download-dvdrip-torrent ]
      [ -tamil-movie-download-dvdrip-torrent ]
      [ -tamil-movie-download-dvdrip-torrent ]
      link= -tamil-movie-download-dvdrip-torrent
      link= -tamil-movie-download-dvdrip-torrent
      link= -tamil-movie-download-dvdrip-torrent

      -

      bots half-life - jumbot 2.4.zip
      sawer fl studio crack version
      Cubase LE AI Elements 8035 Keygen
      XXX Child Porn STOLEN ILLEGAL TAPE
      thiruvaimozhi meaning in tamil pdf download
      Purani Jeans full movie hd 720p download
      masino extensions for phpmaker 14
      2 Sakura no Mori Dreamers 2 Torrent Download [pack]
      Yanpai Simulator full crack
      4Videosoft Screen Capture 1.1.28 Crack

      -

      segredos do lugar secreto pdf download
      iwe egbogi iwosan pdf 13
      download Sirf Tum songs in hindi
      Fifa 10 Crack Razor1911 14
      avatar 2 full movie download torrent
      100 Days - Hundred Days tamil movie download 720p hd
      Download Surah As Sajdah Pdf Printer
      doraemon ringtone mp3 free download in hindi
      the 3 A.M. full movie in hindi hd 1080p download
      Download Saifurs Mba Admission Guide

      -

      midi lagu barat
      Ghost Win 7 Pro Sp1 x86 x64 Clean Auto Full Drivers Activated
      a Sholay 3D movie download
      Animel pig sex with girl 3gp mp4 in zoo
      the grits my life be like zippy
      Doraemon Tagalog Version Gma 7 Full Episodes 17 17
      velai illa pattathari full movie download tamilrockers malayalam
      Alan Wake hack pc
      American Accent Training By Ann Cook 3rd Edition
      Gymnastic Bodies Foundation One Pdf

      -

      -

      maya movie download tamilgun new movies
      answers key payroll accounting project chapter 7.30
      Naam Gum Jayega of love movie download
      Peter Fox-Stadtaffe full album zip
      FSX Qualitywings 757 .EXE with serial
      127 Hours dual audio in hindi 720p movie
      flexisign pro 10 keygen torrent
      connexions methode de francais niveau 2 pdf free 24
      Broadchurch.Season.1-2.S01-S02.1080p.BluRay.x264-SHORTBREHD.[RICK]
      Ram Lakhan hindi movie full download utorrent movies

      -

      mapfactor navigator tomtom maps cracked
      download drake so far gone ep zip
      Azhar in hindi 720p torrent download
      Corel Roxio Creator NXT Pro 8v21.20.55.0 SP2 new verson cherk Serial Key keygen
      prog12z programmer v 1.67
      Garth Brooks-Double Live (CD 1) full album zip
      SIGERSHADERS MR Material Presets Pro v2.5.0.1 For 3ds Max 2010 - .rar
      renamon hentai mugengolkes
      17 habaib berpengaruh di indonesia pdf freegolkes
      thani oruvan tamil full movie hd 1080p

      -

      Download Driver Axioo Neon Cnw E4121
      I doser v5 premium all doses free
      FSX - Friendly FMC Pack V1.5 New Version crack free
      thadaiyara thaakka movie download hd
      Dumb Little Creatures apk download
      ampsa multimatch amplifier design wizard.v9.5(adw.v9.5) 101
      VAJUKA FULL MARATHI MOVE DADA KONDKE
      ParTEDIT32.zip
      nalayira divya prabandham tamil pdf free download
      solucionario vibraciones y ondas a p french

      -

      Trey Songz, Ready full album zip
      vijeo designer 6.1 download torrent
      El Dia De Los Muertos downloads torrent
      U Me Aur Hum man 3 movie free download in hindi hd 720p
      Kyaa Kool Hai Hum man 3 dubbed in hindi download mp4
      The Happening movie in hindi dubbed download movies
      3d shota boys image board
      free download taal hindi movie mp3 songs
      X-Men: Apocalypse (English) 2 full movie download in 720p hd
      xforce keygen autocad 2015 32 bit download

      aaccfb2cb3
      -
      -
      \ No newline at end of file diff --git a/spaces/boomsss/gamedayspx/getDailyData.py b/spaces/boomsss/gamedayspx/getDailyData.py deleted file mode 100644 index 578ae033086a2e04724687d03b64049a234e8bb4..0000000000000000000000000000000000000000 --- a/spaces/boomsss/gamedayspx/getDailyData.py +++ /dev/null @@ -1,278 +0,0 @@ -import pandas as pd -import pandas_datareader as pdr -import numpy as np -import yfinance as yf -import requests -from bs4 import BeautifulSoup -from typing import List -from tqdm import tqdm -import os -import datetime -import json -from sqlalchemy import create_engine - -data_start_date = '2018-07-01' - -def get_daily(mode='daily', periods_30m=None): - ''' - Method to get daily data and create daily features. Optionally append intra data if specified. - `mode`: 'daily' or 'intra'. - `periods_30m`: How many 30m periods to bring in. Only specify if mode == 'intra'. - ''' - - vix = yf.Ticker('^VIX') - vvix = yf.Ticker('^VVIX') - spx = yf.Ticker('^GSPC') - - prices_vix = vix.history(start=data_start_date, interval='1d') - prices_vvix = vvix.history(start=data_start_date, interval='1d') - prices_spx = spx.history(start=data_start_date, interval='1d') - - prices_spx['index'] = [str(x).split()[0] for x in prices_spx.index] - prices_spx['index'] = pd.to_datetime(prices_spx['index']).dt.date - prices_spx.index = prices_spx['index'] - prices_spx = prices_spx.drop(columns='index') - prices_spx.index = pd.DatetimeIndex(prices_spx.index) - - prices_vix['index'] = [str(x).split()[0] for x in prices_vix.index] - prices_vix['index'] = pd.to_datetime(prices_vix['index']).dt.date - prices_vix.index = prices_vix['index'] - prices_vix = prices_vix.drop(columns='index') - prices_vix.index = pd.DatetimeIndex(prices_vix.index) - - prices_vvix['index'] = [str(x).split()[0] for x in prices_vvix.index] - prices_vvix['index'] = pd.to_datetime(prices_vvix['index']).dt.date - prices_vvix.index = prices_vvix['index'] - prices_vvix = prices_vvix.drop(columns='index') - prices_vvix.index = pd.DatetimeIndex(prices_vvix.index) - - if mode == 'intra': - from getIntraData import get_intra - df_intra = get_intra(periods_30m) - data = prices_spx.merge(df_intra, left_index=True, right_index=True) - else: - data = prices_spx.copy() - - data = data.merge(prices_vix[['Open','High','Low','Close']], left_index=True, right_index=True, suffixes=['','_VIX']) - data = data.merge(prices_vvix[['Open','High','Low','Close']], left_index=True, right_index=True, suffixes=['','_VVIX']) - - # Features - data['PrevClose'] = data['Close'].shift(1) - data['Perf5Day'] = data['Close'] > data['Close'].shift(5) - data['Perf5Day_n1'] = data['Perf5Day'].shift(1) - data['Perf5Day_n1'] = data['Perf5Day_n1'].astype(bool) - data['GreenDay'] = (data['Close'] > data['PrevClose']) * 1 - data['RedDay'] = (data['Close'] <= data['PrevClose']) * 1 - - data['VIX5Day'] = data['Close_VIX'] > data['Close_VIX'].shift(5) - data['VIX5Day_n1'] = data['VIX5Day'].astype(bool) - - data['VVIX5Day'] = data['Close_VVIX'] > data['Close_VVIX'].shift(5) - data['VVIX5Day_n1'] = data['VVIX5Day'].astype(bool) - - data['VIXOpen'] = data['Open_VIX'] > data['Close_VIX'].shift(1) - data['VVIXOpen'] = data['Open_VVIX'] > data['Close_VVIX'].shift(1) - data['VIXOpen'] = data['VIXOpen'].astype(bool) - data['VVIXOpen'] = data['VVIXOpen'].astype(bool) - - data['Range'] = data[['Open','High']].max(axis=1) - data[['Low','Open']].min(axis=1) # Current day range in points - data['RangePct'] = data['Range'] / data['Close'] - data['VIXLevel'] = pd.qcut(data['Close_VIX'], 4) - data['OHLC4_VIX'] = data[['Open_VIX','High_VIX','Low_VIX','Close_VIX']].mean(axis=1) - data['OHLC4'] = data[['Open','High','Low','Close']].mean(axis=1) - data['OHLC4_Trend'] = data['OHLC4'] > data['OHLC4'].shift(1) - data['OHLC4_Trend'] = data['OHLC4_Trend'].astype(bool) - data['OHLC4_Trend_n1'] = data['OHLC4_Trend'].shift(1) - data['OHLC4_Trend_n1'] = data['OHLC4_Trend_n1'].astype(float) - data['OHLC4_Trend_n2'] = data['OHLC4_Trend'].shift(1) - data['OHLC4_Trend_n2'] = data['OHLC4_Trend_n2'].astype(float) - data['RangePct_n1'] = data['RangePct'].shift(1) - data['RangePct_n2'] = data['RangePct'].shift(2) - data['OHLC4_VIX_n1'] = data['OHLC4_VIX'].shift(1) - data['OHLC4_VIX_n2'] = data['OHLC4_VIX'].shift(2) - data['CurrentGap'] = (data['Open'] - data['PrevClose']) / data['PrevClose'] - data['CurrentGapHist'] = data['CurrentGap'].copy() - data['CurrentGap'] = data['CurrentGap'].shift(-1) - data['DayOfWeek'] = pd.to_datetime(data.index) - data['DayOfWeek'] = data['DayOfWeek'].dt.day - - # Target -- the next day's low - data['Target'] = (data['OHLC4'] / data['PrevClose']) - 1 - data['Target'] = data['Target'].shift(-1) - # data['Target'] = data['RangePct'].shift(-1) - - # Target for clf -- whether tomorrow will close above or below today's close - data['Target_clf'] = data['Close'] > data['PrevClose'] - data['Target_clf'] = data['Target_clf'].shift(-1) - data['DayOfWeek'] = pd.to_datetime(data.index) - data['Quarter'] = data['DayOfWeek'].dt.quarter - data['DayOfWeek'] = data['DayOfWeek'].dt.weekday - - # Calculate up - data['up'] = 100 * (data['High'].shift(1) - data['Open'].shift(1)) / data['Close'].shift(1) - - # Calculate upSD - data['upSD'] = data['up'].rolling(30).std(ddof=0) - - # Calculate aveUp - data['aveUp'] = data['up'].rolling(30).mean() - data['H1'] = data['Open'] + (data['aveUp'] / 100) * data['Open'] - data['H2'] = data['Open'] + ((data['aveUp'] + data['upSD']) / 100) * data['Open'] - data['down'] = 100 * (data['Open'].shift(1) - data['Low'].shift(1)) / data['Close'].shift(1) - data['downSD'] = data['down'].rolling(30).std(ddof=0) - data['aveDown'] = data['down'].rolling(30).mean() - data['L1'] = data['Open'] - (data['aveDown'] / 100) * data['Open'] - data['L2'] = data['Open'] - ((data['aveDown'] + data['downSD']) / 100) * data['Open'] - - data = data.assign( - L1Touch = lambda x: x['Low'] < x['L1'], - L2Touch = lambda x: x['Low'] < x['L2'], - H1Touch = lambda x: x['High'] > x['H1'], - H2Touch = lambda x: x['High'] > x['H2'], - L1Break = lambda x: x['Close'] < x['L1'], - L1TouchRed = lambda x: (x['Low'] < x['L2']) & (x['Close'] < x['PrevClose']), - L2TouchL1Break = lambda x: (x['Low'] < x['L2']) & (x['Close'] < x['L1']), - L2Break = lambda x: x['Close'] < x['L2'], - H1Break = lambda x: x['Close'] > x['H1'], - H1TouchGreen = lambda x: (x['High'] > x['H1']) & (x['Close'] > x['PrevClose']), - H2TouchH1Break = lambda x: (x['High'] > x['H2']) & (x['Close'] > x['H1']), - H2Break = lambda x: x['Close'] > x['H2'], - OpenL1 = lambda x: np.where(x['Open'] < x['L1'], 1, 0), - OpenL2 = lambda x: np.where(x['Open'] < x['L2'], 1, 0), - OpenH1 = lambda x: np.where(x['Open'] > x['H1'], 1, 0), - OpenH2 = lambda x: np.where(x['Open'] > x['H2'], 1, 0) - ) - - data['OpenL1'] = data['OpenL1'].shift(-1) - data['OpenL2'] = data['OpenL2'].shift(-1) - data['OpenH1'] = data['OpenH1'].shift(-1) - data['OpenH2'] = data['OpenH2'].shift(-1) - - - level_cols = [ - 'L1Touch', - 'L2Touch', - 'H1Touch', - 'H2Touch', - 'L1Break', - 'L2Break', - 'H1Break', - 'H2Break' - ] - - for col in level_cols: - data[col+'Pct'] = data[col].rolling(100).mean() - # data[col+'Pct'] = data[col+'Pct'].shift(-1) - - data['H1BreakTouchPct'] = data['H1Break'].rolling(100).sum() / data['H1Touch'].rolling(100).sum() - data['H2BreakTouchPct'] = data['H2Break'].rolling(100).sum() / data['H2Touch'].rolling(100).sum() - data['L1BreakTouchPct'] = data['L1Break'].rolling(100).sum() / data['L1Touch'].rolling(100).sum() - data['L2BreakTouchPct'] = data['L2Break'].rolling(100).sum() / data['L2Touch'].rolling(100).sum() - data['L1TouchRedPct'] = data['L1TouchRed'].rolling(100).sum() / data['L1Touch'].rolling(100).sum() - data['H1TouchGreenPct'] = data['H1TouchGreen'].rolling(100).sum() / data['H1Touch'].rolling(100).sum() - - data['H1BreakH2TouchPct'] = data['H2TouchH1Break'].rolling(100).sum() / data['H2Touch'].rolling(100).sum() - data['L1BreakL2TouchPct'] = data['L2TouchL1Break'].rolling(100).sum() / data['L2Touch'].rolling(100).sum() - - if mode=='intra': - # Intraday features - data['CurrentOpen30'] = data['Open30'].shift(-1) - data['CurrentHigh30'] = data['High30'].shift(-1) - data['CurrentLow30'] = data['Low30'].shift(-1) - data['CurrentClose30'] = data['Close30'].shift(-1) - data['CurrentOHLC430'] = data[['CurrentOpen30','CurrentHigh30','CurrentLow30','CurrentClose30']].max(axis=1) - data['OHLC4_Current_Trend'] = data['CurrentOHLC430'] > data['OHLC4'] - data['OHLC4_Current_Trend'] = data['OHLC4_Current_Trend'].astype(bool) - data['HistClose30toPrevClose'] = (data['Close30'] / data['PrevClose']) - 1 - - data['CurrentCloseVIX30'] = data['Close_VIX30'].shift(-1) - data['CurrentOpenVIX30'] = data['Open_VIX30'].shift(-1) - - data['CurrentVIXTrend'] = data['CurrentCloseVIX30'] > data['Close_VIX'] - - # Open to High - data['CurrentHigh30toClose'] = (data['CurrentHigh30'] / data['Close']) - 1 - data['CurrentLow30toClose'] = (data['CurrentLow30'] / data['Close']) - 1 - data['CurrentClose30toClose'] = (data['CurrentClose30'] / data['Close']) - 1 - data['CurrentRange30'] = (data['CurrentHigh30'] - data['CurrentLow30']) / data['Close'] - data['GapFill30'] = [low <= prev_close if gap > 0 else high >= prev_close for high, low, prev_close, gap in zip(data['CurrentHigh30'], data['CurrentLow30'], data['Close'], data['CurrentGap'])] - data['CloseL1'] = np.where(data['Close30'] < data['L1'], 1, 0) - data['CloseL2'] = np.where(data['Close30'] < data['L2'], 1, 0) - data['CloseH1'] = np.where(data['Close30'] > data['H1'], 1, 0) - data['CloseH2'] = np.where(data['Close30'] > data['H2'], 1, 0) - data['CloseL1'] = data['CloseL1'].shift(-1) - data['CloseL2'] = data['CloseL2'].shift(-1) - data['CloseH1'] = data['CloseH1'].shift(-1) - data['CloseH2'] = data['CloseH2'].shift(-1) - - def get_quintiles(df, col_name, q): - return df.groupby(pd.qcut(df[col_name], q))['GreenDay'].mean() - - probas = [] - # Given the current price level - for i, pct in enumerate(data['CurrentClose30toClose']): - try: - # Split - df_q = get_quintiles(data.iloc[:i], 'HistClose30toPrevClose', 10) - for q in df_q.index: - if q.left <= pct <= q.right: - p = df_q[q] - except: - p = None - - probas.append(p) - - data['GreenProbas'] = probas - - engine = create_engine( - f"mysql+mysqldb://{os.getenv('DATABASE_USERNAME')}:" \ - f"{os.getenv('DATABASE_PASSWORD')}@{os.getenv('DATABASE_HOST')}/" \ - f"{os.getenv('DATABASE')}?ssl_ca=ca-certificates.crt&ssl_mode=VERIFY_IDENTITY" - ) - - df_releases = pd.read_sql_query('select * from releases', con=engine) - df_releases = df_releases.set_index('Datetime') - data = data.merge(df_releases, how = 'left', left_index=True, right_index=True) - - for n in tqdm(df_releases.columns, desc='Merging econ data'): - # Get the name of the release - # n = releases[rid]['name'] - # Merge the corresponding DF of the release - # data = data.merge(releases[rid]['df'], how = 'left', left_index=True, right_index=True) - # Create a column that shifts the value in the merged column up by 1 - data[f'{n}_shift'] = data[n].shift(-1) - # Fill the rest with zeroes - data[n] = data[n].fillna(0) - data[f'{n}_shift'] = data[f'{n}_shift'].fillna(0) - - data['BigNewsDay'] = data[[x for x in data.columns if '_shift' in x]].max(axis=1) - - def cumul_sum(col): - nums = [] - s = 0 - for x in col: - if x == 1: - s += 1 - elif x == 0: - s = 0 - nums.append(s) - return nums - - consec_green = cumul_sum(data['GreenDay'].values) - consec_red = cumul_sum(data['RedDay'].values) - - data['DaysGreen'] = consec_green - data['DaysRed'] = consec_red - - final_row = data.index[-2] - - if mode=='daily': - from dailyCols import model_cols - - elif mode=='intra': - from intraCols import model_cols - - df_final = data.loc[:final_row, model_cols + ['Target', 'Target_clf']] - df_final = df_final.dropna(subset=['Target','Target_clf']) - # df_final = df_final.dropna(subset=['Target','Target_clf','Perf5Day_n1']) - return data, df_final, final_row \ No newline at end of file diff --git a/spaces/brainblow/AudioCreator_Music-Audio_Generation/audiocraft/solvers/__init__.py b/spaces/brainblow/AudioCreator_Music-Audio_Generation/audiocraft/solvers/__init__.py deleted file mode 100644 index ae19f3a8c51abf469697d6affa91449d668716ba..0000000000000000000000000000000000000000 --- a/spaces/brainblow/AudioCreator_Music-Audio_Generation/audiocraft/solvers/__init__.py +++ /dev/null @@ -1,17 +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. -""" -Solvers. A Solver is a training recipe, combining the dataloaders, models, -optimizer, losses etc into a single convenient object. -""" - -# flake8: noqa -from .audiogen import AudioGenSolver -from .builders import get_solver -from .base import StandardSolver -from .compression import CompressionSolver -from .musicgen import MusicGenSolver -from .diffusion import DiffusionSolver diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/datasets/coco_panoptic.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/datasets/coco_panoptic.py deleted file mode 100644 index b8dae44317b556610d7fed39017e082d7e855956..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/datasets/coco_panoptic.py +++ /dev/null @@ -1,228 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import copy -import json -import os - -from detectron2.data import DatasetCatalog, MetadataCatalog -from detectron2.utils.file_io import PathManager - -from .coco import load_coco_json, load_sem_seg - -__all__ = ["register_coco_panoptic", "register_coco_panoptic_separated"] - - -def load_coco_panoptic_json(json_file, image_dir, gt_dir, meta): - """ - Args: - image_dir (str): path to the raw dataset. e.g., "~/coco/train2017". - gt_dir (str): path to the raw annotations. e.g., "~/coco/panoptic_train2017". - json_file (str): path to the json file. e.g., "~/coco/annotations/panoptic_train2017.json". - - Returns: - list[dict]: a list of dicts in Detectron2 standard format. (See - `Using Custom Datasets `_ ) - """ - - def _convert_category_id(segment_info, meta): - if segment_info["category_id"] in meta["thing_dataset_id_to_contiguous_id"]: - segment_info["category_id"] = meta["thing_dataset_id_to_contiguous_id"][ - segment_info["category_id"] - ] - segment_info["isthing"] = True - else: - segment_info["category_id"] = meta["stuff_dataset_id_to_contiguous_id"][ - segment_info["category_id"] - ] - segment_info["isthing"] = False - return segment_info - - with PathManager.open(json_file) as f: - json_info = json.load(f) - - ret = [] - for ann in json_info["annotations"]: - image_id = int(ann["image_id"]) - # TODO: currently we assume image and label has the same filename but - # different extension, and images have extension ".jpg" for COCO. Need - # to make image extension a user-provided argument if we extend this - # function to support other COCO-like datasets. - image_file = os.path.join(image_dir, os.path.splitext(ann["file_name"])[0] + ".jpg") - label_file = os.path.join(gt_dir, ann["file_name"]) - segments_info = [_convert_category_id(x, meta) for x in ann["segments_info"]] - ret.append( - { - "file_name": image_file, - "image_id": image_id, - "pan_seg_file_name": label_file, - "segments_info": segments_info, - } - ) - assert len(ret), f"No images found in {image_dir}!" - assert PathManager.isfile(ret[0]["file_name"]), ret[0]["file_name"] - assert PathManager.isfile(ret[0]["pan_seg_file_name"]), ret[0]["pan_seg_file_name"] - return ret - - -def register_coco_panoptic( - name, metadata, image_root, panoptic_root, panoptic_json, instances_json=None -): - """ - Register a "standard" version of COCO panoptic segmentation dataset named `name`. - The dictionaries in this registered dataset follows detectron2's standard format. - Hence it's called "standard". - - Args: - name (str): the name that identifies a dataset, - e.g. "coco_2017_train_panoptic" - metadata (dict): extra metadata associated with this dataset. - image_root (str): directory which contains all the images - panoptic_root (str): directory which contains panoptic annotation images in COCO format - panoptic_json (str): path to the json panoptic annotation file in COCO format - sem_seg_root (none): not used, to be consistent with - `register_coco_panoptic_separated`. - instances_json (str): path to the json instance annotation file - """ - panoptic_name = name - DatasetCatalog.register( - panoptic_name, - lambda: load_coco_panoptic_json(panoptic_json, image_root, panoptic_root, metadata), - ) - MetadataCatalog.get(panoptic_name).set( - panoptic_root=panoptic_root, - image_root=image_root, - panoptic_json=panoptic_json, - json_file=instances_json, - evaluator_type="coco_panoptic_seg", - ignore_label=255, - label_divisor=1000, - **metadata, - ) - - -def register_coco_panoptic_separated( - name, metadata, image_root, panoptic_root, panoptic_json, sem_seg_root, instances_json -): - """ - Register a "separated" version of COCO panoptic segmentation dataset named `name`. - The annotations in this registered dataset will contain both instance annotations and - semantic annotations, each with its own contiguous ids. Hence it's called "separated". - - It follows the setting used by the PanopticFPN paper: - - 1. The instance annotations directly come from polygons in the COCO - instances annotation task, rather than from the masks in the COCO panoptic annotations. - - The two format have small differences: - Polygons in the instance annotations may have overlaps. - The mask annotations are produced by labeling the overlapped polygons - with depth ordering. - - 2. The semantic annotations are converted from panoptic annotations, where - all "things" are assigned a semantic id of 0. - All semantic categories will therefore have ids in contiguous - range [1, #stuff_categories]. - - This function will also register a pure semantic segmentation dataset - named ``name + '_stuffonly'``. - - Args: - name (str): the name that identifies a dataset, - e.g. "coco_2017_train_panoptic" - metadata (dict): extra metadata associated with this dataset. - image_root (str): directory which contains all the images - panoptic_root (str): directory which contains panoptic annotation images - panoptic_json (str): path to the json panoptic annotation file - sem_seg_root (str): directory which contains all the ground truth segmentation annotations. - instances_json (str): path to the json instance annotation file - """ - panoptic_name = name + "_separated" - DatasetCatalog.register( - panoptic_name, - lambda: merge_to_panoptic( - load_coco_json(instances_json, image_root, panoptic_name), - load_sem_seg(sem_seg_root, image_root), - ), - ) - MetadataCatalog.get(panoptic_name).set( - panoptic_root=panoptic_root, - image_root=image_root, - panoptic_json=panoptic_json, - sem_seg_root=sem_seg_root, - json_file=instances_json, # TODO rename - evaluator_type="coco_panoptic_seg", - ignore_label=255, - **metadata, - ) - - semantic_name = name + "_stuffonly" - DatasetCatalog.register(semantic_name, lambda: load_sem_seg(sem_seg_root, image_root)) - MetadataCatalog.get(semantic_name).set( - sem_seg_root=sem_seg_root, - image_root=image_root, - evaluator_type="sem_seg", - ignore_label=255, - **metadata, - ) - - -def merge_to_panoptic(detection_dicts, sem_seg_dicts): - """ - Create dataset dicts for panoptic segmentation, by - merging two dicts using "file_name" field to match their entries. - - Args: - detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation. - sem_seg_dicts (list[dict]): lists of dicts for semantic segmentation. - - Returns: - list[dict] (one per input image): Each dict contains all (key, value) pairs from dicts in - both detection_dicts and sem_seg_dicts that correspond to the same image. - The function assumes that the same key in different dicts has the same value. - """ - results = [] - sem_seg_file_to_entry = {x["file_name"]: x for x in sem_seg_dicts} - assert len(sem_seg_file_to_entry) > 0 - - for det_dict in detection_dicts: - dic = copy.copy(det_dict) - dic.update(sem_seg_file_to_entry[dic["file_name"]]) - results.append(dic) - return results - - -if __name__ == "__main__": - """ - Test the COCO panoptic dataset loader. - - Usage: - python -m detectron2.data.datasets.coco_panoptic \ - path/to/image_root path/to/panoptic_root path/to/panoptic_json dataset_name 10 - - "dataset_name" can be "coco_2017_train_panoptic", or other - pre-registered ones - """ - from detectron2.utils.logger import setup_logger - from detectron2.utils.visualizer import Visualizer - import detectron2.data.datasets # noqa # add pre-defined metadata - import sys - from PIL import Image - import numpy as np - - logger = setup_logger(name=__name__) - assert sys.argv[4] in DatasetCatalog.list() - meta = MetadataCatalog.get(sys.argv[4]) - - dicts = load_coco_panoptic_json(sys.argv[3], sys.argv[1], sys.argv[2], meta.as_dict()) - logger.info("Done loading {} samples.".format(len(dicts))) - - dirname = "coco-data-vis" - os.makedirs(dirname, exist_ok=True) - num_imgs_to_vis = int(sys.argv[5]) - for i, d in enumerate(dicts): - img = np.array(Image.open(d["file_name"])) - visualizer = Visualizer(img, metadata=meta) - vis = visualizer.draw_dataset_dict(d) - fpath = os.path.join(dirname, os.path.basename(d["file_name"])) - vis.save(fpath) - if i + 1 >= num_imgs_to_vis: - break diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/roi_heads/keypoint_head.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/roi_heads/keypoint_head.py deleted file mode 100644 index e0acc138e72fcb188e4ffb3d156358b8ca59babf..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/roi_heads/keypoint_head.py +++ /dev/null @@ -1,272 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from typing import List -import torch -from torch import nn -from torch.nn import functional as F - -from detectron2.config import configurable -from detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate -from detectron2.structures import Instances, heatmaps_to_keypoints -from detectron2.utils.events import get_event_storage -from detectron2.utils.registry import Registry - -_TOTAL_SKIPPED = 0 - - -__all__ = [ - "ROI_KEYPOINT_HEAD_REGISTRY", - "build_keypoint_head", - "BaseKeypointRCNNHead", - "KRCNNConvDeconvUpsampleHead", -] - - -ROI_KEYPOINT_HEAD_REGISTRY = Registry("ROI_KEYPOINT_HEAD") -ROI_KEYPOINT_HEAD_REGISTRY.__doc__ = """ -Registry for keypoint heads, which make keypoint predictions from per-region features. - -The registered object will be called with `obj(cfg, input_shape)`. -""" - - -def build_keypoint_head(cfg, input_shape): - """ - Build a keypoint head from `cfg.MODEL.ROI_KEYPOINT_HEAD.NAME`. - """ - name = cfg.MODEL.ROI_KEYPOINT_HEAD.NAME - return ROI_KEYPOINT_HEAD_REGISTRY.get(name)(cfg, input_shape) - - -def keypoint_rcnn_loss(pred_keypoint_logits, instances, normalizer): - """ - Arguments: - pred_keypoint_logits (Tensor): A tensor of shape (N, K, S, S) where N is the total number - of instances in the batch, K is the number of keypoints, and S is the side length - of the keypoint heatmap. The values are spatial logits. - instances (list[Instances]): A list of M Instances, where M is the batch size. - These instances are predictions from the model - that are in 1:1 correspondence with pred_keypoint_logits. - Each Instances should contain a `gt_keypoints` field containing a `structures.Keypoint` - instance. - normalizer (float): Normalize the loss by this amount. - If not specified, we normalize by the number of visible keypoints in the minibatch. - - Returns a scalar tensor containing the loss. - """ - heatmaps = [] - valid = [] - - keypoint_side_len = pred_keypoint_logits.shape[2] - for instances_per_image in instances: - if len(instances_per_image) == 0: - continue - keypoints = instances_per_image.gt_keypoints - heatmaps_per_image, valid_per_image = keypoints.to_heatmap( - instances_per_image.proposal_boxes.tensor, keypoint_side_len - ) - heatmaps.append(heatmaps_per_image.view(-1)) - valid.append(valid_per_image.view(-1)) - - if len(heatmaps): - keypoint_targets = cat(heatmaps, dim=0) - valid = cat(valid, dim=0).to(dtype=torch.uint8) - valid = torch.nonzero(valid).squeeze(1) - - # torch.mean (in binary_cross_entropy_with_logits) doesn't - # accept empty tensors, so handle it separately - if len(heatmaps) == 0 or valid.numel() == 0: - global _TOTAL_SKIPPED - _TOTAL_SKIPPED += 1 - storage = get_event_storage() - storage.put_scalar("kpts_num_skipped_batches", _TOTAL_SKIPPED, smoothing_hint=False) - return pred_keypoint_logits.sum() * 0 - - N, K, H, W = pred_keypoint_logits.shape - pred_keypoint_logits = pred_keypoint_logits.view(N * K, H * W) - - keypoint_loss = F.cross_entropy( - pred_keypoint_logits[valid], keypoint_targets[valid], reduction="sum" - ) - - # If a normalizer isn't specified, normalize by the number of visible keypoints in the minibatch - if normalizer is None: - normalizer = valid.numel() - keypoint_loss /= normalizer - - return keypoint_loss - - -def keypoint_rcnn_inference(pred_keypoint_logits: torch.Tensor, pred_instances: List[Instances]): - """ - Post process each predicted keypoint heatmap in `pred_keypoint_logits` into (x, y, score) - and add it to the `pred_instances` as a `pred_keypoints` field. - - Args: - pred_keypoint_logits (Tensor): A tensor of shape (R, K, S, S) where R is the total number - of instances in the batch, K is the number of keypoints, and S is the side length of - the keypoint heatmap. The values are spatial logits. - pred_instances (list[Instances]): A list of N Instances, where N is the number of images. - - Returns: - None. Each element in pred_instances will contain extra "pred_keypoints" and - "pred_keypoint_heatmaps" fields. "pred_keypoints" is a tensor of shape - (#instance, K, 3) where the last dimension corresponds to (x, y, score). - The scores are larger than 0. "pred_keypoint_heatmaps" contains the raw - keypoint logits as passed to this function. - """ - # flatten all bboxes from all images together (list[Boxes] -> Rx4 tensor) - bboxes_flat = cat([b.pred_boxes.tensor for b in pred_instances], dim=0) - - pred_keypoint_logits = pred_keypoint_logits.detach() - keypoint_results = heatmaps_to_keypoints(pred_keypoint_logits, bboxes_flat.detach()) - num_instances_per_image = [len(i) for i in pred_instances] - keypoint_results = keypoint_results[:, :, [0, 1, 3]].split(num_instances_per_image, dim=0) - heatmap_results = pred_keypoint_logits.split(num_instances_per_image, dim=0) - - for keypoint_results_per_image, heatmap_results_per_image, instances_per_image in zip( - keypoint_results, heatmap_results, pred_instances - ): - # keypoint_results_per_image is (num instances)x(num keypoints)x(x, y, score) - # heatmap_results_per_image is (num instances)x(num keypoints)x(side)x(side) - instances_per_image.pred_keypoints = keypoint_results_per_image - instances_per_image.pred_keypoint_heatmaps = heatmap_results_per_image - - -class BaseKeypointRCNNHead(nn.Module): - """ - Implement the basic Keypoint R-CNN losses and inference logic described in - Sec. 5 of :paper:`Mask R-CNN`. - """ - - @configurable - def __init__(self, *, num_keypoints, loss_weight=1.0, loss_normalizer=1.0): - """ - NOTE: this interface is experimental. - - Args: - num_keypoints (int): number of keypoints to predict - loss_weight (float): weight to multiple on the keypoint loss - loss_normalizer (float or str): - If float, divide the loss by `loss_normalizer * #images`. - If 'visible', the loss is normalized by the total number of - visible keypoints across images. - """ - super().__init__() - self.num_keypoints = num_keypoints - self.loss_weight = loss_weight - assert loss_normalizer == "visible" or isinstance(loss_normalizer, float), loss_normalizer - self.loss_normalizer = loss_normalizer - - @classmethod - def from_config(cls, cfg, input_shape): - ret = { - "loss_weight": cfg.MODEL.ROI_KEYPOINT_HEAD.LOSS_WEIGHT, - "num_keypoints": cfg.MODEL.ROI_KEYPOINT_HEAD.NUM_KEYPOINTS, - } - normalize_by_visible = ( - cfg.MODEL.ROI_KEYPOINT_HEAD.NORMALIZE_LOSS_BY_VISIBLE_KEYPOINTS - ) # noqa - if not normalize_by_visible: - batch_size_per_image = cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE - positive_sample_fraction = cfg.MODEL.ROI_HEADS.POSITIVE_FRACTION - ret["loss_normalizer"] = ( - ret["num_keypoints"] * batch_size_per_image * positive_sample_fraction - ) - else: - ret["loss_normalizer"] = "visible" - return ret - - def forward(self, x, instances: List[Instances]): - """ - Args: - x: input 4D region feature(s) provided by :class:`ROIHeads`. - instances (list[Instances]): contains the boxes & labels corresponding - to the input features. - Exact format is up to its caller to decide. - Typically, this is the foreground instances in training, with - "proposal_boxes" field and other gt annotations. - In inference, it contains boxes that are already predicted. - - Returns: - A dict of losses if in training. The predicted "instances" if in inference. - """ - x = self.layers(x) - if self.training: - num_images = len(instances) - normalizer = ( - None if self.loss_normalizer == "visible" else num_images * self.loss_normalizer - ) - return { - "loss_keypoint": keypoint_rcnn_loss(x, instances, normalizer=normalizer) - * self.loss_weight - } - else: - keypoint_rcnn_inference(x, instances) - return instances - - def layers(self, x): - """ - Neural network layers that makes predictions from regional input features. - """ - raise NotImplementedError - - -# 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_KEYPOINT_HEAD_REGISTRY.register() -class KRCNNConvDeconvUpsampleHead(BaseKeypointRCNNHead, nn.Sequential): - """ - A standard keypoint head containing a series of 3x3 convs, followed by - a transpose convolution and bilinear interpolation for upsampling. - It is described in Sec. 5 of :paper:`Mask R-CNN`. - """ - - @configurable - def __init__(self, input_shape, *, num_keypoints, conv_dims, **kwargs): - """ - NOTE: this interface is experimental. - - Args: - input_shape (ShapeSpec): shape of the input feature - conv_dims: an iterable of output channel counts for each conv in the head - e.g. (512, 512, 512) for three convs outputting 512 channels. - """ - super().__init__(num_keypoints=num_keypoints, **kwargs) - - # default up_scale to 2.0 (this can be made an option) - up_scale = 2.0 - in_channels = input_shape.channels - - for idx, layer_channels in enumerate(conv_dims, 1): - module = Conv2d(in_channels, layer_channels, 3, stride=1, padding=1) - self.add_module("conv_fcn{}".format(idx), module) - self.add_module("conv_fcn_relu{}".format(idx), nn.ReLU()) - in_channels = layer_channels - - deconv_kernel = 4 - self.score_lowres = ConvTranspose2d( - in_channels, num_keypoints, deconv_kernel, stride=2, padding=deconv_kernel // 2 - 1 - ) - self.up_scale = up_scale - - for name, param in self.named_parameters(): - if "bias" in name: - nn.init.constant_(param, 0) - elif "weight" in name: - # Caffe2 implementation uses MSRAFill, which in fact - # corresponds to kaiming_normal_ in PyTorch - nn.init.kaiming_normal_(param, mode="fan_out", nonlinearity="relu") - - @classmethod - def from_config(cls, cfg, input_shape): - ret = super().from_config(cfg, input_shape) - ret["input_shape"] = input_shape - ret["conv_dims"] = cfg.MODEL.ROI_KEYPOINT_HEAD.CONV_DIMS - return ret - - def layers(self, x): - for layer in self: - x = layer(x) - x = interpolate(x, scale_factor=self.up_scale, mode="bilinear", align_corners=False) - return x diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/utils/collect_env.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/utils/collect_env.py deleted file mode 100644 index 2846d7a56c3efbdec5ccc5a9c4890ff47cff9512..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/utils/collect_env.py +++ /dev/null @@ -1,246 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import importlib -import numpy as np -import os -import re -import subprocess -import sys -from collections import defaultdict -import PIL -import torch -import torchvision -from tabulate import tabulate - -__all__ = ["collect_env_info"] - - -def collect_torch_env(): - try: - import torch.__config__ - - return torch.__config__.show() - except ImportError: - # compatible with older versions of pytorch - from torch.utils.collect_env import get_pretty_env_info - - return get_pretty_env_info() - - -def get_env_module(): - var_name = "DETECTRON2_ENV_MODULE" - return var_name, os.environ.get(var_name, "") - - -def detect_compute_compatibility(CUDA_HOME, so_file): - try: - cuobjdump = os.path.join(CUDA_HOME, "bin", "cuobjdump") - if os.path.isfile(cuobjdump): - output = subprocess.check_output( - "'{}' --list-elf '{}'".format(cuobjdump, so_file), shell=True - ) - output = output.decode("utf-8").strip().split("\n") - arch = [] - for line in output: - line = re.findall(r"\.sm_([0-9]*)\.", line)[0] - arch.append(".".join(line)) - arch = sorted(set(arch)) - return ", ".join(arch) - else: - return so_file + "; cannot find cuobjdump" - except Exception: - # unhandled failure - return so_file - - -def collect_env_info(): - has_gpu = torch.cuda.is_available() # true for both CUDA & ROCM - torch_version = torch.__version__ - - # NOTE that CUDA_HOME/ROCM_HOME could be None even when CUDA runtime libs are functional - from torch.utils.cpp_extension import CUDA_HOME, ROCM_HOME - - has_rocm = False - if (getattr(torch.version, "hip", None) is not None) and (ROCM_HOME is not None): - has_rocm = True - has_cuda = has_gpu and (not has_rocm) - - data = [] - data.append(("sys.platform", sys.platform)) # check-template.yml depends on it - data.append(("Python", sys.version.replace("\n", ""))) - data.append(("numpy", np.__version__)) - - try: - import detectron2 # noqa - - data.append( - ("detectron2", detectron2.__version__ + " @" + os.path.dirname(detectron2.__file__)) - ) - except ImportError: - data.append(("detectron2", "failed to import")) - except AttributeError: - data.append(("detectron2", "imported a wrong installation")) - - try: - import detectron2._C as _C - except ImportError as e: - data.append(("detectron2._C", f"not built correctly: {e}")) - - # print system compilers when extension fails to build - if sys.platform != "win32": # don't know what to do for windows - try: - # this is how torch/utils/cpp_extensions.py choose compiler - cxx = os.environ.get("CXX", "c++") - cxx = subprocess.check_output("'{}' --version".format(cxx), shell=True) - cxx = cxx.decode("utf-8").strip().split("\n")[0] - except subprocess.SubprocessError: - cxx = "Not found" - data.append(("Compiler ($CXX)", cxx)) - - if has_cuda and CUDA_HOME is not None: - try: - nvcc = os.path.join(CUDA_HOME, "bin", "nvcc") - nvcc = subprocess.check_output("'{}' -V".format(nvcc), shell=True) - nvcc = nvcc.decode("utf-8").strip().split("\n")[-1] - except subprocess.SubprocessError: - nvcc = "Not found" - data.append(("CUDA compiler", nvcc)) - if has_cuda and sys.platform != "win32": - try: - so_file = importlib.util.find_spec("detectron2._C").origin - except (ImportError, AttributeError): - pass - else: - data.append( - ("detectron2 arch flags", detect_compute_compatibility(CUDA_HOME, so_file)) - ) - else: - # print compilers that are used to build extension - data.append(("Compiler", _C.get_compiler_version())) - data.append(("CUDA compiler", _C.get_cuda_version())) # cuda or hip - if has_cuda and getattr(_C, "has_cuda", lambda: True)(): - data.append( - ("detectron2 arch flags", detect_compute_compatibility(CUDA_HOME, _C.__file__)) - ) - - data.append(get_env_module()) - data.append(("PyTorch", torch_version + " @" + os.path.dirname(torch.__file__))) - data.append(("PyTorch debug build", torch.version.debug)) - try: - data.append(("torch._C._GLIBCXX_USE_CXX11_ABI", torch._C._GLIBCXX_USE_CXX11_ABI)) - except Exception: - pass - - if not has_gpu: - has_gpu_text = "No: torch.cuda.is_available() == False" - else: - has_gpu_text = "Yes" - data.append(("GPU available", has_gpu_text)) - if has_gpu: - devices = defaultdict(list) - for k in range(torch.cuda.device_count()): - cap = ".".join((str(x) for x in torch.cuda.get_device_capability(k))) - name = torch.cuda.get_device_name(k) + f" (arch={cap})" - devices[name].append(str(k)) - for name, devids in devices.items(): - data.append(("GPU " + ",".join(devids), name)) - - if has_rocm: - msg = " - invalid!" if not (ROCM_HOME and os.path.isdir(ROCM_HOME)) else "" - data.append(("ROCM_HOME", str(ROCM_HOME) + msg)) - else: - try: - from torch.utils.collect_env import get_nvidia_driver_version, run as _run - - data.append(("Driver version", get_nvidia_driver_version(_run))) - except Exception: - pass - msg = " - invalid!" if not (CUDA_HOME and os.path.isdir(CUDA_HOME)) else "" - data.append(("CUDA_HOME", str(CUDA_HOME) + msg)) - - cuda_arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST", None) - if cuda_arch_list: - data.append(("TORCH_CUDA_ARCH_LIST", cuda_arch_list)) - data.append(("Pillow", PIL.__version__)) - - try: - data.append( - ( - "torchvision", - str(torchvision.__version__) + " @" + os.path.dirname(torchvision.__file__), - ) - ) - if has_cuda: - try: - torchvision_C = importlib.util.find_spec("torchvision._C").origin - msg = detect_compute_compatibility(CUDA_HOME, torchvision_C) - data.append(("torchvision arch flags", msg)) - except (ImportError, AttributeError): - data.append(("torchvision._C", "Not found")) - except AttributeError: - data.append(("torchvision", "unknown")) - - try: - import fvcore - - data.append(("fvcore", fvcore.__version__)) - except (ImportError, AttributeError): - pass - - try: - import iopath - - data.append(("iopath", iopath.__version__)) - except (ImportError, AttributeError): - pass - - try: - import cv2 - - data.append(("cv2", cv2.__version__)) - except (ImportError, AttributeError): - data.append(("cv2", "Not found")) - env_str = tabulate(data) + "\n" - env_str += collect_torch_env() - return env_str - - -def test_nccl_ops(): - num_gpu = torch.cuda.device_count() - if os.access("/tmp", os.W_OK): - import torch.multiprocessing as mp - - dist_url = "file:///tmp/nccl_tmp_file" - print("Testing NCCL connectivity ... this should not hang.") - mp.spawn(_test_nccl_worker, nprocs=num_gpu, args=(num_gpu, dist_url), daemon=False) - print("NCCL succeeded.") - - -def _test_nccl_worker(rank, num_gpu, dist_url): - import torch.distributed as dist - - dist.init_process_group(backend="NCCL", init_method=dist_url, rank=rank, world_size=num_gpu) - dist.barrier(device_ids=[rank]) - - -if __name__ == "__main__": - try: - from detectron2.utils.collect_env import collect_env_info as f - - print(f()) - except ImportError: - print(collect_env_info()) - - if torch.cuda.is_available(): - num_gpu = torch.cuda.device_count() - for k in range(num_gpu): - device = f"cuda:{k}" - try: - x = torch.tensor([1, 2.0], dtype=torch.float32) - x = x.to(device) - except Exception as e: - print( - f"Unable to copy tensor to device={device}: {e}. " - "Your CUDA environment is broken." - ) - if num_gpu > 1: - test_nccl_ops() diff --git a/spaces/caffeinum/VToonify/vtoonify/model/simple_augment.py b/spaces/caffeinum/VToonify/vtoonify/model/simple_augment.py deleted file mode 100644 index 515d272734e4d10d346461965099a86e53f58701..0000000000000000000000000000000000000000 --- a/spaces/caffeinum/VToonify/vtoonify/model/simple_augment.py +++ /dev/null @@ -1,468 +0,0 @@ -# almost the same as model.stylegan.non_leaking -# we only modify the parameters in sample_affine() to make the transformations mild - -import math - -import torch -from torch import autograd -from torch.nn import functional as F -import numpy as np - -from model.stylegan.distributed import reduce_sum -from model.stylegan.op import upfirdn2d - - -class AdaptiveAugment: - def __init__(self, ada_aug_target, ada_aug_len, update_every, device): - self.ada_aug_target = ada_aug_target - self.ada_aug_len = ada_aug_len - self.update_every = update_every - - self.ada_update = 0 - self.ada_aug_buf = torch.tensor([0.0, 0.0], device=device) - self.r_t_stat = 0 - self.ada_aug_p = 0 - - @torch.no_grad() - def tune(self, real_pred): - self.ada_aug_buf += torch.tensor( - (torch.sign(real_pred).sum().item(), real_pred.shape[0]), - device=real_pred.device, - ) - self.ada_update += 1 - - if self.ada_update % self.update_every == 0: - self.ada_aug_buf = reduce_sum(self.ada_aug_buf) - pred_signs, n_pred = self.ada_aug_buf.tolist() - - self.r_t_stat = pred_signs / n_pred - - if self.r_t_stat > self.ada_aug_target: - sign = 1 - - else: - sign = -1 - - self.ada_aug_p += sign * n_pred / self.ada_aug_len - self.ada_aug_p = min(1, max(0, self.ada_aug_p)) - self.ada_aug_buf.mul_(0) - self.ada_update = 0 - - return self.ada_aug_p - - -SYM6 = ( - 0.015404109327027373, - 0.0034907120842174702, - -0.11799011114819057, - -0.048311742585633, - 0.4910559419267466, - 0.787641141030194, - 0.3379294217276218, - -0.07263752278646252, - -0.021060292512300564, - 0.04472490177066578, - 0.0017677118642428036, - -0.007800708325034148, -) - - -def translate_mat(t_x, t_y, device="cpu"): - batch = t_x.shape[0] - - mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1) - translate = torch.stack((t_x, t_y), 1) - mat[:, :2, 2] = translate - - return mat - - -def rotate_mat(theta, device="cpu"): - batch = theta.shape[0] - - mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1) - sin_t = torch.sin(theta) - cos_t = torch.cos(theta) - rot = torch.stack((cos_t, -sin_t, sin_t, cos_t), 1).view(batch, 2, 2) - mat[:, :2, :2] = rot - - return mat - - -def scale_mat(s_x, s_y, device="cpu"): - batch = s_x.shape[0] - - mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1) - mat[:, 0, 0] = s_x - mat[:, 1, 1] = s_y - - return mat - - -def translate3d_mat(t_x, t_y, t_z): - batch = t_x.shape[0] - - mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - translate = torch.stack((t_x, t_y, t_z), 1) - mat[:, :3, 3] = translate - - return mat - - -def rotate3d_mat(axis, theta): - batch = theta.shape[0] - - u_x, u_y, u_z = axis - - eye = torch.eye(3).unsqueeze(0) - cross = torch.tensor([(0, -u_z, u_y), (u_z, 0, -u_x), (-u_y, u_x, 0)]).unsqueeze(0) - outer = torch.tensor(axis) - outer = (outer.unsqueeze(1) * outer).unsqueeze(0) - - sin_t = torch.sin(theta).view(-1, 1, 1) - cos_t = torch.cos(theta).view(-1, 1, 1) - - rot = cos_t * eye + sin_t * cross + (1 - cos_t) * outer - - eye_4 = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - eye_4[:, :3, :3] = rot - - return eye_4 - - -def scale3d_mat(s_x, s_y, s_z): - batch = s_x.shape[0] - - mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - mat[:, 0, 0] = s_x - mat[:, 1, 1] = s_y - mat[:, 2, 2] = s_z - - return mat - - -def luma_flip_mat(axis, i): - batch = i.shape[0] - - eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - axis = torch.tensor(axis + (0,)) - flip = 2 * torch.ger(axis, axis) * i.view(-1, 1, 1) - - return eye - flip - - -def saturation_mat(axis, i): - batch = i.shape[0] - - eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1) - axis = torch.tensor(axis + (0,)) - axis = torch.ger(axis, axis) - saturate = axis + (eye - axis) * i.view(-1, 1, 1) - - return saturate - - -def lognormal_sample(size, mean=0, std=1, device="cpu"): - return torch.empty(size, device=device).log_normal_(mean=mean, std=std) - - -def category_sample(size, categories, device="cpu"): - category = torch.tensor(categories, device=device) - sample = torch.randint(high=len(categories), size=(size,), device=device) - - return category[sample] - - -def uniform_sample(size, low, high, device="cpu"): - return torch.empty(size, device=device).uniform_(low, high) - - -def normal_sample(size, mean=0, std=1, device="cpu"): - return torch.empty(size, device=device).normal_(mean, std) - - -def bernoulli_sample(size, p, device="cpu"): - return torch.empty(size, device=device).bernoulli_(p) - - -def random_mat_apply(p, transform, prev, eye, device="cpu"): - size = transform.shape[0] - select = bernoulli_sample(size, p, device=device).view(size, 1, 1) - select_transform = select * transform + (1 - select) * eye - - return select_transform @ prev - - -def sample_affine(p, size, height, width, device="cpu"): - G = torch.eye(3, device=device).unsqueeze(0).repeat(size, 1, 1) - eye = G - - # flip - param = category_sample(size, (0, 1)) - Gc = scale_mat(1 - 2.0 * param, torch.ones(size), device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('flip', G, scale_mat(1 - 2.0 * param, torch.ones(size)), sep='\n') - - # 90 rotate - #param = category_sample(size, (0, 3)) - #Gc = rotate_mat(-math.pi / 2 * param, device=device) - #G = random_mat_apply(p, Gc, G, eye, device=device) - # print('90 rotate', G, rotate_mat(-math.pi / 2 * param), sep='\n') - - # integer translate - param = uniform_sample(size, -0.125, 0.125) - param_height = torch.round(param * height) / height - param_width = torch.round(param * width) / width - Gc = translate_mat(param_width, param_height, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('integer translate', G, translate_mat(param_width, param_height), sep='\n') - - # isotropic scale - param = lognormal_sample(size, std=0.1 * math.log(2)) - Gc = scale_mat(param, param, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('isotropic scale', G, scale_mat(param, param), sep='\n') - - p_rot = 1 - math.sqrt(1 - p) - - # pre-rotate - param = uniform_sample(size, -math.pi * 0.25, math.pi * 0.25) - Gc = rotate_mat(-param, device=device) - G = random_mat_apply(p_rot, Gc, G, eye, device=device) - # print('pre-rotate', G, rotate_mat(-param), sep='\n') - - # anisotropic scale - param = lognormal_sample(size, std=0.1 * math.log(2)) - Gc = scale_mat(param, 1 / param, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('anisotropic scale', G, scale_mat(param, 1 / param), sep='\n') - - # post-rotate - param = uniform_sample(size, -math.pi * 0.25, math.pi * 0.25) - Gc = rotate_mat(-param, device=device) - G = random_mat_apply(p_rot, Gc, G, eye, device=device) - # print('post-rotate', G, rotate_mat(-param), sep='\n') - - # fractional translate - param = normal_sample(size, std=0.125) - Gc = translate_mat(param, param, device=device) - G = random_mat_apply(p, Gc, G, eye, device=device) - # print('fractional translate', G, translate_mat(param, param), sep='\n') - - return G - - -def sample_color(p, size): - C = torch.eye(4).unsqueeze(0).repeat(size, 1, 1) - eye = C - axis_val = 1 / math.sqrt(3) - axis = (axis_val, axis_val, axis_val) - - # brightness - param = normal_sample(size, std=0.2) - Cc = translate3d_mat(param, param, param) - C = random_mat_apply(p, Cc, C, eye) - - # contrast - param = lognormal_sample(size, std=0.5 * math.log(2)) - Cc = scale3d_mat(param, param, param) - C = random_mat_apply(p, Cc, C, eye) - - # luma flip - param = category_sample(size, (0, 1)) - Cc = luma_flip_mat(axis, param) - C = random_mat_apply(p, Cc, C, eye) - - # hue rotation - param = uniform_sample(size, -math.pi, math.pi) - Cc = rotate3d_mat(axis, param) - C = random_mat_apply(p, Cc, C, eye) - - # saturation - param = lognormal_sample(size, std=1 * math.log(2)) - Cc = saturation_mat(axis, param) - C = random_mat_apply(p, Cc, C, eye) - - return C - - -def make_grid(shape, x0, x1, y0, y1, device): - n, c, h, w = shape - grid = torch.empty(n, h, w, 3, device=device) - grid[:, :, :, 0] = torch.linspace(x0, x1, w, device=device) - grid[:, :, :, 1] = torch.linspace(y0, y1, h, device=device).unsqueeze(-1) - grid[:, :, :, 2] = 1 - - return grid - - -def affine_grid(grid, mat): - n, h, w, _ = grid.shape - return (grid.view(n, h * w, 3) @ mat.transpose(1, 2)).view(n, h, w, 2) - - -def get_padding(G, height, width, kernel_size): - device = G.device - - cx = (width - 1) / 2 - cy = (height - 1) / 2 - cp = torch.tensor( - [(-cx, -cy, 1), (cx, -cy, 1), (cx, cy, 1), (-cx, cy, 1)], device=device - ) - cp = G @ cp.T - - pad_k = kernel_size // 4 - - pad = cp[:, :2, :].permute(1, 0, 2).flatten(1) - pad = torch.cat((-pad, pad)).max(1).values - pad = pad + torch.tensor([pad_k * 2 - cx, pad_k * 2 - cy] * 2, device=device) - pad = pad.max(torch.tensor([0, 0] * 2, device=device)) - pad = pad.min(torch.tensor([width - 1, height - 1] * 2, device=device)) - - pad_x1, pad_y1, pad_x2, pad_y2 = pad.ceil().to(torch.int32) - - return pad_x1, pad_x2, pad_y1, pad_y2 - - -def try_sample_affine_and_pad(img, p, kernel_size, G=None): - batch, _, height, width = img.shape - - G_try = G - - if G is None: - G_try = torch.inverse(sample_affine(p, batch, height, width)) - - pad_x1, pad_x2, pad_y1, pad_y2 = get_padding(G_try, height, width, kernel_size) - - img_pad = F.pad(img, (pad_x1, pad_x2, pad_y1, pad_y2), mode="reflect") - - return img_pad, G_try, (pad_x1, pad_x2, pad_y1, pad_y2) - - -class GridSampleForward(autograd.Function): - @staticmethod - def forward(ctx, input, grid): - out = F.grid_sample( - input, grid, mode="bilinear", padding_mode="zeros", align_corners=False - ) - ctx.save_for_backward(input, grid) - - return out - - @staticmethod - def backward(ctx, grad_output): - input, grid = ctx.saved_tensors - grad_input, grad_grid = GridSampleBackward.apply(grad_output, input, grid) - - return grad_input, grad_grid - - -class GridSampleBackward(autograd.Function): - @staticmethod - def forward(ctx, grad_output, input, grid): - op = torch._C._jit_get_operation("aten::grid_sampler_2d_backward") - grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False) - ctx.save_for_backward(grid) - - return grad_input, grad_grid - - @staticmethod - def backward(ctx, grad_grad_input, grad_grad_grid): - grid, = ctx.saved_tensors - grad_grad_output = None - - if ctx.needs_input_grad[0]: - grad_grad_output = GridSampleForward.apply(grad_grad_input, grid) - - return grad_grad_output, None, None - - -grid_sample = GridSampleForward.apply - - -def scale_mat_single(s_x, s_y): - return torch.tensor(((s_x, 0, 0), (0, s_y, 0), (0, 0, 1)), dtype=torch.float32) - - -def translate_mat_single(t_x, t_y): - return torch.tensor(((1, 0, t_x), (0, 1, t_y), (0, 0, 1)), dtype=torch.float32) - - -def random_apply_affine(img, p, G=None, antialiasing_kernel=SYM6): - kernel = antialiasing_kernel - len_k = len(kernel) - - kernel = torch.as_tensor(kernel).to(img) - # kernel = torch.ger(kernel, kernel).to(img) - kernel_flip = torch.flip(kernel, (0,)) - - img_pad, G, (pad_x1, pad_x2, pad_y1, pad_y2) = try_sample_affine_and_pad( - img, p, len_k, G - ) - - G_inv = ( - translate_mat_single((pad_x1 - pad_x2).item() / 2, (pad_y1 - pad_y2).item() / 2) - @ G - ) - up_pad = ( - (len_k + 2 - 1) // 2, - (len_k - 2) // 2, - (len_k + 2 - 1) // 2, - (len_k - 2) // 2, - ) - img_2x = upfirdn2d(img_pad, kernel.unsqueeze(0), up=(2, 1), pad=(*up_pad[:2], 0, 0)) - img_2x = upfirdn2d(img_2x, kernel.unsqueeze(1), up=(1, 2), pad=(0, 0, *up_pad[2:])) - G_inv = scale_mat_single(2, 2) @ G_inv @ scale_mat_single(1 / 2, 1 / 2) - G_inv = translate_mat_single(-0.5, -0.5) @ G_inv @ translate_mat_single(0.5, 0.5) - batch_size, channel, height, width = img.shape - pad_k = len_k // 4 - shape = (batch_size, channel, (height + pad_k * 2) * 2, (width + pad_k * 2) * 2) - G_inv = ( - scale_mat_single(2 / img_2x.shape[3], 2 / img_2x.shape[2]) - @ G_inv - @ scale_mat_single(1 / (2 / shape[3]), 1 / (2 / shape[2])) - ) - grid = F.affine_grid(G_inv[:, :2, :].to(img_2x), shape, align_corners=False) - img_affine = grid_sample(img_2x, grid) - d_p = -pad_k * 2 - down_pad = ( - d_p + (len_k - 2 + 1) // 2, - d_p + (len_k - 2) // 2, - d_p + (len_k - 2 + 1) // 2, - d_p + (len_k - 2) // 2, - ) - img_down = upfirdn2d( - img_affine, kernel_flip.unsqueeze(0), down=(2, 1), pad=(*down_pad[:2], 0, 0) - ) - img_down = upfirdn2d( - img_down, kernel_flip.unsqueeze(1), down=(1, 2), pad=(0, 0, *down_pad[2:]) - ) - - return img_down, G - - -def apply_color(img, mat): - batch = img.shape[0] - img = img.permute(0, 2, 3, 1) - mat_mul = mat[:, :3, :3].transpose(1, 2).view(batch, 1, 3, 3) - mat_add = mat[:, :3, 3].view(batch, 1, 1, 3) - img = img @ mat_mul + mat_add - img = img.permute(0, 3, 1, 2) - - return img - - -def random_apply_color(img, p, C=None): - if C is None: - C = sample_color(p, img.shape[0]) - - img = apply_color(img, C.to(img)) - - return img, C - - -def augment(img, p, transform_matrix=(None, None)): - img, G = random_apply_affine(img, p, transform_matrix[0]) - img, C = random_apply_color(img, p, transform_matrix[1]) - - return img, (G, C) diff --git a/spaces/camilosegura/traductor-multilenguaje/Lib/site-packages/aiohttp/http_exceptions.py b/spaces/camilosegura/traductor-multilenguaje/Lib/site-packages/aiohttp/http_exceptions.py deleted file mode 100644 index b5d16ea4ec1058f4e9c011677b8b34ffadc22622..0000000000000000000000000000000000000000 --- a/spaces/camilosegura/traductor-multilenguaje/Lib/site-packages/aiohttp/http_exceptions.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Low-level http related exceptions.""" - - -from textwrap import indent -from typing import Optional, Union - -from .typedefs import _CIMultiDict - -__all__ = ("HttpProcessingError",) - - -class HttpProcessingError(Exception): - """HTTP error. - - Shortcut for raising HTTP errors with custom code, message and headers. - - code: HTTP Error code. - message: (optional) Error message. - headers: (optional) Headers to be sent in response, a list of pairs - """ - - code = 0 - message = "" - headers = None - - def __init__( - self, - *, - code: Optional[int] = None, - message: str = "", - headers: Optional[_CIMultiDict] = None, - ) -> None: - if code is not None: - self.code = code - self.headers = headers - self.message = message - - def __str__(self) -> str: - msg = indent(self.message, " ") - return f"{self.code}, message:\n{msg}" - - def __repr__(self) -> str: - return f"<{self.__class__.__name__}: {self.code}, message={self.message!r}>" - - -class BadHttpMessage(HttpProcessingError): - - code = 400 - message = "Bad Request" - - def __init__(self, message: str, *, headers: Optional[_CIMultiDict] = None) -> None: - super().__init__(message=message, headers=headers) - self.args = (message,) - - -class HttpBadRequest(BadHttpMessage): - - code = 400 - message = "Bad Request" - - -class PayloadEncodingError(BadHttpMessage): - """Base class for payload errors""" - - -class ContentEncodingError(PayloadEncodingError): - """Content encoding error.""" - - -class TransferEncodingError(PayloadEncodingError): - """transfer encoding error.""" - - -class ContentLengthError(PayloadEncodingError): - """Not enough data for satisfy content length header.""" - - -class LineTooLong(BadHttpMessage): - def __init__( - self, line: str, limit: str = "Unknown", actual_size: str = "Unknown" - ) -> None: - super().__init__( - f"Got more than {limit} bytes ({actual_size}) when reading {line}." - ) - self.args = (line, limit, actual_size) - - -class InvalidHeader(BadHttpMessage): - def __init__(self, hdr: Union[bytes, str]) -> None: - if isinstance(hdr, bytes): - hdr = hdr.decode("utf-8", "surrogateescape") - super().__init__(f"Invalid HTTP Header: {hdr}") - self.hdr = hdr - self.args = (hdr,) - - -class BadStatusLine(BadHttpMessage): - def __init__(self, line: str = "") -> None: - if not isinstance(line, str): - line = repr(line) - super().__init__(f"Bad status line {line!r}") - self.args = (line,) - self.line = line - - -class InvalidURLError(BadHttpMessage): - pass diff --git a/spaces/candlend/vits-hoshimi/vits/text/cleaners.py b/spaces/candlend/vits-hoshimi/vits/text/cleaners.py deleted file mode 100644 index 809d7dd35f252fc9670a544beca7975ea4802838..0000000000000000000000000000000000000000 --- a/spaces/candlend/vits-hoshimi/vits/text/cleaners.py +++ /dev/null @@ -1,176 +0,0 @@ -import re -from text.japanese import japanese_to_romaji_with_accent, japanese_to_ipa, japanese_to_ipa2, japanese_to_ipa3 -from text.korean import latin_to_hangul, number_to_hangul, divide_hangul, korean_to_lazy_ipa, korean_to_ipa -from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo, chinese_to_romaji, chinese_to_lazy_ipa, chinese_to_ipa, chinese_to_ipa2 -from text.sanskrit import devanagari_to_ipa -from text.english import english_to_lazy_ipa, english_to_ipa2, english_to_lazy_ipa2 -from text.thai import num_to_thai, latin_to_thai -# from text.shanghainese import shanghainese_to_ipa -# from text.cantonese import cantonese_to_ipa -# from text.ngu_dialect import ngu_dialect_to_ipa - - -def japanese_cleaners(text): - text = japanese_to_romaji_with_accent(text) - if re.match('[A-Za-z]', text[-1]): - text += '.' - return text - - -def japanese_cleaners2(text): - return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…') - - -def korean_cleaners(text): - '''Pipeline for Korean text''' - text = latin_to_hangul(text) - text = number_to_hangul(text) - text = divide_hangul(text) - if re.match('[\u3131-\u3163]', text[-1]): - text += '.' - return text - - -def chinese_cleaners(text): - '''Pipeline for Chinese text''' - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - if re.match('[ˉˊˇˋ˙]', text[-1]): - text += '。' - return text - - -def zh_ja_mixture_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_romaji(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_romaji_with_accent( - japanese_text[4:-4]).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…') - text = text.replace(japanese_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match('[A-Za-zɯɹəɥ→↓↑]', text[-1]): - text += '.' - return text - - -def sanskrit_cleaners(text): - text = text.replace('॥', '।').replace('ॐ', 'ओम्') - if text[-1] != '।': - text += ' ।' - return text - - -def cjks_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - sanskrit_texts = re.findall(r'\[SA\].*?\[SA\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa(japanese_text[4:-4]) - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_lazy_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for sanskrit_text in sanskrit_texts: - cleaned_text = devanagari_to_ipa(sanskrit_text[4:-4]) - text = text.replace(sanskrit_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_lazy_ipa(english_text[4:-4]) - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def cjke_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4]) - cleaned_text = cleaned_text.replace( - 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn') - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa(japanese_text[4:-4]) - cleaned_text = cleaned_text.replace('ʧ', 'tʃ').replace( - 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz') - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_ipa2(english_text[4:-4]) - cleaned_text = cleaned_text.replace('ɑ', 'a').replace( - 'ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u') - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def cjke_cleaners2(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_ipa(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa2(japanese_text[4:-4]) - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_ipa2(english_text[4:-4]) - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def thai_cleaners(text): - text = num_to_thai(text) - text = latin_to_thai(text) - return text - - -# def shanghainese_cleaners(text): -# text = shanghainese_to_ipa(text) -# if re.match(r'[^\.,!\?\-…~]', text[-1]): -# text += '.' -# return text - - -# def chinese_dialect_cleaners(text): -# text = re.sub(r'\[MD\](.*?)\[MD\]', -# lambda x: chinese_to_ipa2(x.group(1))+' ', text) -# text = re.sub(r'\[TW\](.*?)\[TW\]', -# lambda x: chinese_to_ipa2(x.group(1), True)+' ', text) -# text = re.sub(r'\[JA\](.*?)\[JA\]', -# lambda x: japanese_to_ipa3(x.group(1)).replace('Q', 'ʔ')+' ', text) -# text = re.sub(r'\[SH\](.*?)\[SH\]', lambda x: shanghainese_to_ipa(x.group(1)).replace('1', '˥˧').replace('5', -# '˧˧˦').replace('6', '˩˩˧').replace('7', '˥').replace('8', '˩˨').replace('ᴀ', 'ɐ').replace('ᴇ', 'e')+' ', text) -# text = re.sub(r'\[GD\](.*?)\[GD\]', -# lambda x: cantonese_to_ipa(x.group(1))+' ', text) -# text = re.sub(r'\[EN\](.*?)\[EN\]', -# lambda x: english_to_lazy_ipa2(x.group(1))+' ', text) -# text = re.sub(r'\[([A-Z]{2})\](.*?)\[\1\]', lambda x: ngu_dialect_to_ipa(x.group(2), x.group( -# 1)).replace('ʣ', 'dz').replace('ʥ', 'dʑ').replace('ʦ', 'ts').replace('ʨ', 'tɕ')+' ', text) -# text = re.sub(r'\s+$', '', text) -# text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) -# return text \ No newline at end of file diff --git a/spaces/cariai/somos-alpaca-es/Dockerfile b/spaces/cariai/somos-alpaca-es/Dockerfile deleted file mode 100644 index f082970621660a3a398d4266140ceb3a4baa4895..0000000000000000000000000000000000000000 --- a/spaces/cariai/somos-alpaca-es/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM argilla/argilla-quickstart:latest - -# Define datasets to preload: full=all datasets, single=one dataset, and none=no datasets. -ENV LOAD_DATASETS=single - -CMD whoami && /start_quickstart_argilla.sh \ No newline at end of file diff --git a/spaces/chendl/compositional_test/transformers/examples/tensorflow/token-classification/run_ner.py b/spaces/chendl/compositional_test/transformers/examples/tensorflow/token-classification/run_ner.py deleted file mode 100644 index 91aafeeaec3bf29d6ba3b65c29a7f4003121b2cc..0000000000000000000000000000000000000000 --- a/spaces/chendl/compositional_test/transformers/examples/tensorflow/token-classification/run_ner.py +++ /dev/null @@ -1,599 +0,0 @@ -#!/usr/bin/env python -# coding=utf-8 -# Copyright 2021 The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -Fine-tuning a 🤗 Transformers model on token classification tasks (NER, POS, CHUNKS) relying on the accelerate library -without using a Trainer. -""" - -import json -import logging -import os -import random -from dataclasses import dataclass, field -from typing import Optional - -import datasets -import evaluate -import tensorflow as tf -from datasets import ClassLabel, load_dataset - -import transformers -from transformers import ( - CONFIG_MAPPING, - AutoConfig, - AutoTokenizer, - DataCollatorForTokenClassification, - HfArgumentParser, - PushToHubCallback, - TFAutoModelForTokenClassification, - TFTrainingArguments, - create_optimizer, - set_seed, -) -from transformers.utils import send_example_telemetry -from transformers.utils.versions import require_version - - -logger = logging.getLogger(__name__) -logger.addHandler(logging.StreamHandler()) -require_version("datasets>=1.8.0", "To fix: pip install -r examples/tensorflow/token-classification/requirements.txt") - - -# region Command-line arguments -@dataclass -class ModelArguments: - """ - Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. - """ - - model_name_or_path: str = field( - metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} - ) - config_name: Optional[str] = field( - default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} - ) - tokenizer_name: Optional[str] = field( - default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} - ) - cache_dir: Optional[str] = field( - default=None, - metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, - ) - model_revision: str = field( - default="main", - metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, - ) - use_auth_token: bool = field( - default=False, - metadata={ - "help": ( - "Will use the token generated when running `huggingface-cli login` (necessary to use this script " - "with private models)." - ) - }, - ) - - -@dataclass -class DataTrainingArguments: - """ - Arguments pertaining to what data we are going to input our model for training and eval. - """ - - task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."}) - dataset_name: Optional[str] = field( - default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} - ) - dataset_config_name: Optional[str] = field( - default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} - ) - train_file: Optional[str] = field( - default=None, metadata={"help": "The input training data file (a csv or JSON file)."} - ) - validation_file: Optional[str] = field( - default=None, - metadata={"help": "An optional input evaluation data file to evaluate on (a csv or JSON file)."}, - ) - test_file: Optional[str] = field( - default=None, - metadata={"help": "An optional input test data file to predict on (a csv or JSON file)."}, - ) - text_column_name: Optional[str] = field( - default=None, metadata={"help": "The column name of text to input in the file (a csv or JSON file)."} - ) - label_column_name: Optional[str] = field( - default=None, metadata={"help": "The column name of label to input in the file (a csv or JSON file)."} - ) - overwrite_cache: bool = field( - default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} - ) - preprocessing_num_workers: Optional[int] = field( - default=None, - metadata={"help": "The number of processes to use for the preprocessing."}, - ) - max_length: Optional[int] = field(default=256, metadata={"help": "Max length (in tokens) for truncation/padding"}) - pad_to_max_length: bool = field( - default=False, - metadata={ - "help": ( - "Whether to pad all samples to model maximum sentence length. " - "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " - "efficient on GPU but very bad for TPU." - ) - }, - ) - max_train_samples: Optional[int] = field( - default=None, - metadata={ - "help": ( - "For debugging purposes or quicker training, truncate the number of training examples to this " - "value if set." - ) - }, - ) - max_eval_samples: Optional[int] = field( - default=None, - metadata={ - "help": ( - "For debugging purposes or quicker training, truncate the number of evaluation examples to this " - "value if set." - ) - }, - ) - max_predict_samples: Optional[int] = field( - default=None, - metadata={ - "help": ( - "For debugging purposes or quicker training, truncate the number of prediction examples to this " - "value if set." - ) - }, - ) - label_all_tokens: bool = field( - default=False, - metadata={ - "help": ( - "Whether to put the label for one word on all tokens of generated by that word or just on the " - "one (in which case the other tokens will have a padding index)." - ) - }, - ) - return_entity_level_metrics: bool = field( - default=False, - metadata={"help": "Whether to return all the entity levels during evaluation or just the overall ones."}, - ) - - def __post_init__(self): - if self.dataset_name is None and self.train_file is None and self.validation_file is None: - raise ValueError("Need either a dataset name or a training/validation file.") - else: - if self.train_file is not None: - extension = self.train_file.split(".")[-1] - assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." - if self.validation_file is not None: - extension = self.validation_file.split(".")[-1] - assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." - self.task_name = self.task_name.lower() - - -# endregion - - -def main(): - # region Argument Parsing - parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)) - model_args, data_args, training_args = parser.parse_args_into_dataclasses() - - # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The - # information sent is the one passed as arguments along with your Python/PyTorch versions. - send_example_telemetry("run_ner", model_args, data_args, framework="tensorflow") - # endregion - - # region Setup logging - # we only want one process per machine to log things on the screen. - # accelerator.is_local_main_process is only True for one process per machine. - logger.setLevel(logging.INFO) - datasets.utils.logging.set_verbosity_warning() - transformers.utils.logging.set_verbosity_info() - - # If passed along, set the training seed now. - if training_args.seed is not None: - set_seed(training_args.seed) - # endregion - - # region Loading datasets - # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) - # or just provide the name of one of the public datasets for token classification task available on the hub at https://huggingface.co/datasets/ - # (the dataset will be downloaded automatically from the datasets Hub). - # - # For CSV/JSON files, this script will use the column called 'tokens' or the first column if no column called - # 'tokens' is found. You can easily tweak this behavior (see below). - # - # In distributed training, the load_dataset function guarantee that only one local process can concurrently - # download the dataset. - if data_args.dataset_name is not None: - # Downloading and loading a dataset from the hub. - raw_datasets = load_dataset( - data_args.dataset_name, - data_args.dataset_config_name, - use_auth_token=True if model_args.use_auth_token else None, - ) - else: - data_files = {} - if data_args.train_file is not None: - data_files["train"] = data_args.train_file - if data_args.validation_file is not None: - data_files["validation"] = data_args.validation_file - extension = data_args.train_file.split(".")[-1] - raw_datasets = load_dataset( - extension, - data_files=data_files, - use_auth_token=True if model_args.use_auth_token else None, - ) - # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at - # https://huggingface.co/docs/datasets/loading_datasets.html. - - if raw_datasets["train"] is not None: - column_names = raw_datasets["train"].column_names - features = raw_datasets["train"].features - else: - column_names = raw_datasets["validation"].column_names - features = raw_datasets["validation"].features - - if data_args.text_column_name is not None: - text_column_name = data_args.text_column_name - elif "tokens" in column_names: - text_column_name = "tokens" - else: - text_column_name = column_names[0] - - if data_args.label_column_name is not None: - label_column_name = data_args.label_column_name - elif f"{data_args.task_name}_tags" in column_names: - label_column_name = f"{data_args.task_name}_tags" - else: - label_column_name = column_names[1] - - # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the - # unique labels. - def get_label_list(labels): - unique_labels = set() - for label in labels: - unique_labels = unique_labels | set(label) - label_list = list(unique_labels) - label_list.sort() - return label_list - - if isinstance(features[label_column_name].feature, ClassLabel): - label_list = features[label_column_name].feature.names - # No need to convert the labels since they are already ints. - label_to_id = {i: i for i in range(len(label_list))} - else: - label_list = get_label_list(raw_datasets["train"][label_column_name]) - label_to_id = {l: i for i, l in enumerate(label_list)} - num_labels = len(label_list) - # endregion - - # region Load config and tokenizer - # - # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently - # download model & vocab. - if model_args.config_name: - config = AutoConfig.from_pretrained(model_args.config_name, num_labels=num_labels) - elif model_args.model_name_or_path: - config = AutoConfig.from_pretrained(model_args.model_name_or_path, num_labels=num_labels) - else: - config = CONFIG_MAPPING[model_args.model_type]() - logger.warning("You are instantiating a new config instance from scratch.") - - tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path - if not tokenizer_name_or_path: - raise ValueError( - "You are instantiating a new tokenizer from scratch. This is not supported by this script." - "You can do it from another script, save it, and load it from here, using --tokenizer_name." - ) - - if config.model_type in {"gpt2", "roberta"}: - tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True, add_prefix_space=True) - else: - tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True) - # endregion - - # region Preprocessing the raw datasets - # First we tokenize all the texts. - padding = "max_length" if data_args.pad_to_max_length else False - - # Tokenize all texts and align the labels with them. - - def tokenize_and_align_labels(examples): - tokenized_inputs = tokenizer( - examples[text_column_name], - max_length=data_args.max_length, - padding=padding, - truncation=True, - # We use this argument because the texts in our dataset are lists of words (with a label for each word). - is_split_into_words=True, - ) - - labels = [] - for i, label in enumerate(examples[label_column_name]): - word_ids = tokenized_inputs.word_ids(batch_index=i) - previous_word_idx = None - label_ids = [] - for word_idx in word_ids: - # Special tokens have a word id that is None. We set the label to -100 so they are automatically - # ignored in the loss function. - if word_idx is None: - label_ids.append(-100) - # We set the label for the first token of each word. - elif word_idx != previous_word_idx: - label_ids.append(label_to_id[label[word_idx]]) - # For the other tokens in a word, we set the label to either the current label or -100, depending on - # the label_all_tokens flag. - else: - label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100) - previous_word_idx = word_idx - - labels.append(label_ids) - tokenized_inputs["labels"] = labels - return tokenized_inputs - - processed_raw_datasets = raw_datasets.map( - tokenize_and_align_labels, - batched=True, - remove_columns=raw_datasets["train"].column_names, - desc="Running tokenizer on dataset", - ) - - train_dataset = processed_raw_datasets["train"] - eval_dataset = processed_raw_datasets["validation"] - - if data_args.max_train_samples is not None: - max_train_samples = min(len(train_dataset), data_args.max_train_samples) - train_dataset = train_dataset.select(range(max_train_samples)) - - if data_args.max_eval_samples is not None: - max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) - eval_dataset = eval_dataset.select(range(max_eval_samples)) - - # Log a few random samples from the training set: - for index in random.sample(range(len(train_dataset)), 3): - logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") - # endregion - - with training_args.strategy.scope(): - # region Initialize model - if model_args.model_name_or_path: - model = TFAutoModelForTokenClassification.from_pretrained( - model_args.model_name_or_path, - config=config, - ) - else: - logger.info("Training new model from scratch") - model = TFAutoModelForTokenClassification.from_config(config) - - # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch - # on a small vocab and want a smaller embedding size, remove this test. - embeddings = model.get_input_embeddings() - - # Matt: This is a temporary workaround as we transition our models to exclusively using Keras embeddings. - # As soon as the transition is complete, all embeddings should be keras.Embeddings layers, and - # the weights will always be in embeddings.embeddings. - if hasattr(embeddings, "embeddings"): - embedding_size = embeddings.embeddings.shape[0] - else: - embedding_size = embeddings.weight.shape[0] - if len(tokenizer) > embedding_size: - model.resize_token_embeddings(len(tokenizer)) - # endregion - - # region Create TF datasets - - # We need the DataCollatorForTokenClassification here, as we need to correctly pad labels as - # well as inputs. - collate_fn = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="np") - num_replicas = training_args.strategy.num_replicas_in_sync - total_train_batch_size = training_args.per_device_train_batch_size * num_replicas - - dataset_options = tf.data.Options() - dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF - - # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in - # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also - # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names - # yourself if you use this method, whereas they are automatically inferred from the model input names when - # using model.prepare_tf_dataset() - # For more info see the docs: - # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset - # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset - - tf_train_dataset = model.prepare_tf_dataset( - train_dataset, - collate_fn=collate_fn, - batch_size=total_train_batch_size, - shuffle=True, - ).with_options(dataset_options) - total_eval_batch_size = training_args.per_device_eval_batch_size * num_replicas - tf_eval_dataset = model.prepare_tf_dataset( - eval_dataset, - collate_fn=collate_fn, - batch_size=total_eval_batch_size, - shuffle=False, - ).with_options(dataset_options) - - # endregion - - # region Optimizer, loss and compilation - num_train_steps = int(len(tf_train_dataset) * training_args.num_train_epochs) - if training_args.warmup_steps > 0: - num_warmup_steps = training_args.warmup_steps - elif training_args.warmup_ratio > 0: - num_warmup_steps = int(num_train_steps * training_args.warmup_ratio) - else: - num_warmup_steps = 0 - - optimizer, lr_schedule = create_optimizer( - init_lr=training_args.learning_rate, - num_train_steps=num_train_steps, - num_warmup_steps=num_warmup_steps, - adam_beta1=training_args.adam_beta1, - adam_beta2=training_args.adam_beta2, - adam_epsilon=training_args.adam_epsilon, - weight_decay_rate=training_args.weight_decay, - adam_global_clipnorm=training_args.max_grad_norm, - ) - - model.compile(optimizer=optimizer, jit_compile=training_args.xla) - # endregion - - # Metrics - metric = evaluate.load("seqeval") - - def get_labels(y_pred, y_true): - # Transform predictions and references tensos to numpy arrays - - # Remove ignored index (special tokens) - true_predictions = [ - [label_list[p] for (p, l) in zip(pred, gold_label) if l != -100] - for pred, gold_label in zip(y_pred, y_true) - ] - true_labels = [ - [label_list[l] for (p, l) in zip(pred, gold_label) if l != -100] - for pred, gold_label in zip(y_pred, y_true) - ] - return true_predictions, true_labels - - def compute_metrics(): - results = metric.compute() - if data_args.return_entity_level_metrics: - # Unpack nested dictionaries - final_results = {} - for key, value in results.items(): - if isinstance(value, dict): - for n, v in value.items(): - final_results[f"{key}_{n}"] = v - else: - final_results[key] = value - return final_results - else: - return { - "precision": results["overall_precision"], - "recall": results["overall_recall"], - "f1": results["overall_f1"], - "accuracy": results["overall_accuracy"], - } - - # endregion - - # region Preparing push_to_hub and model card - push_to_hub_model_id = training_args.push_to_hub_model_id - model_name = model_args.model_name_or_path.split("/")[-1] - if not push_to_hub_model_id: - if data_args.dataset_name is not None: - push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}" - else: - push_to_hub_model_id = f"{model_name}-finetuned-token-classification" - - model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "token-classification"} - if data_args.dataset_name is not None: - model_card_kwargs["dataset_tags"] = data_args.dataset_name - if data_args.dataset_config_name is not None: - model_card_kwargs["dataset_args"] = data_args.dataset_config_name - model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" - else: - model_card_kwargs["dataset"] = data_args.dataset_name - - if training_args.push_to_hub: - callbacks = [ - PushToHubCallback( - output_dir=training_args.output_dir, - hub_model_id=push_to_hub_model_id, - hub_token=training_args.push_to_hub_token, - tokenizer=tokenizer, - **model_card_kwargs, - ) - ] - else: - callbacks = [] - # endregion - - # region Training - logger.info("***** Running training *****") - logger.info(f" Num examples = {len(train_dataset)}") - logger.info(f" Num Epochs = {training_args.num_train_epochs}") - logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}") - logger.info(f" Total train batch size = {total_train_batch_size}") - # Only show the progress bar once on each machine. - - model.fit( - tf_train_dataset, - validation_data=tf_eval_dataset, - epochs=int(training_args.num_train_epochs), - callbacks=callbacks, - ) - # endregion - - # region Predictions - # If you have variable batch sizes (i.e. not using pad_to_max_length), then - # this bit might fail on TF < 2.8 because TF can't concatenate outputs of varying seq - # length from predict(). - - try: - predictions = model.predict(tf_eval_dataset, batch_size=training_args.per_device_eval_batch_size)["logits"] - except tf.python.framework.errors_impl.InvalidArgumentError: - raise ValueError( - "Concatenating predictions failed! If your version of TensorFlow is 2.8.0 or older " - "then you will need to use --pad_to_max_length to generate predictions, as older " - "versions of TensorFlow cannot concatenate variable-length predictions as RaggedTensor." - ) - if isinstance(predictions, tf.RaggedTensor): - predictions = predictions.to_tensor(default_value=-100) - predictions = tf.math.argmax(predictions, axis=-1).numpy() - if "label" in eval_dataset: - labels = eval_dataset.with_format("tf")["label"] - else: - labels = eval_dataset.with_format("tf")["labels"] - if isinstance(labels, tf.RaggedTensor): - labels = labels.to_tensor(default_value=-100) - labels = labels.numpy() - attention_mask = eval_dataset.with_format("tf")["attention_mask"] - if isinstance(attention_mask, tf.RaggedTensor): - attention_mask = attention_mask.to_tensor(default_value=-100) - attention_mask = attention_mask.numpy() - labels[attention_mask == 0] = -100 - preds, refs = get_labels(predictions, labels) - metric.add_batch( - predictions=preds, - references=refs, - ) - eval_metric = compute_metrics() - logger.info("Evaluation metrics:") - for key, val in eval_metric.items(): - logger.info(f"{key}: {val:.4f}") - - if training_args.output_dir is not None: - output_eval_file = os.path.join(training_args.output_dir, "all_results.json") - with open(output_eval_file, "w") as writer: - writer.write(json.dumps(eval_metric)) - # endregion - - if training_args.output_dir is not None and not training_args.push_to_hub: - # If we're not pushing to hub, at least save a local copy when we're done - model.save_pretrained(training_args.output_dir) - - -if __name__ == "__main__": - main() diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/dateutil/tz/_factories.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/dateutil/tz/_factories.py deleted file mode 100644 index f8a65891a023ebf9eb0c24d391ba67541b7133f1..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/dateutil/tz/_factories.py +++ /dev/null @@ -1,80 +0,0 @@ -from datetime import timedelta -import weakref -from collections import OrderedDict - -from six.moves import _thread - - -class _TzSingleton(type): - def __init__(cls, *args, **kwargs): - cls.__instance = None - super(_TzSingleton, cls).__init__(*args, **kwargs) - - def __call__(cls): - if cls.__instance is None: - cls.__instance = super(_TzSingleton, cls).__call__() - return cls.__instance - - -class _TzFactory(type): - def instance(cls, *args, **kwargs): - """Alternate constructor that returns a fresh instance""" - return type.__call__(cls, *args, **kwargs) - - -class _TzOffsetFactory(_TzFactory): - def __init__(cls, *args, **kwargs): - cls.__instances = weakref.WeakValueDictionary() - cls.__strong_cache = OrderedDict() - cls.__strong_cache_size = 8 - - cls._cache_lock = _thread.allocate_lock() - - def __call__(cls, name, offset): - if isinstance(offset, timedelta): - key = (name, offset.total_seconds()) - else: - key = (name, offset) - - instance = cls.__instances.get(key, None) - if instance is None: - instance = cls.__instances.setdefault(key, - cls.instance(name, offset)) - - # This lock may not be necessary in Python 3. See GH issue #901 - with cls._cache_lock: - cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) - - # Remove an item if the strong cache is overpopulated - if len(cls.__strong_cache) > cls.__strong_cache_size: - cls.__strong_cache.popitem(last=False) - - return instance - - -class _TzStrFactory(_TzFactory): - def __init__(cls, *args, **kwargs): - cls.__instances = weakref.WeakValueDictionary() - cls.__strong_cache = OrderedDict() - cls.__strong_cache_size = 8 - - cls.__cache_lock = _thread.allocate_lock() - - def __call__(cls, s, posix_offset=False): - key = (s, posix_offset) - instance = cls.__instances.get(key, None) - - if instance is None: - instance = cls.__instances.setdefault(key, - cls.instance(s, posix_offset)) - - # This lock may not be necessary in Python 3. See GH issue #901 - with cls.__cache_lock: - cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) - - # Remove an item if the strong cache is overpopulated - if len(cls.__strong_cache) > cls.__strong_cache_size: - cls.__strong_cache.popitem(last=False) - - return instance - diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/opc/spec.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/opc/spec.py deleted file mode 100644 index 60fc3856483afffedd43d329f4fef82f144bfbb9..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/opc/spec.py +++ /dev/null @@ -1,29 +0,0 @@ -# encoding: utf-8 - -""" -Provides mappings that embody aspects of the Open XML spec ISO/IEC 29500. -""" - -from .constants import CONTENT_TYPE as CT - - -default_content_types = ( - ('bin', CT.PML_PRINTER_SETTINGS), - ('bin', CT.SML_PRINTER_SETTINGS), - ('bin', CT.WML_PRINTER_SETTINGS), - ('bmp', CT.BMP), - ('emf', CT.X_EMF), - ('fntdata', CT.X_FONTDATA), - ('gif', CT.GIF), - ('jpe', CT.JPEG), - ('jpeg', CT.JPEG), - ('jpg', CT.JPEG), - ('png', CT.PNG), - ('rels', CT.OPC_RELATIONSHIPS), - ('tif', CT.TIFF), - ('tiff', CT.TIFF), - ('wdp', CT.MS_PHOTO), - ('wmf', CT.X_WMF), - ('xlsx', CT.SML_SHEET), - ('xml', CT.XML), -) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/encodings/__init__.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/encodings/__init__.py deleted file mode 100644 index 156cb232a7aa80eee1526c7598f72043de10473f..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/encodings/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Empty __init__.py file to signal Python this directory is a package.""" diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/misc/bezierTools.c b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/misc/bezierTools.c deleted file mode 100644 index 3c9d25e5ebe574b9bdf43b88c151207ae0d945c2..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.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/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/aiohttp/multipart.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/aiohttp/multipart.py deleted file mode 100644 index 73801f459aa274ca6aae7bf28a2c5bb3bf075d11..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/aiohttp/multipart.py +++ /dev/null @@ -1,961 +0,0 @@ -import base64 -import binascii -import json -import re -import uuid -import warnings -import zlib -from collections import deque -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - AsyncIterator, - Deque, - Dict, - Iterator, - List, - Mapping, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -from urllib.parse import parse_qsl, unquote, urlencode - -from multidict import CIMultiDict, CIMultiDictProxy, MultiMapping - -from .hdrs import ( - CONTENT_DISPOSITION, - CONTENT_ENCODING, - CONTENT_LENGTH, - CONTENT_TRANSFER_ENCODING, - CONTENT_TYPE, -) -from .helpers import CHAR, TOKEN, parse_mimetype, reify -from .http import HeadersParser -from .payload import ( - JsonPayload, - LookupError, - Order, - Payload, - StringPayload, - get_payload, - payload_type, -) -from .streams import StreamReader - -__all__ = ( - "MultipartReader", - "MultipartWriter", - "BodyPartReader", - "BadContentDispositionHeader", - "BadContentDispositionParam", - "parse_content_disposition", - "content_disposition_filename", -) - - -if TYPE_CHECKING: # pragma: no cover - from .client_reqrep import ClientResponse - - -class BadContentDispositionHeader(RuntimeWarning): - pass - - -class BadContentDispositionParam(RuntimeWarning): - pass - - -def parse_content_disposition( - header: Optional[str], -) -> Tuple[Optional[str], Dict[str, str]]: - def is_token(string: str) -> bool: - return bool(string) and TOKEN >= set(string) - - def is_quoted(string: str) -> bool: - return string[0] == string[-1] == '"' - - def is_rfc5987(string: str) -> bool: - return is_token(string) and string.count("'") == 2 - - def is_extended_param(string: str) -> bool: - return string.endswith("*") - - def is_continuous_param(string: str) -> bool: - pos = string.find("*") + 1 - if not pos: - return False - substring = string[pos:-1] if string.endswith("*") else string[pos:] - return substring.isdigit() - - def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str: - return re.sub(f"\\\\([{chars}])", "\\1", text) - - if not header: - return None, {} - - disptype, *parts = header.split(";") - if not is_token(disptype): - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - params: Dict[str, str] = {} - while parts: - item = parts.pop(0) - - if "=" not in item: - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - key, value = item.split("=", 1) - key = key.lower().strip() - value = value.lstrip() - - if key in params: - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - if not is_token(key): - warnings.warn(BadContentDispositionParam(item)) - continue - - elif is_continuous_param(key): - if is_quoted(value): - value = unescape(value[1:-1]) - elif not is_token(value): - warnings.warn(BadContentDispositionParam(item)) - continue - - elif is_extended_param(key): - if is_rfc5987(value): - encoding, _, value = value.split("'", 2) - encoding = encoding or "utf-8" - else: - warnings.warn(BadContentDispositionParam(item)) - continue - - try: - value = unquote(value, encoding, "strict") - except UnicodeDecodeError: # pragma: nocover - warnings.warn(BadContentDispositionParam(item)) - continue - - else: - failed = True - if is_quoted(value): - failed = False - value = unescape(value[1:-1].lstrip("\\/")) - elif is_token(value): - failed = False - elif parts: - # maybe just ; in filename, in any case this is just - # one case fix, for proper fix we need to redesign parser - _value = f"{value};{parts[0]}" - if is_quoted(_value): - parts.pop(0) - value = unescape(_value[1:-1].lstrip("\\/")) - failed = False - - if failed: - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - params[key] = value - - return disptype.lower(), params - - -def content_disposition_filename( - params: Mapping[str, str], name: str = "filename" -) -> Optional[str]: - name_suf = "%s*" % name - if not params: - return None - elif name_suf in params: - return params[name_suf] - elif name in params: - return params[name] - else: - parts = [] - fnparams = sorted( - (key, value) for key, value in params.items() if key.startswith(name_suf) - ) - for num, (key, value) in enumerate(fnparams): - _, tail = key.split("*", 1) - if tail.endswith("*"): - tail = tail[:-1] - if tail == str(num): - parts.append(value) - else: - break - if not parts: - return None - value = "".join(parts) - if "'" in value: - encoding, _, value = value.split("'", 2) - encoding = encoding or "utf-8" - return unquote(value, encoding, "strict") - return value - - -class MultipartResponseWrapper: - """Wrapper around the MultipartReader. - - It takes care about - underlying connection and close it when it needs in. - """ - - def __init__( - self, - resp: "ClientResponse", - stream: "MultipartReader", - ) -> None: - self.resp = resp - self.stream = stream - - def __aiter__(self) -> "MultipartResponseWrapper": - return self - - async def __anext__( - self, - ) -> Union["MultipartReader", "BodyPartReader"]: - part = await self.next() - if part is None: - raise StopAsyncIteration - return part - - def at_eof(self) -> bool: - """Returns True when all response data had been read.""" - return self.resp.content.at_eof() - - async def next( - self, - ) -> Optional[Union["MultipartReader", "BodyPartReader"]]: - """Emits next multipart reader object.""" - item = await self.stream.next() - if self.stream.at_eof(): - await self.release() - return item - - async def release(self) -> None: - """Release the connection gracefully. - - All remaining content is read to the void. - """ - await self.resp.release() - - -class BodyPartReader: - """Multipart reader for single body part.""" - - chunk_size = 8192 - - def __init__( - self, boundary: bytes, headers: "CIMultiDictProxy[str]", content: StreamReader - ) -> None: - self.headers = headers - self._boundary = boundary - self._content = content - self._at_eof = False - length = self.headers.get(CONTENT_LENGTH, None) - self._length = int(length) if length is not None else None - self._read_bytes = 0 - # TODO: typeing.Deque is not supported by Python 3.5 - self._unread: Deque[bytes] = deque() - self._prev_chunk: Optional[bytes] = None - self._content_eof = 0 - self._cache: Dict[str, Any] = {} - - def __aiter__(self) -> AsyncIterator["BodyPartReader"]: - return self # type: ignore[return-value] - - async def __anext__(self) -> bytes: - part = await self.next() - if part is None: - raise StopAsyncIteration - return part - - async def next(self) -> Optional[bytes]: - item = await self.read() - if not item: - return None - return item - - async def read(self, *, decode: bool = False) -> bytes: - """Reads body part data. - - decode: Decodes data following by encoding - method from Content-Encoding header. If it missed - data remains untouched - """ - if self._at_eof: - return b"" - data = bytearray() - while not self._at_eof: - data.extend(await self.read_chunk(self.chunk_size)) - if decode: - return self.decode(data) - return data - - async def read_chunk(self, size: int = chunk_size) -> bytes: - """Reads body part content chunk of the specified size. - - size: chunk size - """ - if self._at_eof: - return b"" - if self._length: - chunk = await self._read_chunk_from_length(size) - else: - chunk = await self._read_chunk_from_stream(size) - - self._read_bytes += len(chunk) - if self._read_bytes == self._length: - self._at_eof = True - if self._at_eof: - clrf = await self._content.readline() - assert ( - b"\r\n" == clrf - ), "reader did not read all the data or it is malformed" - return chunk - - async def _read_chunk_from_length(self, size: int) -> bytes: - # Reads body part content chunk of the specified size. - # The body part must has Content-Length header with proper value. - assert self._length is not None, "Content-Length required for chunked read" - chunk_size = min(size, self._length - self._read_bytes) - chunk = await self._content.read(chunk_size) - return chunk - - async def _read_chunk_from_stream(self, size: int) -> bytes: - # Reads content chunk of body part with unknown length. - # The Content-Length header for body part is not necessary. - assert ( - size >= len(self._boundary) + 2 - ), "Chunk size must be greater or equal than boundary length + 2" - first_chunk = self._prev_chunk is None - if first_chunk: - self._prev_chunk = await self._content.read(size) - - chunk = await self._content.read(size) - self._content_eof += int(self._content.at_eof()) - assert self._content_eof < 3, "Reading after EOF" - assert self._prev_chunk is not None - window = self._prev_chunk + chunk - sub = b"\r\n" + self._boundary - if first_chunk: - idx = window.find(sub) - else: - idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub))) - if idx >= 0: - # pushing boundary back to content - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", category=DeprecationWarning) - self._content.unread_data(window[idx:]) - if size > idx: - self._prev_chunk = self._prev_chunk[:idx] - chunk = window[len(self._prev_chunk) : idx] - if not chunk: - self._at_eof = True - result = self._prev_chunk - self._prev_chunk = chunk - return result - - async def readline(self) -> bytes: - """Reads body part by line by line.""" - if self._at_eof: - return b"" - - if self._unread: - line = self._unread.popleft() - else: - line = await self._content.readline() - - if line.startswith(self._boundary): - # the very last boundary may not come with \r\n, - # so set single rules for everyone - sline = line.rstrip(b"\r\n") - boundary = self._boundary - last_boundary = self._boundary + b"--" - # ensure that we read exactly the boundary, not something alike - if sline == boundary or sline == last_boundary: - self._at_eof = True - self._unread.append(line) - return b"" - else: - next_line = await self._content.readline() - if next_line.startswith(self._boundary): - line = line[:-2] # strip CRLF but only once - self._unread.append(next_line) - - return line - - async def release(self) -> None: - """Like read(), but reads all the data to the void.""" - if self._at_eof: - return - while not self._at_eof: - await self.read_chunk(self.chunk_size) - - async def text(self, *, encoding: Optional[str] = None) -> str: - """Like read(), but assumes that body part contains text data.""" - data = await self.read(decode=True) - # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm # NOQA - # and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-send # NOQA - encoding = encoding or self.get_charset(default="utf-8") - return data.decode(encoding) - - async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, Any]]: - """Like read(), but assumes that body parts contains JSON data.""" - data = await self.read(decode=True) - if not data: - return None - encoding = encoding or self.get_charset(default="utf-8") - return cast(Dict[str, Any], json.loads(data.decode(encoding))) - - async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]: - """Like read(), but assumes that body parts contain form urlencoded data.""" - data = await self.read(decode=True) - if not data: - return [] - if encoding is not None: - real_encoding = encoding - else: - real_encoding = self.get_charset(default="utf-8") - return parse_qsl( - data.rstrip().decode(real_encoding), - keep_blank_values=True, - encoding=real_encoding, - ) - - def at_eof(self) -> bool: - """Returns True if the boundary was reached or False otherwise.""" - return self._at_eof - - def decode(self, data: bytes) -> bytes: - """Decodes data. - - Decoding is done according the specified Content-Encoding - or Content-Transfer-Encoding headers value. - """ - if CONTENT_TRANSFER_ENCODING in self.headers: - data = self._decode_content_transfer(data) - if CONTENT_ENCODING in self.headers: - return self._decode_content(data) - return data - - def _decode_content(self, data: bytes) -> bytes: - encoding = self.headers.get(CONTENT_ENCODING, "").lower() - - if encoding == "deflate": - return zlib.decompress(data, -zlib.MAX_WBITS) - elif encoding == "gzip": - return zlib.decompress(data, 16 + zlib.MAX_WBITS) - elif encoding == "identity": - return data - else: - raise RuntimeError(f"unknown content encoding: {encoding}") - - def _decode_content_transfer(self, data: bytes) -> bytes: - encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() - - if encoding == "base64": - return base64.b64decode(data) - elif encoding == "quoted-printable": - return binascii.a2b_qp(data) - elif encoding in ("binary", "8bit", "7bit"): - return data - else: - raise RuntimeError( - "unknown content transfer encoding: {}" "".format(encoding) - ) - - def get_charset(self, default: str) -> str: - """Returns charset parameter from Content-Type header or default.""" - ctype = self.headers.get(CONTENT_TYPE, "") - mimetype = parse_mimetype(ctype) - return mimetype.parameters.get("charset", default) - - @reify - def name(self) -> Optional[str]: - """Returns name specified in Content-Disposition header. - - If the header is missing or malformed, returns None. - """ - _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) - return content_disposition_filename(params, "name") - - @reify - def filename(self) -> Optional[str]: - """Returns filename specified in Content-Disposition header. - - Returns None if the header is missing or malformed. - """ - _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) - return content_disposition_filename(params, "filename") - - -@payload_type(BodyPartReader, order=Order.try_first) -class BodyPartReaderPayload(Payload): - def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None: - super().__init__(value, *args, **kwargs) - - params: Dict[str, str] = {} - if value.name is not None: - params["name"] = value.name - if value.filename is not None: - params["filename"] = value.filename - - if params: - self.set_content_disposition("attachment", True, **params) - - async def write(self, writer: Any) -> None: - field = self._value - chunk = await field.read_chunk(size=2**16) - while chunk: - await writer.write(field.decode(chunk)) - chunk = await field.read_chunk(size=2**16) - - -class MultipartReader: - """Multipart body reader.""" - - #: Response wrapper, used when multipart readers constructs from response. - response_wrapper_cls = MultipartResponseWrapper - #: Multipart reader class, used to handle multipart/* body parts. - #: None points to type(self) - multipart_reader_cls = None - #: Body part reader class for non multipart/* content types. - part_reader_cls = BodyPartReader - - def __init__(self, headers: Mapping[str, str], content: StreamReader) -> None: - self.headers = headers - self._boundary = ("--" + self._get_boundary()).encode() - self._content = content - self._last_part: Optional[Union["MultipartReader", BodyPartReader]] = None - self._at_eof = False - self._at_bof = True - self._unread: List[bytes] = [] - - def __aiter__( - self, - ) -> AsyncIterator["BodyPartReader"]: - return self # type: ignore[return-value] - - async def __anext__( - self, - ) -> Optional[Union["MultipartReader", BodyPartReader]]: - part = await self.next() - if part is None: - raise StopAsyncIteration - return part - - @classmethod - def from_response( - cls, - response: "ClientResponse", - ) -> MultipartResponseWrapper: - """Constructs reader instance from HTTP response. - - :param response: :class:`~aiohttp.client.ClientResponse` instance - """ - obj = cls.response_wrapper_cls( - response, cls(response.headers, response.content) - ) - return obj - - def at_eof(self) -> bool: - """Returns True if the final boundary was reached, false otherwise.""" - return self._at_eof - - async def next( - self, - ) -> Optional[Union["MultipartReader", BodyPartReader]]: - """Emits the next multipart body part.""" - # So, if we're at BOF, we need to skip till the boundary. - if self._at_eof: - return None - await self._maybe_release_last_part() - if self._at_bof: - await self._read_until_first_boundary() - self._at_bof = False - else: - await self._read_boundary() - if self._at_eof: # we just read the last boundary, nothing to do there - return None - self._last_part = await self.fetch_next_part() - return self._last_part - - async def release(self) -> None: - """Reads all the body parts to the void till the final boundary.""" - while not self._at_eof: - item = await self.next() - if item is None: - break - await item.release() - - async def fetch_next_part( - self, - ) -> Union["MultipartReader", BodyPartReader]: - """Returns the next body part reader.""" - headers = await self._read_headers() - return self._get_part_reader(headers) - - def _get_part_reader( - self, - headers: "CIMultiDictProxy[str]", - ) -> Union["MultipartReader", BodyPartReader]: - """Dispatches the response by the `Content-Type` header. - - Returns a suitable reader instance. - - :param dict headers: Response headers - """ - ctype = headers.get(CONTENT_TYPE, "") - mimetype = parse_mimetype(ctype) - - if mimetype.type == "multipart": - if self.multipart_reader_cls is None: - return type(self)(headers, self._content) - return self.multipart_reader_cls(headers, self._content) - else: - return self.part_reader_cls(self._boundary, headers, self._content) - - def _get_boundary(self) -> str: - mimetype = parse_mimetype(self.headers[CONTENT_TYPE]) - - assert mimetype.type == "multipart", "multipart/* content type expected" - - if "boundary" not in mimetype.parameters: - raise ValueError( - "boundary missed for Content-Type: %s" % self.headers[CONTENT_TYPE] - ) - - boundary = mimetype.parameters["boundary"] - if len(boundary) > 70: - raise ValueError("boundary %r is too long (70 chars max)" % boundary) - - return boundary - - async def _readline(self) -> bytes: - if self._unread: - return self._unread.pop() - return await self._content.readline() - - async def _read_until_first_boundary(self) -> None: - while True: - chunk = await self._readline() - if chunk == b"": - raise ValueError( - "Could not find starting boundary %r" % (self._boundary) - ) - chunk = chunk.rstrip() - if chunk == self._boundary: - return - elif chunk == self._boundary + b"--": - self._at_eof = True - return - - async def _read_boundary(self) -> None: - chunk = (await self._readline()).rstrip() - if chunk == self._boundary: - pass - elif chunk == self._boundary + b"--": - self._at_eof = True - epilogue = await self._readline() - next_line = await self._readline() - - # the epilogue is expected and then either the end of input or the - # parent multipart boundary, if the parent boundary is found then - # it should be marked as unread and handed to the parent for - # processing - if next_line[:2] == b"--": - self._unread.append(next_line) - # otherwise the request is likely missing an epilogue and both - # lines should be passed to the parent for processing - # (this handles the old behavior gracefully) - else: - self._unread.extend([next_line, epilogue]) - else: - raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}") - - async def _read_headers(self) -> "CIMultiDictProxy[str]": - lines = [b""] - while True: - chunk = await self._content.readline() - chunk = chunk.strip() - lines.append(chunk) - if not chunk: - break - parser = HeadersParser() - headers, raw_headers = parser.parse_headers(lines) - return headers - - async def _maybe_release_last_part(self) -> None: - """Ensures that the last read body part is read completely.""" - if self._last_part is not None: - if not self._last_part.at_eof(): - await self._last_part.release() - self._unread.extend(self._last_part._unread) - self._last_part = None - - -_Part = Tuple[Payload, str, str] - - -class MultipartWriter(Payload): - """Multipart body writer.""" - - def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> None: - boundary = boundary if boundary is not None else uuid.uuid4().hex - # The underlying Payload API demands a str (utf-8), not bytes, - # so we need to ensure we don't lose anything during conversion. - # As a result, require the boundary to be ASCII only. - # In both situations. - - try: - self._boundary = boundary.encode("ascii") - except UnicodeEncodeError: - raise ValueError("boundary should contain ASCII only chars") from None - ctype = f"multipart/{subtype}; boundary={self._boundary_value}" - - super().__init__(None, content_type=ctype) - - self._parts: List[_Part] = [] - - def __enter__(self) -> "MultipartWriter": - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - pass - - def __iter__(self) -> Iterator[_Part]: - return iter(self._parts) - - def __len__(self) -> int: - return len(self._parts) - - def __bool__(self) -> bool: - return True - - _valid_tchar_regex = re.compile(rb"\A[!#$%&'*+\-.^_`|~\w]+\Z") - _invalid_qdtext_char_regex = re.compile(rb"[\x00-\x08\x0A-\x1F\x7F]") - - @property - def _boundary_value(self) -> str: - """Wrap boundary parameter value in quotes, if necessary. - - Reads self.boundary and returns a unicode sting. - """ - # Refer to RFCs 7231, 7230, 5234. - # - # parameter = token "=" ( token / quoted-string ) - # token = 1*tchar - # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - # obs-text = %x80-FF - # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - # / DIGIT / ALPHA - # ; any VCHAR, except delimiters - # VCHAR = %x21-7E - value = self._boundary - if re.match(self._valid_tchar_regex, value): - return value.decode("ascii") # cannot fail - - if re.search(self._invalid_qdtext_char_regex, value): - raise ValueError("boundary value contains invalid characters") - - # escape %x5C and %x22 - quoted_value_content = value.replace(b"\\", b"\\\\") - quoted_value_content = quoted_value_content.replace(b'"', b'\\"') - - return '"' + quoted_value_content.decode("ascii") + '"' - - @property - def boundary(self) -> str: - return self._boundary.decode("ascii") - - def append(self, obj: Any, headers: Optional[MultiMapping[str]] = None) -> Payload: - if headers is None: - headers = CIMultiDict() - - if isinstance(obj, Payload): - obj.headers.update(headers) - return self.append_payload(obj) - else: - try: - payload = get_payload(obj, headers=headers) - except LookupError: - raise TypeError("Cannot create payload from %r" % obj) - else: - return self.append_payload(payload) - - def append_payload(self, payload: Payload) -> Payload: - """Adds a new body part to multipart writer.""" - # compression - encoding: Optional[str] = payload.headers.get( - CONTENT_ENCODING, - "", - ).lower() - if encoding and encoding not in ("deflate", "gzip", "identity"): - raise RuntimeError(f"unknown content encoding: {encoding}") - if encoding == "identity": - encoding = None - - # te encoding - te_encoding: Optional[str] = payload.headers.get( - CONTENT_TRANSFER_ENCODING, - "", - ).lower() - if te_encoding not in ("", "base64", "quoted-printable", "binary"): - raise RuntimeError( - "unknown content transfer encoding: {}" "".format(te_encoding) - ) - if te_encoding == "binary": - te_encoding = None - - # size - size = payload.size - if size is not None and not (encoding or te_encoding): - payload.headers[CONTENT_LENGTH] = str(size) - - self._parts.append((payload, encoding, te_encoding)) # type: ignore[arg-type] - return payload - - def append_json( - self, obj: Any, headers: Optional[MultiMapping[str]] = None - ) -> Payload: - """Helper to append JSON part.""" - if headers is None: - headers = CIMultiDict() - - return self.append_payload(JsonPayload(obj, headers=headers)) - - def append_form( - self, - obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]], - headers: Optional[MultiMapping[str]] = None, - ) -> Payload: - """Helper to append form urlencoded part.""" - assert isinstance(obj, (Sequence, Mapping)) - - if headers is None: - headers = CIMultiDict() - - if isinstance(obj, Mapping): - obj = list(obj.items()) - data = urlencode(obj, doseq=True) - - return self.append_payload( - StringPayload( - data, headers=headers, content_type="application/x-www-form-urlencoded" - ) - ) - - @property - def size(self) -> Optional[int]: - """Size of the payload.""" - total = 0 - for part, encoding, te_encoding in self._parts: - if encoding or te_encoding or part.size is None: - return None - - total += int( - 2 - + len(self._boundary) - + 2 - + part.size # b'--'+self._boundary+b'\r\n' - + len(part._binary_headers) - + 2 # b'\r\n' - ) - - total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n' - return total - - async def write(self, writer: Any, close_boundary: bool = True) -> None: - """Write body.""" - for part, encoding, te_encoding in self._parts: - await writer.write(b"--" + self._boundary + b"\r\n") - await writer.write(part._binary_headers) - - if encoding or te_encoding: - w = MultipartPayloadWriter(writer) - if encoding: - w.enable_compression(encoding) - if te_encoding: - w.enable_encoding(te_encoding) - await part.write(w) # type: ignore[arg-type] - await w.write_eof() - else: - await part.write(writer) - - await writer.write(b"\r\n") - - if close_boundary: - await writer.write(b"--" + self._boundary + b"--\r\n") - - -class MultipartPayloadWriter: - def __init__(self, writer: Any) -> None: - self._writer = writer - self._encoding: Optional[str] = None - self._compress: Any = None - self._encoding_buffer: Optional[bytearray] = None - - def enable_encoding(self, encoding: str) -> None: - if encoding == "base64": - self._encoding = encoding - self._encoding_buffer = bytearray() - elif encoding == "quoted-printable": - self._encoding = "quoted-printable" - - def enable_compression( - self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY - ) -> None: - zlib_mode = 16 + zlib.MAX_WBITS if encoding == "gzip" else -zlib.MAX_WBITS - self._compress = zlib.compressobj(wbits=zlib_mode, strategy=strategy) - - async def write_eof(self) -> None: - if self._compress is not None: - chunk = self._compress.flush() - if chunk: - self._compress = None - await self.write(chunk) - - if self._encoding == "base64": - if self._encoding_buffer: - await self._writer.write(base64.b64encode(self._encoding_buffer)) - - async def write(self, chunk: bytes) -> None: - if self._compress is not None: - if chunk: - chunk = self._compress.compress(chunk) - if not chunk: - return - - if self._encoding == "base64": - buf = self._encoding_buffer - assert buf is not None - buf.extend(chunk) - - if buf: - div, mod = divmod(len(buf), 3) - enc_chunk, self._encoding_buffer = (buf[: div * 3], buf[div * 3 :]) - if enc_chunk: - b64chunk = base64.b64encode(enc_chunk) - await self._writer.write(b64chunk) - elif self._encoding == "quoted-printable": - await self._writer.write(binascii.b2a_qp(chunk)) - else: - await self._writer.write(chunk) diff --git a/spaces/codertoro/gpt-academic/crazy_functions/test_project/cpp/cppipc/policy.h b/spaces/codertoro/gpt-academic/crazy_functions/test_project/cpp/cppipc/policy.h deleted file mode 100644 index f88ab5d8cb343f97026966b402eaeed8831e356a..0000000000000000000000000000000000000000 --- a/spaces/codertoro/gpt-academic/crazy_functions/test_project/cpp/cppipc/policy.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include - -#include "libipc/def.h" -#include "libipc/prod_cons.h" - -#include "libipc/circ/elem_array.h" - -namespace ipc { -namespace policy { - -template